mirror of
https://github.com/nim-lang/Nim.git
synced 2026-09-17 02:32:11 +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)
|
||||
|
||||
@@ -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"
|
||||
|
||||
Reference in New Issue
Block a user