From f6dae4edbcd541d06b204dd85f76694256f8f70d Mon Sep 17 00:00:00 2001 From: Zahary Karadjov Date: Sat, 23 Jun 2018 16:25:33 +0300 Subject: [PATCH] bugfix: allow the slice operators to return empty ranges --- ranges/bitranges.nim | 5 +++-- ranges/typedranges.nim | 7 ++++++- tests/ttypedranges.nim | 5 ++++- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/ranges/bitranges.nim b/ranges/bitranges.nim index d796d14..05c6fde 100644 --- a/ranges/bitranges.nim +++ b/ranges/bitranges.nim @@ -137,8 +137,9 @@ proc `[]`*(x: BitRange, idx: int): bool {.inline.} = proc sliceNormalized(x: BitRange, ibegin, iend: int): BitRange = assert ibegin >= 0 and ibegin < x.len and - iend >= ibegin and - iend < x.len + iend < x.len and + iend + 1 >= ibegin # the +1 here allows the result to be + # an empty range result.data = x.data result.start = x.start + ibegin diff --git a/ranges/typedranges.nim b/ranges/typedranges.nim index 8cb7a4b..daa4519 100644 --- a/ranges/typedranges.nim +++ b/ranges/typedranges.nim @@ -113,7 +113,12 @@ proc `$`*(r: Range): string = result &= "]" proc sliceNormalized[T](r: Range[T], ibegin, iend: int): Range[T] = - assert(ibegin >= 0 and ibegin < r.len and iend >= ibegin and iend < r.len) + assert ibegin >= 0 and + ibegin < r.len and + iend < r.len and + iend + 1 >= ibegin # the +1 here allows the result to be + # an empty range + when rangesGCHoldEnabled: result.gcHold = r.gcHold result.start = r.start.shift(ibegin) diff --git a/tests/ttypedranges.nim b/tests/ttypedranges.nim index b2ea9df..27bec80 100644 --- a/tests/ttypedranges.nim +++ b/tests/ttypedranges.nim @@ -19,6 +19,9 @@ suite "Typed ranges": let b = toRange(@[1, 2, 3]) a[1 .. 3] = b check a.toSeq == @[0, 1, 2, 3, 0] + check: + a[2 .. 2].len == 1 + a[1 ..< 1].len == 0 test "equality operator": var x = toRange(@[0, 1, 2, 3, 4, 5]) @@ -95,4 +98,4 @@ suite "Typed ranges": check hash(uu) == hash(u) check hash(v) == hash(vv) check hash(uu) != hash(vv) - \ No newline at end of file +