Skip to content

Commit

Permalink
arraybuf: new constructor
Browse files Browse the repository at this point in the history
also add a block to avoid symbol leaks
  • Loading branch information
arnetheduck committed Oct 7, 2024
1 parent b7b5969 commit b0c6b11
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 10 deletions.
30 changes: 20 additions & 10 deletions stew/arraybuf.nim
Original file line number Diff line number Diff line change
Expand Up @@ -48,19 +48,22 @@ template len*(b: ArrayBuf): int =
int(b.n)

template setLen*(b: var ArrayBuf, newLenParam: int) =
newLenParam.evalOnceAs(newLen)
let nl = typeof(b.n)(newLen)
for i in newLen ..< b.len():
reset(b.buf[i]) # reset cleared items when shrinking
b.n = nl
block:
newLenParam.evalOnceAs(newLen)
let nl = typeof(b.n)(newLen)
for i in newLen ..< b.len():
reset(b.buf[i]) # reset cleared items when shrinking
b.n = nl

template data*(bParam: ArrayBuf): openArray =
bParam.evalOnceAs(b)
b.buf.toOpenArray(0, b.len() - 1)
block:
bParam.evalOnceAs(b)
b.buf.toOpenArray(0, b.len() - 1)

template data*(bParam: var ArrayBuf): var openArray =
bParam.evalOnceAs(b)
b.buf.toOpenArray(0, b.len() - 1)
block:
bParam.evalOnceAs(b)
b.buf.toOpenArray(0, b.len() - 1)

iterator items*[N, T](b: ArrayBuf[N, T]): lent T =
for i in 0 ..< b.len:
Expand Down Expand Up @@ -92,6 +95,13 @@ template `==`*(a, b: ArrayBuf): bool =
template `<`*(a, b: ArrayBuf): bool =
a.data() < b.data()

template initCopyFrom*[N, T](
_: type ArrayBuf[N, T], data: openArray[T]
): ArrayBuf[N, T] =
var v {.noinit.}: ArrayBuf[N, T]
v.n = typeof(v.n)(v.buf.copyFrom(data))
v

template add*[N, T](b: var ArrayBuf[N, T], v: T) =
## Adds items up to capacity then drops the rest
# TODO `b` is evaluated multiple times but since it's a `var` this should
Expand All @@ -112,4 +122,4 @@ template pop*[N, T](b: var ArrayBuf[N, T]): T =
# _hopefully_ be fine..
assert b.n > 0, "pop from empty ArrayBuf"
b.n -= 1
move(b.buf[b.n])
move(b.buf[b.n])
11 changes: 11 additions & 0 deletions tests/test_arraybuf.nim
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,14 @@ suite "ArrayBuf":
v.len == 1
v.setLen(2)
doAssert v.data() == [byte 1, 0]

test "construction":
let
a0 = ArrayBuf[4, byte].initCopyFrom([])
a2 = ArrayBuf[2, byte].initCopyFrom([byte 2, 3, 4, 5])
a5 = ArrayBuf[5, byte].initCopyFrom([byte 2, 3])

check:
a0.len == 0
a2.data() == [byte 2, 3]
a5.data() == [byte 2, 3]

0 comments on commit b0c6b11

Please sign in to comment.