@@ -130,6 +130,17 @@ where
130
130
pub fn is_empty ( & self ) -> bool {
131
131
self . root . is_empty ( )
132
132
}
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
+ }
133
144
}
134
145
135
146
impl < BS , K , V , H , const N : usize > Kamt < BS , K , V , H , N >
@@ -549,4 +560,45 @@ mod tests {
549
560
550
561
Ok ( ( ) )
551
562
}
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
+ }
552
604
}
0 commit comments