SliceMem: change newSliceMem(ptr, len...) to match an example, add another.

This commit is contained in:
Alberto Torres 2024-09-10 00:52:39 +02:00
parent dd75d19399
commit 90abbac26b

View file

@ -35,7 +35,8 @@ proc newSliceMem*[T, U](container: sink U; p: pointer, byte_len: int): SliceMem[
## Create a SliceMem from a container, a pointer, and a length in bytes. ## Create a SliceMem from a container, a pointer, and a length in bytes.
runnableExamples: runnableExamples:
let x = @[1,2,3,4,5] let x = @[1,2,3,4,5]
let s = newSliceMem(x, x[0].addr, x.len * sizeof(x[0])) # You can omit the [int] here because the container is iterable
let s = newSliceMem[int](x, x[0].addr, x.len * sizeof(x[0]))
result = SliceMem[T]( result = SliceMem[T](
data: cast[ptr UncheckedArray[T]](p), data: cast[ptr UncheckedArray[T]](p),
@ -48,9 +49,9 @@ proc newSliceMem*[T, U](container: sink U; p: pointer, byte_len: int): SliceMem[
), ),
) )
proc newSliceMem*[T](p: ptr T, byte_len: int, destructor: proc() {.closure, raises: [].}): SliceMem[T] = proc newSliceMem*[T](p: ptr T, len: int, destructor: proc() {.closure, raises: [].}): SliceMem[T] =
## Create a SliceMem from a pointer to a type, a length in bytes, and a # Create a SliceMem from a pointer to a type, a length, and a destructor
## destructor closure. # closure.
runnableExamples: runnableExamples:
let x = createShared(int, 5) let x = createShared(int, 5)
proc destroy() = deallocShared(x) proc destroy() = deallocShared(x)
@ -58,7 +59,7 @@ proc newSliceMem*[T](p: ptr T, byte_len: int, destructor: proc() {.closure, rais
result = SliceMem[T]( result = SliceMem[T](
data: cast[ptr UncheckedArray[T]](p), data: cast[ptr UncheckedArray[T]](p),
byte_len: byte_len, byte_len: len * sizeof(T),
destroy_ref: (ref CustomDestructor)(destroy: destructor), destroy_ref: (ref CustomDestructor)(destroy: destructor),
) )
@ -85,6 +86,11 @@ proc newSliceMem*[T, U](container: sink U; first, last: pointer): SliceMem[T] =
proc newSliceMem*[T](size: int): SliceMem[T] = proc newSliceMem*[T](size: int): SliceMem[T] =
## Create a SliceMem from new memory, similar to ArrRef[T]. ## Create a SliceMem from new memory, similar to ArrRef[T].
runnableExamples:
let s = newSliceMem[int](10)
for i,n in s.mpairs:
n = (i+1)*11
doAssert $s == "SliceMem([11, 22, 33, 44, 55, 66, 77, 88, 99, 110])"
var r: ref byte var r: ref byte
unsafeNew(r, size * sizeof(T)) unsafeNew(r, size * sizeof(T))
result = SliceMem[T]( result = SliceMem[T](