I need to use bitwise operations (like AND or other) and bit shifts on a large buffer I have but I couldn’t find anything ressembling that in the buffer library, so I made a little function for this (another one for bit shift that uses buffer.copy but it’s pretty much the same code).
The problem is that my game calls this function many many times (>5000 per thread) every frame (and I cannot remove or optimize the calls made) so I’d like to know if there is a better/faster alternative to doing that (especially since it uses loops).
local function processBuffer(b: buffer, bitOffset: number, op: (number) -> (number))
-- The last iteration may not be in a batch of 32
local bLen = buffer.len(b)
local iterations, lastIterationLength = bLen, bLen % 4
local bOutput = buffer.create(bLen)
for i=4, iterations, 4 do
local position = bitOffset + (i - 4) * 8
buffer.writeu32(bOutput, position, op(
buffer.readu32(b, position)
))
end
-- Handle the last iteration
local position = bitOffset + bLen - lastIterationLength
local size = lastIterationLength
buffer.writebits(bOutput, position, size, op(
buffer.readbits(b, position, size)
))
-- Returning
return bOutput
end