Hello world. Is there in Nim an equivalent of nodejs's buffers ? A structured type that allows doing all kinds of binary operations on groups of bytes ? I'm thinking of something like this:
var
ba1 = initByteArr(234, 69, 43, 20)
ba2 = initByteArr(0x1A, 0x4F, 0xF5, 0xBD)
ba3 = initByteArr()
readBytes(someFile, ba3, 0, 4)
echo ba1 xor ba2
echo ba2 and ba3
echo ba1 & b2 # Concatenation
I don't think anyone have implemented xor or and on them, but you can simply store the buffers as seq[byte]. But it's simple enough:
proc `xor`(a, b: seq[byte]): seq[byte] =
assert a.len == b.len
result.setLen a.len
for i in 0..a.high:
result[i] = a[i] xor b[i]
let
b1 = @[234.byte, 69, 43, 20]
b2 = @[0x1A.byte, 0x4F, 0xF5, 0xBD]
echo b1 xor b2
The readBytes part is easy enough to do with cast[seq[byte]](readFile("myfile.bin")), readFile returns a string which is basically just a seq[char] so that cast should be safe.