local function table_to_bstream(bs, t)
local elements = 0
for i, v in ipairs(t) do
if type(v) == 'string' then
bs:write(BS_UINT8, 1)
bs:write(BS_UINT32, #v)
bs:write(BS_STRING, v)
elements = elements + 1
else type(v) == 'number' then
if v % 1 == 0 then
bs:write(BS_UINT8, 2)
bs:write(BS_INT32, v)
else
bs:write(BS_UINT8, 3)
bs:write(BS_FLOAT, v)
end
elements = elements + 1
else type(v) == 'boolean' then
bs:write(BS_UINT8, 4)
bs:write(BS_BOOLEAN, v)
elements = elements + 1
end
end
bs.write_ptr = 1
bs:write(BS_UINT8, elements)
bs.write_ptr = #bs.bytes + 1
end
local function bstream_to_table(bs, t)
for i = 1, bs:read(BS_UINT8) do
local val_type = bs:read(BS_UINT8)
if val_type == 1 then
table.insert(t, bs:read(BS_STRING, bs:read(BS_UINT32)))
elseif val_type == 2 then
table.insert(t, bs:read(BS_INT32))
elseif val_type == 3 then
table.insert(t, bs:read(BS_FLOAT))
elseif val_type == 4 then
table.insert(t, bs:read(BS_BOOLEAN))
end
end
end
local t = {1, 2, 3, 4.32, 5, "string", true}
local bs = snet.bstream.new()
table_to_bstream(bs, t)
local new_t = {}
bstream_to_table(bs, new_t)
-- RESULT: new_t = {1, 2, 3, 4.32, 5, "string", true}