mirror of
https://github.com/nim-lang/Nim.git
synced 2026-09-17 18:44:53 +00:00
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 <imcusg@gmail.com>
This commit is contained in:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user