From c4f0a62e84a2fc3d6484fea41324a6fe334c95ae Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Tue, 28 Oct 2014 05:07:55 -0700 Subject: [PATCH] sorted: add Foreach and ForeachInRange helpers Change-Id: Ifeba7ed6719468f01585aa7f7f9a9006fdd661de --- pkg/sorted/kv.go | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/pkg/sorted/kv.go b/pkg/sorted/kv.go index 4fb649a56..5d5cf2722 100644 --- a/pkg/sorted/kv.go +++ b/pkg/sorted/kv.go @@ -191,3 +191,24 @@ func NewKeyValue(cfg jsonconfig.Obj) (KeyValue, error) { } return s, cfg.Validate() } + +// Foreach runs fn for each key/value pair in kv. If fn returns an error, +// that same error is returned from Foreach and iteration stops. +func Foreach(kv KeyValue, fn func(key, value string) error) error { + return ForeachInRange(kv, "", "", fn) +} + +// ForeachInRange runs fn for each key/value pair in kv in the range +// of start and end, which behave the same as kv.Find. If fn returns +// an error, that same error is returned from Foreach and iteration +// stops. +func ForeachInRange(kv KeyValue, start, end string, fn func(key, value string) error) error { + it := kv.Find(start, end) + for it.Next() { + if err := fn(it.Key(), it.Value()); err != nil { + it.Close() + return err + } + } + return it.Close() +}