Add a helper for creating open arrays from pointers (#36)
* Add a helper for creating open arrays from pointers * doh, toOpenArray is broken in Nim 0.19.0 * Make openarrays from typed pointers * remove the ptr.toOpenArray seq work-around
This commit is contained in:
parent
0156cbd7f4
commit
9960d8eea9
|
@ -8,3 +8,19 @@ proc distance*(a, b: pointer): int {.inline.} =
|
||||||
|
|
||||||
proc shift*[T](p: ptr T, delta: int): ptr T {.inline.} =
|
proc shift*[T](p: ptr T, delta: int): ptr T {.inline.} =
|
||||||
cast[ptr T](shift(cast[pointer](p), delta * sizeof(T)))
|
cast[ptr T](shift(cast[pointer](p), delta * sizeof(T)))
|
||||||
|
|
||||||
|
when (NimMajor,NimMinor,NimPatch) >= (0,19,9):
|
||||||
|
template makeOpenArray*[T](p: ptr T, len: int): auto =
|
||||||
|
toOpenArray(cast[ptr UncheckedArray[T]](p), 0, len - 1)
|
||||||
|
|
||||||
|
template makeOpenArray*(p: pointer, T: type, len: int): auto =
|
||||||
|
toOpenArray(cast[ptr UncheckedArray[T]](p), 0, len - 1)
|
||||||
|
|
||||||
|
else:
|
||||||
|
# TODO: These are fallbacks until we upgrade to 0.19.9
|
||||||
|
template makeOpenArray*(p: pointer, T: type, len: int): auto =
|
||||||
|
toOpenArray(cast[ptr array[0, T]](p)[], 0, len - 1)
|
||||||
|
|
||||||
|
template makeOpenArray*[T](p: ptr T, len: int): auto =
|
||||||
|
toOpenArray(cast[ptr array[0, T]](p)[], 0, len - 1)
|
||||||
|
|
||||||
|
|
|
@ -45,7 +45,7 @@ suite "bit ranges":
|
||||||
check $asciiBits == "0100000101010011010000110100100101001001"
|
check $asciiBits == "0100000101010011010000110100100101001001"
|
||||||
|
|
||||||
test "concat operator":
|
test "concat operator":
|
||||||
randomize(0)
|
randomize(5000)
|
||||||
|
|
||||||
for i in 0..<256:
|
for i in 0..<256:
|
||||||
var xSeq = randomBytes(rand(i))
|
var xSeq = randomBytes(rand(i))
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
import
|
import
|
||||||
unittest, sets,
|
unittest, sets,
|
||||||
../ranges/typedranges
|
../ranges/[typedranges, ptr_arith]
|
||||||
|
|
||||||
suite "Typed ranges":
|
suite "Typed ranges":
|
||||||
test "basic stuff":
|
test "basic stuff":
|
||||||
|
@ -237,3 +237,18 @@ suite "Typed ranges":
|
||||||
$b.toOpenArray == "[]"
|
$b.toOpenArray == "[]"
|
||||||
b.aecheck(1) == 2
|
b.aecheck(1) == 2
|
||||||
$b.toOpenArray == "[]"
|
$b.toOpenArray == "[]"
|
||||||
|
|
||||||
|
test "make openarrays from pointers":
|
||||||
|
var str = "test 1,2,3"
|
||||||
|
var charPtr: ptr char = addr str[7]
|
||||||
|
var regularPtr: pointer = addr str[5]
|
||||||
|
|
||||||
|
check:
|
||||||
|
# (regularPtr.makeOpenArray(char, 4).len == 4)
|
||||||
|
(regularPtr.makeOpenArray(char, 5) == "1,2,3")
|
||||||
|
(regularPtr.makeOpenArray(char, 5) == str[5..9])
|
||||||
|
|
||||||
|
# (charPtr.makeOpenArray(3).len == 3)
|
||||||
|
(charPtr.makeOpenArray(3) == "2,3")
|
||||||
|
(charPtr.makeOpenArray(1) == str[7..7])
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue