Skip to main content

icydb_core/patch/
list.rs

1use candid::CandidType;
2use serde::{Deserialize, Serialize};
3
4///
5/// ListPatch
6///
7/// Positional list patches applied in order.
8/// Indices refer to the list state at the time each patch executes.
9/// `Insert` clamps out-of-bounds indices to the tail; `Remove` ignores invalid indices.
10/// `Update` only applies to existing elements and never creates new entries.
11/// `Overwrite` replaces the entire list with the provided values.
12///
13
14#[derive(CandidType, Clone, Debug, Deserialize, Serialize)]
15pub enum ListPatch<U> {
16    Update { index: usize, patch: U },
17    Insert { index: usize, value: U },
18    Push { value: U },
19    Overwrite { values: Vec<U> },
20    Remove { index: usize },
21    Clear,
22}
23
24///
25/// TESTS
26///
27
28#[cfg(test)]
29mod tests {
30    use super::*;
31    use crate::traits::UpdateView;
32
33    #[test]
34    fn vec_partial_patches() {
35        let mut values = vec![10u8, 20, 30];
36        let patches = vec![
37            ListPatch::Update {
38                index: 1,
39                patch: 99,
40            },
41            ListPatch::Insert {
42                index: 1,
43                value: 11,
44            },
45            ListPatch::Remove { index: 0 },
46        ];
47
48        values
49            .merge(patches)
50            .expect("list patch merge should succeed");
51
52        assert_eq!(values, vec![11, 99, 30]);
53    }
54
55    #[test]
56    fn vec_overwrite_replaces_contents() {
57        let mut values = vec![1u8, 2, 3];
58        let patches = vec![ListPatch::Overwrite {
59            values: vec![9u8, 8],
60        }];
61
62        values
63            .merge(patches)
64            .expect("list patch merge should succeed");
65
66        assert_eq!(values, vec![9, 8]);
67    }
68}