junobuild_storage/
stable_utils.rs

1use crate::types::state::FullPath;
2use crate::types::store::{Asset, AssetEncoding};
3use ic_stable_structures::{StableBTreeMap, Storable};
4use junobuild_shared::memory::serializers::serialize_to_bytes;
5use junobuild_shared::types::core::Blob;
6use junobuild_shared::types::memory::Memory;
7use serde::Serialize;
8
9pub fn insert_asset_encoding_stable<K>(
10    full_path: &FullPath,
11    encoding_type: &str,
12    encoding: &AssetEncoding,
13    asset: &mut Asset,
14    stable_encoding_chunk_key: impl Fn(&FullPath, &str, usize) -> K,
15    chunks: &mut StableBTreeMap<K, Blob, Memory>,
16) where
17    K: Clone + Serialize + Storable + Ord,
18{
19    let mut content_chunks = Vec::new();
20
21    // Insert each chunk into the StableBTreeMap
22    for (i, chunk) in encoding.content_chunks.iter().enumerate() {
23        let key = stable_encoding_chunk_key(full_path, encoding_type, i);
24
25        chunks.insert(key.clone(), chunk.clone());
26
27        content_chunks.push(serialize_to_bytes(&key).into_owned());
28    }
29
30    // Insert the encoding by replacing the chunks with their referenced keys serialized
31    asset.encodings.insert(
32        encoding_type.to_owned(),
33        AssetEncoding {
34            content_chunks,
35            ..encoding.clone()
36        },
37    );
38}