From 8225b6d7d9d1301ab47793040864779c170287a3 Mon Sep 17 00:00:00 2001 From: Yusuf Efe <120668197+yuefdev@users.noreply.github.com> Date: Thu, 22 Oct 2026 05:40:12 +0300 Subject: [PATCH] fix(package): [stream] avoid overflowing range arithmetic (#393) --- stream/range_overflow_test.go | 13 +++++++++++++ stream/stream.go | 13 ++++++++----- 2 files changed, 21 insertions(+), 5 deletions(-) create mode 100644 stream/range_overflow_test.go diff --git a/stream/range_overflow_test.go b/stream/range_overflow_test.go new file mode 100644 index 0000000..b784fce --- /dev/null +++ b/stream/range_overflow_test.go @@ -0,0 +1,13 @@ +package stream + +import "testing" + +func TestFromRangeSmallIntegerSpan(t *testing.T) { + got := FromRange[int8](-120, 120, 10).ToSlice() + if len(got) != 25 || got[0] != -120 || got[len(got)-1] != 120 { + t.Errorf("unexpected range: %v", got) + } + if got := FromRange[uint8](250, 255, 5).ToSlice(); len(got) != 2 || got[1] != 255 { + t.Errorf("unexpected unsigned range: %v", got) + } +} diff --git a/stream/stream.go b/stream/stream.go index a4797de..ddf7ec4 100644 --- a/stream/stream.go +++ b/stream/stream.go @@ -101,11 +101,14 @@ func FromRange[T constraints.Integer | constraints.Float](start, end, step T) St panic("stream.FromRange: param step should be positive") } - l := int((end-start)/step) + 1 - source := make([]T, l) - - for i := 0; i < l; i++ { - source[i] = start + (T(i) * step) + source := make([]T, 0) + for value := start; value <= end; { + source = append(source, value) + next := value + step + if next <= value { + break + } + value = next } return FromSlice(source)