@@ -48,19 +48,22 @@ template len*(b: ArrayBuf): int =
48
48
int (b.n)
49
49
50
50
template setLen* (b: var ArrayBuf, newLenParam: int ) =
51
- newLenParam.evalOnceAs(newLen)
52
- let nl = typeof(b.n)(newLen)
53
- for i in newLen ..< b.len():
54
- reset(b.buf[i]) # reset cleared items when shrinking
55
- b.n = nl
51
+ block :
52
+ newLenParam.evalOnceAs(newLen)
53
+ let nl = typeof(b.n)(newLen)
54
+ for i in newLen ..< b.len():
55
+ reset(b.buf[i]) # reset cleared items when shrinking
56
+ b.n = nl
56
57
57
58
template data* (bParam: ArrayBuf): openArray =
58
- bParam.evalOnceAs(b)
59
- b.buf.toOpenArray(0 , b.len() - 1 )
59
+ block :
60
+ bParam.evalOnceAs(b)
61
+ b.buf.toOpenArray(0 , b.len() - 1 )
60
62
61
63
template data* (bParam: var ArrayBuf): var openArray =
62
- bParam.evalOnceAs(b)
63
- b.buf.toOpenArray(0 , b.len() - 1 )
64
+ block :
65
+ bParam.evalOnceAs(b)
66
+ b.buf.toOpenArray(0 , b.len() - 1 )
64
67
65
68
iterator items* [N, T](b: ArrayBuf[N, T]): lent T =
66
69
for i in 0 ..< b.len:
@@ -92,6 +95,22 @@ template `==`*(a, b: ArrayBuf): bool =
92
95
template `<` * (a, b: ArrayBuf): bool =
93
96
a.data() < b.data()
94
97
98
+ template initCopyFrom* [N, T](
99
+ _: type ArrayBuf[N, T], data: openArray [T]
100
+ ): ArrayBuf[N, T] =
101
+ var v: ArrayBuf[N, T]
102
+ v.n = typeof(v.n)(v.buf.copyFrom(data))
103
+ v
104
+
105
+ template initCopyFrom*[N, T](
106
+ _: type ArrayBuf[N, T], data: array [N, T]
107
+ ): ArrayBuf[N, T] =
108
+ # Shortcut version that avoids zeroMem on matching lengths
109
+ ArrayBuf[N, T](
110
+ buf: data,
111
+ n: N
112
+ )
113
+
95
114
template add*[N, T](b: var ArrayBuf[N, T], v: T) =
96
115
## Adds items up to capacity then drops the rest
97
116
# TODO `b` is evaluated multiple times but since it's a `var` this should
@@ -112,4 +131,4 @@ template pop*[N, T](b: var ArrayBuf[N, T]): T =
112
131
# _hopefully_ be fine..
113
132
assert b.n > 0, "pop from empty ArrayBuf"
114
133
b.n -= 1
115
- move(b.buf[b.n])
134
+ move(b.buf[b.n])
0 commit comments