Last active
August 29, 2015 14:13
-
-
Save oprypin/3de6485bc57bee074a21 to your computer and use it in GitHub Desktop.
Negative indices workaround
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
proc `..<`(a, b: int): auto = | |
if a < 0: | |
raise newException(IndexError, "Left index == " & $a & ", out of range") | |
if b <= 0: | |
return 1 .. 0 | |
if a >= b: | |
return a .. <a | |
return a .. <b | |
proc `.!`(a, b: int): auto = | |
if a < 0: | |
raise newException(IndexError, "Left index == " & $a & ", out of range") | |
if b < 0: | |
return 1 .. 0 | |
if a > b: | |
return a .. <a | |
return a .. b | |
template asserr(x: expr): stmt {.immediate.}= | |
## assert that this expression produces an IndexError | |
try: | |
discard x | |
assert false | |
except IndexError: | |
discard | |
var s0: seq[int] = @[] | |
var s1 = @[0] | |
var s4 = @[0, 1, 2, 3] | |
assert s0[0 ..< 0] == @[] | |
assert s1[0 ..< 1] == @[0] | |
assert s4[0 ..< 0] == @[] | |
assert s1[1 ..< 1] == @[] | |
assert s4[1 ..< 2] == @[1] | |
assert s4[0 ..< 3] == @[0, 1, 2] | |
assert s4[0 ..< 4] == @[0, 1, 2, 3] | |
asserr s0[0 ..< 1] | |
asserr s1[-1 ..< 0] | |
asserr s4[0 ..< 100] | |
assert s0[0 .! -1] == @[] | |
assert s1[0 .! 0] == @[0] | |
assert s4[0 .! -1] == @[] | |
assert s1[1 .! 0] == @[] | |
assert s4[1 .! 1] == @[1] | |
assert s4[0 .! 2] == @[0, 1, 2] | |
assert s4[0 .! 3] == @[0, 1, 2, 3] | |
asserr s0[0 .! 0] | |
asserr s1[-1 .! -1] | |
asserr s4[0 .! 99] | |
assert s0[0 .. < 0] == @[] | |
assert s1[0 .. < 1] == @[0] | |
assert s4[0 .. < 0] == @[0, 1, 2, 3] | |
assert s1[1 .. < 1] == @[] | |
assert s4[1 .. < 2] == @[1] | |
assert s4[0 .. < 3] == @[0, 1, 2] | |
assert s4[0 .. < 4] == @[0, 1, 2, 3] | |
asserr s0[0 .. < 1] | |
assert s1[-1 .. < 0] == @[0] | |
asserr s4[0 .. < 100] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment