extendable_assets/asset/serialize/json_backend.rs
1use crate::asset::{AssetSerializationBackend, SerializedAsset};
2
3/// JSON-based asset serialization backend.
4///
5/// This backend uses serde_json to serialize and deserialize assets in JSON format.
6/// JSON is human-readable and widely supported, making it ideal for debugging,
7/// configuration files, and interoperability with other systems.
8///
9/// # Performance Characteristics
10/// - Serialization: Moderate speed, larger output size due to text format
11/// - Deserialization: Moderate speed, good error reporting
12/// - Storage: Human-readable but less space-efficient than binary formats
13///
14/// # Example
15/// ```rust
16/// # use extendable_assets::{AssetManager, FallbackFilesystem, JsonAssetSerializationBackend, AssetSerializationBackend, SerializedAsset};
17/// # use std::sync::Arc;
18/// # let fs = FallbackFilesystem::new(Vec::new());
19/// # let mut asset_manager = AssetManager::new(Arc::new(fs));
20///
21/// let backend = JsonAssetSerializationBackend;
22/// // Use backend for serialization operations
23/// asset_manager.set_serialization_backend(Box::new(backend));
24/// ```
25pub struct JsonAssetSerializationBackend;
26
27impl AssetSerializationBackend for JsonAssetSerializationBackend {
28 /// Serializes a SerializedAsset to JSON bytes.
29 ///
30 /// Uses serde_json internally to convert the asset to a JSON byte vector.
31 /// The resulting JSON will be compact (no pretty-printing) for efficiency.
32 ///
33 /// # Arguments
34 /// * `asset` - The asset to serialize
35 ///
36 /// # Returns
37 /// A vector of bytes containing the JSON representation, or an error if
38 /// serialization fails (e.g., due to invalid UTF-8 in string fields).
39 fn serialize(&self, asset: &SerializedAsset) -> anyhow::Result<Vec<u8>> {
40 // Use serde_json::to_vec for compact JSON output
41 Ok(serde_json::to_vec(asset)?)
42 }
43
44 /// Deserializes JSON bytes back into a SerializedAsset.
45 ///
46 /// Parses the provided JSON bytes and reconstructs a SerializedAsset.
47 /// The JSON must match the expected SerializedAsset structure.
48 ///
49 /// # Arguments
50 /// * `bytes` - JSON bytes to deserialize
51 ///
52 /// # Returns
53 /// The reconstructed SerializedAsset, or an error if the JSON is malformed
54 /// or doesn't match the expected structure.
55 fn deserialize(&self, bytes: &[u8]) -> anyhow::Result<SerializedAsset> {
56 // Parse JSON from byte slice directly for efficiency
57 Ok(serde_json::from_slice(bytes)?)
58 }
59}
60
61#[cfg(test)]
62mod test {
63 use super::*;
64 use crate::asset::SerializedData;
65 use rand::prelude::*;
66
67 #[test]
68 fn serialize_deserialize_asset() {
69 let backend = JsonAssetSerializationBackend;
70
71 let asset_type = (0..10)
72 .map(|_| rand::rng().random_range('a'..='z'))
73 .collect::<String>();
74 let data: [u8; 128] = rand::rng().random();
75 let asset = SerializedAsset {
76 id: rand::rng().random(),
77 asset_type,
78 data: SerializedData::Uncompressed(Vec::from(data)),
79 };
80 let serialized = backend.serialize(&asset).unwrap();
81 let deserialized = backend.deserialize(&serialized).unwrap();
82 assert_eq!(asset, deserialized);
83 }
84}