Skip to content

Commit cf6771a

Browse files
authored
add clear() method to HAMT that resets object to empty (#2095)
1 parent e9eef91 commit cf6771a

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

ipld/hamt/src/hamt.rs

+57
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,17 @@ where
336336
self.root.is_empty()
337337
}
338338

339+
/// Clears all entries in the HAMT and resets the root to an empty node.
340+
pub fn clear(&mut self) {
341+
// Check if the HAMT is already empty
342+
if self.is_empty() {
343+
return; // Avoid unnecessary root reset
344+
}
345+
346+
self.root = Node::default(); // Reset the root to an empty node
347+
self.flushed_cid = None; // Invalidate the flushed CID
348+
}
349+
339350
/// Iterates over each KV in the Hamt and runs a function on the values.
340351
///
341352
/// This function will constrain all values to be of the same type
@@ -534,3 +545,49 @@ where
534545
self.iter()
535546
}
536547
}
548+
549+
#[cfg(test)]
550+
mod tests {
551+
use super::*;
552+
use fvm_ipld_blockstore::MemoryBlockstore;
553+
554+
#[test]
555+
fn test_clear() {
556+
let store = MemoryBlockstore::default();
557+
let mut hamt: Hamt<_, _, usize> = Hamt::new_with_config(store, Config::default());
558+
559+
// Verify the HAMT is initially empty
560+
assert!(hamt.is_empty());
561+
562+
// Call clear on an already empty HAMT
563+
hamt.clear();
564+
565+
// Verify it is still empty
566+
assert!(hamt.is_empty());
567+
568+
// Insert some entries into the HAMT
569+
hamt.set(1, "a".to_string()).unwrap();
570+
hamt.set(2, "b".to_string()).unwrap();
571+
572+
// Verify the entries exist
573+
assert_eq!(hamt.get(&1).unwrap(), Some(&"a".to_string()));
574+
assert_eq!(hamt.get(&2).unwrap(), Some(&"b".to_string()));
575+
576+
// Verify the HAMT is not empty
577+
assert!(!hamt.is_empty());
578+
579+
// Clear the HAMT
580+
hamt.clear();
581+
582+
// Verify the HAMT is empty
583+
assert!(hamt.is_empty());
584+
585+
// Verify previous entries are gone
586+
assert_eq!(hamt.get(&1).unwrap(), None);
587+
assert_eq!(hamt.get(&2).unwrap(), None);
588+
589+
// Ensure subsequent operations still work
590+
hamt.set(3, "c".to_string()).unwrap();
591+
assert_eq!(hamt.get(&3).unwrap(), Some(&"c".to_string()));
592+
}
593+
}

0 commit comments

Comments
 (0)