I am think of writing a simple proc to use verilog HDL style syntax, such as register_a[3:1] = 0x1 register_a[4:2] = 0x2
the operator like [ end : start ] might need some overload of [ : ] but don't know to : (.
a:b is hard to overload because : is not a normal operator. This is how Slice does it (without using HSlice):
type Slice[T] = object
a, b: T
template `..`[T](x, y: T): Slice[T] =
Slice[T](a: x, b: y)
proc `[]`[T, I](s: openarray[T], sl: Slice[I]): seq[T] =
result.newSeq(sl.b - sl.a + 1)
for i in 0 ..< result.len:
result[i] = s[sl.a + i]
let s = @[1, 2, 3, 4, 5]
echo s[1..3]
You could replace .. with another operator here and use that instead of :, or you could just allow 2 arguments inside the bracket, separated by a comma. No operator is needed for this.
type BitSlice[T] = object
`end`, start: T
template `:<`[T](x, y: T): BitSlice[T] =
BitSlice[T](`end`: x, start: y)
proc `[]=`[T, I](s: var openarray[T], sl: BitSlice[I], val: T) =
for i in countup(sl.start, sl.end):
s[i] = val
var s = @[1, 2, 3, 4, 5]
s[3:<1] = -1
echo s
# or
proc `[]=`[T, I](s: var openarray[T], `end`, start: I, val: T) =
for i in countup(start, `end`):
s[i] = val
var s = @[1, 2, 3, 4, 5]
s[3, 1] = -1
echo s
Thanks a lot! This solved my problem.
Only thing not so "perfect" is : could not be used as slice operator.
Nice! Maybe you could try .. instead? I used .. for HDL/hardware register style descriptions BitFields. Not sure but I think .. would work in a setter.
Oh and I like the set slice syntax too! Mind if I steal it and add it to the bitfields module? I'm trying to collect nice syntaxes :)