Small buffer module

just a small buffer module.

local Buffer = {}
Buffer.__index = Buffer

function Buffer.new(size)
	local self = setmetatable({}, Buffer)
	self.data = table.create(size, 0)
	self.position = 1
	self.size = size
	return self
end

function Buffer:WriteUInt8(value)
	if self.position > self.size then error("Buffer overflow") end
	self.data[self.position] = bit32.band(value, 0xFF)
	self.position = self.position + 1
end

function Buffer:WriteUInt16(value)
	self:WriteUInt8(bit32.band(value, 0xFF))
	self:WriteUInt8(bit32.band(bit32.rshift(value, 8), 0xFF))
end

function Buffer:WriteUInt32(value)
	self:WriteUInt16(bit32.band(value, 0xFFFF))
	self:WriteUInt16(bit32.band(bit32.rshift(value, 16), 0xFFFF))
end

function Buffer:WriteString(str)
	self:WriteUInt16(#str)
	for i = 1, #str do
		self:WriteUInt8(string.byte(str, i))
	end
end

function Buffer:ReadUInt8()
	if self.position > self.size then error("Buffer underflow") end
	local value = self.data[self.position]
	self.position = self.position + 1
	return value
end

function Buffer:ReadUInt16()
	local low = self:ReadUInt8()
	local high = self:ReadUInt8()
	return bit32.bor(bit32.lshift(high, 8), low)
end

function Buffer:ReadUInt32()
	local low = self:ReadUInt16()
	local high = self:ReadUInt16()
	return bit32.bor(bit32.lshift(high, 16), low)
end

function Buffer:ReadString()
	local length = self:ReadUInt16()
	local str = ""
	for i = 1, length do
		str = str .. string.char(self:ReadUInt8())
	end
	return str
end

return Buffer

FYI Luau has native buffers buffer | Documentation - Roblox Creator Hub

3 Likes