From 3629d723288755f45e94c4c9fea1a92893455d0a Mon Sep 17 00:00:00 2001 From: Kyle Consalus Date: Tue, 8 Feb 2011 20:07:05 -0800 Subject: [PATCH] container/ring: Replace Iter() with Do(). Faster in most cases, and not prone to memory leaks. Named "Do" to match with similarly named method on Vector. R=gri CC=golang-dev https://golang.org/cl/4134046 --- src/pkg/container/ring/ring.go | 19 ++++++++----------- src/pkg/container/ring/ring_test.go | 14 ++------------ 2 files changed, 10 insertions(+), 23 deletions(-) diff --git a/src/pkg/container/ring/ring.go b/src/pkg/container/ring/ring.go index 335afbc3cc..5925164e9d 100644 --- a/src/pkg/container/ring/ring.go +++ b/src/pkg/container/ring/ring.go @@ -138,16 +138,13 @@ func (r *Ring) Len() int { } -func (r *Ring) Iter() <-chan interface{} { - c := make(chan interface{}) - go func() { - if r != nil { - c <- r.Value - for p := r.Next(); p != r; p = p.next { - c <- p.Value - } +// Do calls function f on each element of the ring, in forward order. +// The behavior of Do is undefined if f changes *r. +func (r *Ring) Do(f func(interface{})) { + if r != nil { + f(r.Value) + for p := r.Next(); p != r; p = p.next { + f(p.Value) } - close(c) - }() - return c + } } diff --git a/src/pkg/container/ring/ring_test.go b/src/pkg/container/ring/ring_test.go index ee3c411283..778c083d02 100644 --- a/src/pkg/container/ring/ring_test.go +++ b/src/pkg/container/ring/ring_test.go @@ -35,12 +35,12 @@ func verify(t *testing.T, r *Ring, N int, sum int) { // iteration n = 0 s := 0 - for p := range r.Iter() { + r.Do(func(p interface{}) { n++ if p != nil { s += p.(int) } - } + }) if n != N { t.Errorf("number of forward iterations == %d; expected %d", n, N) } @@ -128,16 +128,6 @@ func makeN(n int) *Ring { return r } - -func sum(r *Ring) int { - s := 0 - for p := range r.Iter() { - s += p.(int) - } - return s -} - - func sumN(n int) int { return (n*n + n) / 2 }