diff --git a/stream/limit_capacity_test.go b/stream/limit_capacity_test.go new file mode 100644 index 0000000..6c88741 --- /dev/null +++ b/stream/limit_capacity_test.go @@ -0,0 +1,13 @@ +package stream + +import ( + "math" + "testing" +) + +func TestLimitLargerThanSource(t *testing.T) { + got := Of(1, 2).Limit(math.MaxInt).ToSlice() + if len(got) != 2 || got[0] != 1 || got[1] != 2 { + t.Errorf("unexpected limited stream: %v", got) + } +} diff --git a/stream/stream.go b/stream/stream.go index 7c2acd8..a4797de 100644 --- a/stream/stream.go +++ b/stream/stream.go @@ -219,6 +219,9 @@ func (s Stream[T]) Limit(maxSize int) Stream[T] { if maxSize < 0 { return FromSlice([]T{}) } + if maxSize > len(s.source) { + maxSize = len(s.source) + } source := make([]T, 0, maxSize)