1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//! Utilities for loading JSON from the embedded filesystem.

use serde::de::DeserializeOwned;

use super::datastore::InternalData;

/// Possible errors generated when deserializing JSON data from memory
#[derive(Debug, thiserror::Error)]
pub enum InternalJsonLoadError {
    /// An error occurred with the JSON data itself
    #[error(transparent)]
    JsonError(#[from] serde_json::Error),

    /// The JSON data was not found in the internal data store
    #[error("Could not load embedded asset: {0}")]
    AssetNotFound(String),
}

/// Load an embedded JSON file
///
/// **This is a blocking function call**
/// 
/// ## Errors
///
/// This may raise an error either because the requested asset was not found, or because the JSON data could not be deserialized.
/// See [`InternalJsonLoadError`](enum.InternalJsonLoadError.html) for more information.
pub fn load_json_structure<'a, T: DeserializeOwned>(
    dist_path: &str,
) -> Result<T, InternalJsonLoadError> {
    // Load the json file from the embedded data as a string
    let data = InternalData::get(dist_path)
        .ok_or(InternalJsonLoadError::AssetNotFound(dist_path.to_string()))?
        .data;

    // Deserialize the json string into a rust structure
    let json_structure: T = serde_json::from_slice(&data)?;
    Ok(json_structure)
}