junobuild_storage/
stable_utils.rs

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
use crate::types::state::FullPath;
use crate::types::store::{Asset, AssetEncoding};
use ic_stable_structures::{StableBTreeMap, Storable};
use junobuild_shared::serializers::serialize_to_bytes;
use junobuild_shared::types::core::Blob;
use junobuild_shared::types::memory::Memory;
use serde::Serialize;

pub fn insert_asset_encoding_stable<K>(
    full_path: &FullPath,
    encoding_type: &str,
    encoding: &AssetEncoding,
    asset: &mut Asset,
    stable_encoding_chunk_key: impl Fn(&FullPath, &str, usize) -> K,
    chunks: &mut StableBTreeMap<K, Blob, Memory>,
) where
    K: Clone + Serialize + Storable + Ord,
{
    let mut content_chunks = Vec::new();

    // Insert each chunk into the StableBTreeMap
    for (i, chunk) in encoding.content_chunks.iter().enumerate() {
        let key = stable_encoding_chunk_key(full_path, encoding_type, i);

        chunks.insert(key.clone(), chunk.clone());

        content_chunks.push(serialize_to_bytes(&key).into_owned());
    }

    // Insert the encoding by replacing the chunks with their referenced keys serialized
    asset.encodings.insert(
        encoding_type.to_owned(),
        AssetEncoding {
            content_chunks,
            ..encoding.clone()
        },
    );
}