File tree Expand file tree Collapse file tree 2 files changed +60
-1
lines changed
Expand file tree Collapse file tree 2 files changed +60
-1
lines changed Original file line number Diff line number Diff line change @@ -339,7 +339,36 @@ func (c *Ctrie) ReadOnlySnapshot() *Ctrie {
339339 }
340340}
341341
342- //func (c *Ctrie) Iterator()
342+ // Iterator returns a channel which yields the Entries of the Ctrie.
343+ func (c * Ctrie ) Iterator () <- chan * Entry {
344+ ch := make (chan * Entry )
345+ snapshot := c .ReadOnlySnapshot ()
346+ go func () {
347+ traverse (snapshot .root , ch )
348+ close (ch )
349+ }()
350+ return ch
351+ }
352+
353+ func traverse (i * iNode , ch chan <- * Entry ) {
354+ switch {
355+ case i .main .cNode != nil :
356+ for _ , br := range i .main .cNode .array {
357+ switch b := br .(type ) {
358+ case * iNode :
359+ traverse (b , ch )
360+ case * sNode :
361+ ch <- b .Entry
362+ }
363+ }
364+ case i .main .lNode != nil :
365+ for _ , e := range i .main .lNode .Map (func (sn interface {}) interface {} {
366+ return sn .(* sNode ).Entry
367+ }) {
368+ ch <- e .(* Entry )
369+ }
370+ }
371+ }
343372
344373func (c * Ctrie ) assertReadWrite () {
345374 if c .readOnly {
Original file line number Diff line number Diff line change @@ -253,6 +253,36 @@ func TestSnapshot(t *testing.T) {
253253 assert .Equal (0 , val )
254254}
255255
256+ func TestIterator (t * testing.T ) {
257+ assert := assert .New (t )
258+ ctrie := New (nil )
259+ for i := 0 ; i < 10 ; i ++ {
260+ ctrie .Insert ([]byte (strconv .Itoa (i )), i )
261+ }
262+ expected := map [string ]int {
263+ "0" : 0 ,
264+ "1" : 1 ,
265+ "2" : 2 ,
266+ "3" : 3 ,
267+ "4" : 4 ,
268+ "5" : 5 ,
269+ "6" : 6 ,
270+ "7" : 7 ,
271+ "8" : 8 ,
272+ "9" : 9 ,
273+ }
274+
275+ count := 0
276+ for entry := range ctrie .Iterator () {
277+ exp , ok := expected [string (entry .Key )]
278+ if assert .True (ok ) {
279+ assert .Equal (exp , entry .Value )
280+ }
281+ count ++
282+ }
283+ assert .Equal (len (expected ), count )
284+ }
285+
256286func BenchmarkInsert (b * testing.B ) {
257287 ctrie := New (nil )
258288 b .ResetTimer ()
You can’t perform that action at this time.
0 commit comments