Skip to content

Commit e9eef91

Browse files
authored
feat: kamt: Add public fn clear to reset and clear all entries in KAMT (#2092)
1 parent 2b54219 commit e9eef91

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

ipld/kamt/src/kamt.rs

+52
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,17 @@ where
130130
pub fn is_empty(&self) -> bool {
131131
self.root.is_empty()
132132
}
133+
134+
/// Clears all entries in the KAMT and resets the root to an empty node.
135+
pub fn clear(&mut self) {
136+
// Check if the KAMT is already empty
137+
if self.is_empty() {
138+
return; // Avoid unnecessary root reset
139+
}
140+
141+
self.root = Node::default(); // Reset the root to an empty node
142+
self.flushed_cid = None; // Invalidate the flushed CID
143+
}
133144
}
134145

135146
impl<BS, K, V, H, const N: usize> Kamt<BS, K, V, H, N>
@@ -549,4 +560,45 @@ mod tests {
549560

550561
Ok(())
551562
}
563+
564+
#[test]
565+
fn test_clear() {
566+
let store = MemoryBlockstore::default();
567+
let mut kamt: Kamt<_, u32, String, Identity> =
568+
Kamt::new_with_config(store, Config::default());
569+
570+
// Verify the KAMT is initially empty
571+
assert!(kamt.is_empty());
572+
573+
// Call clear on an already empty KAMT
574+
kamt.clear();
575+
576+
// Verify it is still empty
577+
assert!(kamt.is_empty());
578+
579+
// Insert some entries into the KAMT
580+
kamt.set(1, "a".to_string()).unwrap();
581+
kamt.set(2, "b".to_string()).unwrap();
582+
583+
// Verify the entries exist
584+
assert_eq!(kamt.get(&1).unwrap(), Some(&"a".to_string()));
585+
assert_eq!(kamt.get(&2).unwrap(), Some(&"b".to_string()));
586+
587+
// Verify the KAMT is not empty
588+
assert!(!kamt.is_empty());
589+
590+
// Clear the KAMT
591+
kamt.clear();
592+
593+
// Verify the KAMT is empty
594+
assert!(kamt.is_empty());
595+
596+
// Verify previous entries are gone
597+
assert_eq!(kamt.get(&1).unwrap(), None);
598+
assert_eq!(kamt.get(&2).unwrap(), None);
599+
600+
// Ensure subsequent operations still work
601+
kamt.set(3, "c".to_string()).unwrap();
602+
assert_eq!(kamt.get(&3).unwrap(), Some(&"c".to_string()));
603+
}
552604
}

0 commit comments

Comments
 (0)