From be3bc0c43faa4abfc944f7961f9c2a6f4e34c343 Mon Sep 17 00:00:00 2001 From: Yusuf Efe <120668197+yuefdev@users.noreply.github.com> Date: Thu, 22 Oct 2026 05:34:04 +0300 Subject: [PATCH] fix(package): [iterator] report available elements in HasNext (#392) --- iterator/hasnext_exhaustion_test.go | 26 ++++++++++++++++++++++++++ iterator/operation.go | 15 +++++++++++++-- 2 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 iterator/hasnext_exhaustion_test.go diff --git a/iterator/hasnext_exhaustion_test.go b/iterator/hasnext_exhaustion_test.go new file mode 100644 index 0000000..f471d1d --- /dev/null +++ b/iterator/hasnext_exhaustion_test.go @@ -0,0 +1,26 @@ +package iterator + +import "testing" + +func TestTakeHasNextExhaustedSource(t *testing.T) { + it := Take[int](FromSlice([]int{1}), 3) + if value, ok := it.Next(); !ok || value != 1 { + t.Fatal("missing first value") + } + if it.HasNext() { + t.Error("exhausted source still reports an element") + } +} + +func TestFilterHasNextMatches(t *testing.T) { + it := Filter[int](FromSlice([]int{1, 2, 3}), func(value int) bool { return value%2 == 0 }) + if !it.HasNext() || !it.HasNext() { + t.Fatal("missing matching value") + } + if value, ok := it.Next(); !ok || value != 2 { + t.Fatal("HasNext consumed the matching value") + } + if it.HasNext() { + t.Error("unmatched tail reported as another element") + } +} diff --git a/iterator/operation.go b/iterator/operation.go index 6340c5a..4be7b6c 100644 --- a/iterator/operation.go +++ b/iterator/operation.go @@ -44,9 +44,17 @@ func Filter[T any](iter Iterator[T], predicateFunc func(item T) bool) Iterator[T type filterIterator[T any] struct { iter Iterator[T] predicateFunc func(T) bool + next T + ready bool } func (fr *filterIterator[T]) Next() (T, bool) { + if fr.ready { + item := fr.next + var zero T + fr.next, fr.ready = zero, false + return item, true + } for item, ok := fr.iter.Next(); ok; item, ok = fr.iter.Next() { if fr.predicateFunc(item) { return item, true @@ -57,7 +65,10 @@ func (fr *filterIterator[T]) Next() (T, bool) { } func (fr *filterIterator[T]) HasNext() bool { - return fr.iter.HasNext() + if !fr.ready { + fr.next, fr.ready = fr.Next() + } + return fr.ready } // Join creates an iterator that join all elements of iters[0], then all elements of iters[1] and so on. @@ -135,5 +146,5 @@ func (iter *takeIterator[T]) Next() (T, bool) { } func (iter *takeIterator[T]) HasNext() bool { - return iter.num > 0 + return iter.num > 0 && iter.it.HasNext() }