ptrops: add makeUncheckedArray (#193)

turns a pointer into an array pointer of the same type
This commit is contained in:
Jacek Sieka 2023-06-12 14:13:18 +02:00 committed by GitHub
parent 36e0eb8d89
commit ebbb391b9e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 9 additions and 1 deletions

View File

@ -49,10 +49,13 @@ template distance*[T](a, b: ptr T): int =
# exceeds what can be represented in an int
distance(cast[pointer](a), cast[pointer](b)) div sizeof(T)
proc baseAddr*[T](x: openArray[T]): ptr T =
func baseAddr*[T](x: openArray[T]): ptr T =
# Return the address of the zero:th element of x or `nil` if x is empty
if x.len == 0: nil else: cast[ptr T](x)
func makeUncheckedArray*[T](p: ptr T): ptr UncheckedArray[T] =
cast[ptr UncheckedArray[T]](p)
template makeOpenArray*[T](p: ptr T, len: Natural): openArray[T] =
toOpenArray(cast[ptr UncheckedArray[T]](p), 0, len - 1)

View File

@ -86,3 +86,8 @@ suite "ptrops":
check:
baseAddr(makeOpenArray(nil, int, 0)) == nil
baseAddr(makeOpenArray(addr v, 1)) == addr v
block ua:
var v = [2, 3]
check:
makeUncheckedArray(baseAddr v)[1] == 3