]> Cypherpunks repositories - gostls13.git/commitdiff
iterator for vector
authorRob Pike <r@golang.org>
Tue, 24 Mar 2009 00:46:59 +0000 (17:46 -0700)
committerRob Pike <r@golang.org>
Tue, 24 Mar 2009 00:46:59 +0000 (17:46 -0700)
R=rsc
DELTA=35  (35 added, 0 deleted, 0 changed)
OCL=26662
CL=26662

src/lib/container/vector.go
src/lib/container/vector_test.go

index 9e738ebef455a0c54cc7b100ad3c4455ecb69b04..673b47d0214762852f26d4f74091f8565e8fac13 100644 (file)
@@ -210,3 +210,19 @@ func (p *Vector) Swap(i, j int) {
        a := p.a;
        a[i], a[j] = a[j], a[i]
 }
+
+
+// Iterate over all elements; driver for range
+func (p *Vector) iterate(c chan Element) {
+       for i := 0; i < len(p.a); i++ {
+               c <- p.a[i]
+       }
+       close(c);
+}
+
+// Channel iterator for range.
+func (p *Vector) Iter() chan Element {
+       c := make(chan Element);
+       go p.iterate(c);
+       return c;
+}
index ac16709a0ecdc53b890427fdcf20474e61196753..7a56f3664f5c80f4af881e18cd3a4d8c72913006 100644 (file)
@@ -139,6 +139,7 @@ func TestInsertVector(t *testing.T) {
        verify_pattern(t, a, 8, 1000, 2);
 }
 
+
 func TestSorting(t *testing.T) {
        const n = 100;
        a := vector.NewIntVector(n);
@@ -170,3 +171,21 @@ func TestDo(t *testing.T) {
                t.Error("should visit", n, "values; did visit", count)
        }
 }
+
+func TestIter(t *testing.T) {
+       const Len = 100;
+       x := vector.New(Len);
+       for i := 0; i < Len; i++ {
+               x.Set(i, i*i);
+       }
+       i := 0;
+       for v := range x.Iter() {
+               if v.(int) != i*i {
+                       t.Error("Iter expected", i*i, "got", v.(int))
+               }
+               i++;
+       }
+       if i != Len {
+               t.Error("Iter stopped at", i, "not", Len)
+       }
+}