diff --git a/ipld/kamt/src/kamt.rs b/ipld/kamt/src/kamt.rs index 5366704ad..7742b6157 100644 --- a/ipld/kamt/src/kamt.rs +++ b/ipld/kamt/src/kamt.rs @@ -130,6 +130,12 @@ where pub fn is_empty(&self) -> bool { self.root.is_empty() } + + /// Clears all entries in the KAMT and resets the root to an empty node. + pub fn clear(&mut self) { + self.root = Node::default(); // Reset the root to an empty node + self.flushed_cid = None; // Invalidate the flushed CID + } } impl Kamt @@ -549,4 +555,36 @@ mod tests { Ok(()) } + + #[test] + fn test_clear() { + let store = MemoryBlockstore::default(); + let mut kamt: Kamt<_, u32, String, Identity> = Kamt::new_with_config(store, Config::default()); + + + // Insert some entries into the KAMT + kamt.set(1, "a".to_string()).unwrap(); + kamt.set(2, "b".to_string()).unwrap(); + + // Verify the entries exist + assert_eq!(kamt.get(&1).unwrap(), Some(&"a".to_string())); + assert_eq!(kamt.get(&2).unwrap(), Some(&"b".to_string())); + + // Verify the KAMT is not empty + assert_eq!(kamt.is_empty(), false); + + // Clear the KAMT + kamt.clear(); + + // Verify the KAMT is empty + assert_eq!(kamt.is_empty(), true); + + // Verify previous entries are gone + assert_eq!(kamt.get(&1).unwrap(), None); + assert_eq!(kamt.get(&2).unwrap(), None); + + // Ensure subsequent operations still work + kamt.set(3, "c".to_string()).unwrap(); + assert_eq!(kamt.get(&3).unwrap(), Some(&"c".to_string())); + } }