state_tree/
lib.rs

1pub mod patch;
2pub mod tree;
3pub mod tree_diff;
4
5use crate::tree::{
6    SizedType, StateTree, StateTreeSkeleton, deserialize_tree_untagged, serialize_tree_untagged,
7};
8
9pub fn update_state_storage<T: SizedType + PartialEq>(
10    old: &[u64],
11    old_state_skeleton: StateTreeSkeleton<T>,
12    new_state_skeleton: StateTreeSkeleton<T>,
13) -> Result<Option<Vec<u64>>, Box<dyn std::error::Error>> {
14    if old_state_skeleton == new_state_skeleton {
15        return Ok(None);
16    }
17    let target_tree = deserialize_tree_untagged(old, &old_state_skeleton)
18        .ok_or("Failed to deserialize old state tree")?;
19    let totalsize = new_state_skeleton.total_size();
20    let patches = tree_diff::take_diff(&old_state_skeleton, &new_state_skeleton)
21        .into_iter()
22        .collect::<Vec<_>>();
23    let mut new_tree = StateTree::from(new_state_skeleton);
24
25    for patch in &patches {
26        log::debug!("Patch: {patch:?}");
27    }
28    patch::apply_patches(&mut new_tree, &target_tree, patches.as_slice());
29
30    let res = serialize_tree_untagged(new_tree);
31    debug_assert_eq!(res.len(), totalsize as usize);
32
33    Ok(Some(res))
34}