From 0ed883ef11dcf76e980aba4d15add106df3cfb39 Mon Sep 17 00:00:00 2001 From: cui fliter Date: Wed, 9 Sep 2026 16:57:29 +0800 Subject: [PATCH] algorithm: handle empty inputs in rotateLeft (#26191) `rotateLeft` and `rotatedLeft` raised `DivByZeroDefect` for empty containers because their whole-container overloads computed `dist mod arg.len` before checking for an empty input. Handle empty inputs explicitly: - `rotateLeft` returns `0` and leaves the container unchanged. - `rotatedLeft` returns an empty sequence. Add a regression test covering both overloads. The slice overloads are intentionally left unchanged because zero-length slice semantics need separate consideration. Signed-off-by: cuishuang --- lib/pure/algorithm.nim | 4 ++++ tests/stdlib/talgorithm.nim | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim index c38b4233c5..f86260328f 100644 --- a/lib/pure/algorithm.nim +++ b/lib/pure/algorithm.nim @@ -865,6 +865,8 @@ proc rotateLeft*[T](arg: var openArray[T]; dist: int): int {.discardable.} = a.rotateLeft(-6) assert a == [1, 2, 3, 4, 5] let argLen = arg.len + if argLen == 0: + return 0 let distLeft = ((dist mod argLen) + argLen) mod argLen arg.rotateInternal(0, distLeft, argLen) @@ -914,5 +916,7 @@ proc rotatedLeft*[T](arg: openArray[T]; dist: int): seq[T] = a = rotatedLeft(a, -6) assert a == @[1, 2, 3, 4, 5] let argLen = arg.len + if argLen == 0: + return newSeq[T]() let distLeft = ((dist mod argLen) + argLen) mod argLen arg.rotatedInternal(0, distLeft, argLen) diff --git a/tests/stdlib/talgorithm.nim b/tests/stdlib/talgorithm.nim index 589111b482..b04d43201f 100644 --- a/tests/stdlib/talgorithm.nim +++ b/tests/stdlib/talgorithm.nim @@ -74,6 +74,12 @@ block: doAssert s5.rotateLeft(3 ..< 10, 11) == 6 doAssert s5 == "xxxefgabcdxxx" + block: + var x: seq[int] = @[] + doAssert x.rotateLeft(1) == 0 + doAssert x == @[] + doAssert x.rotatedLeft(1) == @[] + block product: doAssert product(newSeq[seq[int]]()) == newSeq[seq[int]](), "empty input" doAssert product(@[newSeq[int](), @[], @[]]) == newSeq[seq[int]](), "bit more empty input"