add slice assignment for openarray

This commit is contained in:
Jacek Sieka 2020-03-05 00:42:04 +01:00 committed by zah
parent 598fe151f8
commit ca8fb7ebd0
2 changed files with 24 additions and 0 deletions

View File

@ -22,6 +22,20 @@ func `&`*[N1, N2: static[int], T](
result[0 ..< N1] = a
result[N1 ..< result.len] = b
template `^^`(s, i: untyped): untyped =
(when i is BackwardsIndex: s.len - int(i) else: int(i))
func `[]=`*[T, U, V](r: var openArray[T], s: HSlice[U, V], v: openArray[T]) =
## openArray slice assignment:
## v[0..<2] = [0, 1]
let a = r ^^ s.a
let b = r ^^ s.b
let L = b - a + 1
if L == v.len:
for i in 0..<L: r[i + a] = v[i]
else:
raise newException(RangeError, "different lengths for slice assignment")
########################################################################################################
##################################### Hex utilities ################################################

View File

@ -87,3 +87,13 @@ suite "Byte utils":
"a".toBytes() == @[byte(ord('a'))]
string.fromBytes([byte(ord('a'))]) == "a"
cast[ptr UncheckedArray[byte]](cstring(string.fromBytes([byte(ord('a'))])))[1] == byte(0)
test "slices":
var a: array[4, byte]
a[0..<2] = [2'u8, 3]
check:
a[1] == 3
a.toOpenArray(0, 3)[0..<2] = [4'u8, 5]
check:
a[1] == 5