File tree Expand file tree Collapse file tree 2 files changed +35
-0
lines changed
Expand file tree Collapse file tree 2 files changed +35
-0
lines changed Original file line number Diff line number Diff line change @@ -339,6 +339,21 @@ func (c *Ctrie) ReadOnlySnapshot() *Ctrie {
339339 }
340340}
341341
342+ // Clear removes all keys from the Ctrie.
343+ func (c * Ctrie ) Clear () {
344+ for {
345+ root := c .readRoot ()
346+ gen := & generation {}
347+ newRoot := & iNode {
348+ main : & mainNode {cNode : & cNode {array : make ([]branch , 0 ), gen : gen }},
349+ gen : gen ,
350+ }
351+ if c .rdcssRoot (root , gcasRead (root , c ), newRoot ) {
352+ return
353+ }
354+ }
355+ }
356+
342357// Iterator returns a channel which yields the Entries of the Ctrie.
343358func (c * Ctrie ) Iterator () <- chan * Entry {
344359 ch := make (chan * Entry )
@@ -352,6 +367,11 @@ func (c *Ctrie) Iterator() <-chan *Entry {
352367
353368// Size returns the number of keys in the Ctrie.
354369func (c * Ctrie ) Size () uint {
370+ // TODO: The size operation can be optimized further by caching the size
371+ // information in main nodes of a read-only Ctrie – this reduces the
372+ // amortized complexity of the size operation to O(1) because the size
373+ // computation is amortized across the update operations that occurred
374+ // since the last snapshot.
355375 size := uint (0 )
356376 for _ = range c .Iterator () {
357377 size ++
Original file line number Diff line number Diff line change @@ -291,6 +291,21 @@ func TestSize(t *testing.T) {
291291 assert .Equal (t , uint (10 ), ctrie .Size ())
292292}
293293
294+ func TestClear (t * testing.T ) {
295+ assert := assert .New (t )
296+ ctrie := New (nil )
297+ for i := 0 ; i < 10 ; i ++ {
298+ ctrie .Insert ([]byte (strconv .Itoa (i )), i )
299+ }
300+ assert .Equal (uint (10 ), ctrie .Size ())
301+ snapshot := ctrie .Snapshot ()
302+
303+ ctrie .Clear ()
304+
305+ assert .Equal (uint (0 ), ctrie .Size ())
306+ assert .Equal (uint (10 ), snapshot .Size ())
307+ }
308+
294309func BenchmarkInsert (b * testing.B ) {
295310 ctrie := New (nil )
296311 b .ResetTimer ()
You can’t perform that action at this time.
0 commit comments