Hello
I have a pointer to a memory region containing a binary bitmap array coded in LSB https://en.wikipedia.org/wiki/Bit_numbering (from right to left) completed with the number of expected bools contained in it
for example:
byte 1: 00000111
byte 2: 00000011
num: 11
would mean logic values: [true,true,true,false,false,false,false,false,true,true,false]
Is it possible to abstract the access to this buffer as an openArray without performing any copy of the data?
I can successfully get bool value at index j with:
bitand(toOpenArray(cast[ptr UncheckedArray[byte]](myPointer), 0, num-1)[j div 8], (1 shl (j mod 8)).byte).bool
But I'm failing to generate or understanding if it's really possible or not to write the template that would have signature:
template bitmapBufferAsOpenArray(a: pointer): openArray[bool] =
thanks
Since bool`s are not bits you have to copy to make an `openarray[bool]. What makes a bit more sense is to make the following then implement operations on the type.
type MyBitset = object
start: ptr UncheckedArray[byte]
size: int
I was focusing on openArray for 2 reasons:
1- zero-copy access
2- make it work with all the things that already accepts openArray
by following the new type MyBitset approach I would save point 1 but lose 2. Is there a workaround to have the best of both worlds?
Also openarray is not a real type. Its used as parameter type to show what parameter is an array with length and subscript operator. So you don`t need to cast everything to it unless you need a generic proc accepting any array like.
I can suggest you to make your own structure with overload subscript operator
type BitVector = object
data: pointer
size: int
proc newBitVector(size: int): BitVector =
result.data = alloc0(size div 8 + 1)
result.size = size
proc `=destroy`(bv: BitVector) =
dealloc(bv.data)
proc `[]`(bv: BitVector, i: int): bool =
return (cast[ptr UncheckedArray[byte]](bv.data)[i div 8] shl (i mod 8)) > 0
let bv = newBitVector(10)
echo bv[7]
Missed the classical:
proc `=copy`(dest: var BitVector; source: BitVector) {.error.}
Somebody needs to come up with better default rules with what happens if only a subset of the =hooks are defined. We can probably steal these from C++... :-)