diff options
author | Heiko Nickerl <dev@hnicke.de> | 2021-06-20 17:56:33 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-06-20 08:56:33 -0700 |
commit | 92cb765714325703d1a8e1b0409bfcd1b17af103 (patch) | |
tree | 42d0acf856e744f6105fb16c9b57bbbd0d065b6e /lib/system.nim | |
parent | eb0b323f452f5f06d74a4f747c50ae5115e44eae (diff) | |
download | Nim-92cb765714325703d1a8e1b0409bfcd1b17af103.tar.gz |
Raise IndexDefect when deleting element at out of bounds index (#17821)
Co-authored-by: Timothee Cour <timothee.cour2@gmail.com> Co-authored-by: Heiko Nickerl <mail@hnicke.de> Co-authored-by: Heiko Nickerl <heiko.nickerl@flipapp.de>
Diffstat (limited to 'lib/system.nim')
-rw-r--r-- | lib/system.nim | 58 |
1 files changed, 34 insertions, 24 deletions
diff --git a/lib/system.nim b/lib/system.nim index cae0ec3e2..a4608997a 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -1325,30 +1325,6 @@ proc del*[T](x: var seq[T], i: Natural) {.noSideEffect.} = movingCopy(x[i], x[xl]) setLen(x, xl) -proc delete*[T](x: var seq[T], i: Natural) {.noSideEffect.} = - ## Deletes the item at index `i` by moving all `x[i+1..]` items by one position. - ## - ## This is an `O(n)` operation. - ## - ## See also: - ## * `del <#del,seq[T],Natural>`_ for O(1) operation - ## - ## .. code-block:: Nim - ## var i = @[1, 2, 3, 4, 5] - ## i.delete(2) # => @[1, 2, 4, 5] - template defaultImpl = - let xl = x.len - for j in i.int..xl-2: movingCopy(x[j], x[j+1]) - setLen(x, xl-1) - - when nimvm: - defaultImpl() - else: - when defined(js): - {.emit: "`x`.splice(`i`, 1);".} - else: - defaultImpl() - proc insert*[T](x: var seq[T], item: sink T, i = 0.Natural) {.noSideEffect.} = ## Inserts `item` into `x` at position `i`. ## @@ -2154,6 +2130,40 @@ const import system/dollars export dollars +proc delete*[T](x: var seq[T], i: Natural) {.noSideEffect.} = + ## Deletes the item at index `i` by moving all `x[i+1..^1]` items by one position. + ## + ## This is an `O(n)` operation. + ## + ## See also: + ## * `del <#del,seq[T],Natural>`_ for O(1) operation + ## + runnableExamples: + var s = @[1, 2, 3, 4, 5] + s.delete(2) + doAssert s == @[1, 2, 4, 5] + + doAssertRaises(IndexDefect): + s.delete(4) + + if i > high(x): + # xxx this should call `raiseIndexError2(i, high(x))` after some refactoring + raise (ref IndexDefect)(msg: "index out of bounds: '" & $i & "' < '" & $x.len & "' failed") + + template defaultImpl = + let xl = x.len + for j in i.int..xl-2: movingCopy(x[j], x[j+1]) + setLen(x, xl-1) + + when nimvm: + defaultImpl() + else: + when defined(js): + {.emit: "`x`.splice(`i`, 1);".} + else: + defaultImpl() + + const NimVersion*: string = $NimMajor & "." & $NimMinor & "." & $NimPatch ## is the version of Nim as a string. |