@@ -123,12 +123,12 @@ func (file *File) Delete() {
123
123
124
124
// Len returns the File's size - that is, the maximum key in the tree of line
125
125
// intervals.
126
- func (file * File ) Len () int {
126
+ func (file File ) Len () int {
127
127
return int (file .tree .Max ().Item ().Key )
128
128
}
129
129
130
130
// Nodes returns the number of RBTree nodes in the file.
131
- func (file * File ) Nodes () int {
131
+ func (file File ) Nodes () int {
132
132
return file .tree .Len ()
133
133
}
134
134
@@ -327,18 +327,11 @@ func (file *File) Merge(day int, others ...*File) {
327
327
328
328
// Dump formats the underlying line interval tree into a string.
329
329
// Useful for error messages, panic()-s and debugging.
330
- func (file * File ) Dump () string {
330
+ func (file File ) Dump () string {
331
331
buffer := ""
332
- for iter := file .tree .Min (); ! iter .Limit (); iter = iter .Next () {
333
- node := iter .Item ()
334
- var val int
335
- if node .Value == math .MaxUint32 {
336
- val = - 1
337
- } else {
338
- val = int (node .Value )
339
- }
340
- buffer += fmt .Sprintf ("%d %d\n " , node .Key , val )
341
- }
332
+ file .ForEach (func (line , value int ) {
333
+ buffer += fmt .Sprintf ("%d %d\n " , line , value )
334
+ })
342
335
return buffer
343
336
}
344
337
@@ -351,7 +344,7 @@ func (file *File) Dump() string {
351
344
// which marks the ending of the last line interval.
352
345
//
353
346
// 3. Node keys must monotonically increase and never duplicate.
354
- func (file * File ) Validate () {
347
+ func (file File ) Validate () {
355
348
if file .tree .Min ().Item ().Key != 0 {
356
349
log .Panic ("the tree must start with key 0" )
357
350
}
@@ -371,6 +364,21 @@ func (file *File) Validate() {
371
364
}
372
365
}
373
366
367
+ // ForEach visits each node in the underlying tree, in ascending key order.
368
+ func (file File ) ForEach (callback func (line , value int )) {
369
+ for iter := file .tree .Min (); ! iter .Limit (); iter = iter .Next () {
370
+ item := iter .Item ()
371
+ key := int (item .Key )
372
+ var value int
373
+ if item .Value == math .MaxUint32 {
374
+ value = - 1
375
+ } else {
376
+ value = int (item .Value )
377
+ }
378
+ callback (key , value )
379
+ }
380
+ }
381
+
374
382
// flatten represents the file as a slice of lines, each line's value being the corresponding day.
375
383
func (file * File ) flatten () []int {
376
384
lines := make ([]int , 0 , file .Len ())
0 commit comments