extendable_assets/asset/serialize/msgpack_backend.rs
1use crate::asset::{AssetSerializationBackend, SerializedAsset};
2
3/// MessagePack-based asset serialization backend.
4///
5/// This backend uses rmp_serde to serialize and deserialize assets in MessagePack format.
6/// MessagePack is a compact binary format that provides efficient serialization with
7/// smaller output sizes and faster processing compared to text-based formats like JSON.
8///
9/// # Performance Characteristics
10/// - Serialization: Fast speed, compact binary output
11/// - Deserialization: Fast speed, efficient memory usage
12/// - Storage: Space-efficient binary format, ideal for production environments
13///
14/// # Example
15/// ```rust
16/// # use extendable_assets::{AssetManager, FallbackFilesystem, MsgpackAssetSerializationBackend, 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 = MsgpackAssetSerializationBackend;
22/// // Use backend for serialization operations
23/// asset_manager.set_serialization_backend(Box::new(backend));
24/// ```
25pub struct MsgpackAssetSerializationBackend;
26
27impl AssetSerializationBackend for MsgpackAssetSerializationBackend {
28 /// Serializes a SerializedAsset to MessagePack bytes.
29 ///
30 /// Uses rmp_serde internally to convert the asset to a compact binary format.
31 /// MessagePack provides excellent space efficiency and fast serialization performance.
32 ///
33 /// # Arguments
34 /// * `asset` - The asset to serialize
35 ///
36 /// # Returns
37 /// A vector of bytes containing the MessagePack representation, or an error if
38 /// serialization fails (e.g., due to unsupported data types).
39 fn serialize(&self, asset: &SerializedAsset) -> anyhow::Result<Vec<u8>> {
40 // Use rmp_serde::to_vec for compact MessagePack binary output
41 Ok(rmp_serde::to_vec(asset)?)
42 }
43
44 /// Deserializes MessagePack bytes back into a SerializedAsset.
45 ///
46 /// Parses the provided MessagePack bytes and reconstructs a SerializedAsset.
47 /// The binary data must be valid MessagePack that matches the expected structure.
48 ///
49 /// # Arguments
50 /// * `bytes` - MessagePack bytes to deserialize
51 ///
52 /// # Returns
53 /// The reconstructed SerializedAsset, or an error if the data is corrupted
54 /// or doesn't match the expected MessagePack structure.
55 fn deserialize(&self, bytes: &[u8]) -> anyhow::Result<SerializedAsset> {
56 // Parse MessagePack from byte slice directly for efficiency
57 Ok(rmp_serde::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 = MsgpackAssetSerializationBackend;
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}