From 098e423d39a697717ceff01b9f4d4e0d58ef422d Mon Sep 17 00:00:00 2001 From: Fabio Falzoi Date: Tue, 2 Apr 2024 18:38:13 +0200 Subject: [PATCH 1/2] Fix wording of Filter iterator docstring Filter iterator ranges over the objects and skips the ones for which the predicate is not true. The commit fixes the wording of the function docstring that was stating the opposite. Signed-off-by: Fabio Falzoi --- iterator.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/iterator.go b/iterator.go index 2494256..db4617e 100644 --- a/iterator.go +++ b/iterator.go @@ -76,7 +76,7 @@ func (it *mapIterator[In, Out]) Next() (out Out, revision Revision, ok bool) { return } -// Filter skips objects for which the supplied predicate returns true +// Filter includes objects for which the supplied predicate returns true func Filter[Obj any, It Iterator[Obj]](iter It, pred func(Obj) bool) Iterator[Obj] { return &filterIterator[Obj]{ iter: iter, From 9b373107310e2e3606a3a3c57f8173b05036ffc3 Mon Sep 17 00:00:00 2001 From: Fabio Falzoi Date: Tue, 2 Apr 2024 19:04:31 +0200 Subject: [PATCH 2/2] Add a simple test for Filter iterator Add a simple unit test to validate the Filter iterator semantic. Signed-off-by: Fabio Falzoi --- iterator_test.go | 56 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 iterator_test.go diff --git a/iterator_test.go b/iterator_test.go new file mode 100644 index 0000000..d21fc02 --- /dev/null +++ b/iterator_test.go @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright Authors of Cilium + +package statedb + +import ( + "testing" + + "github.com/cilium/statedb/index" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestFilter(t *testing.T) { + type testObject struct { + ID int + } + + db, _ := NewDB(nil, NewExpVarMetrics(false)) + idIndex := Index[*testObject, int]{ + Name: "id", + FromObject: func(t *testObject) index.KeySet { + return index.NewKeySet(index.Int(t.ID)) + }, + FromKey: index.Int, + Unique: true, + } + table, _ := NewTable("test", idIndex) + require.NoError(t, db.RegisterTable(table)) + + txn := db.WriteTxn(table) + table.Insert(txn, &testObject{ID: 1}) + table.Insert(txn, &testObject{ID: 2}) + table.Insert(txn, &testObject{ID: 3}) + table.Insert(txn, &testObject{ID: 4}) + table.Insert(txn, &testObject{ID: 5}) + txn.Commit() + + iter, _ := table.All(db.ReadTxn()) + filtered := CollectSet( + Map( + Filter( + iter, + func(obj *testObject) bool { + return obj.ID%2 == 0 + }, + ), + func(obj *testObject) int { + return obj.ID + }, + ), + ) + assert.Len(t, filtered, 2) + assert.True(t, filtered.Has(2)) + assert.True(t, filtered.Has(4)) +}