Skip to main content

icydb_core/patch/
list.rs

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