packages feed

clua-0.3: parse-bin-test.lua

require "parse-bin"

-- TOOLS

-- Deep coparison of data structures
-- http://snippets.luacode.org/snippets/Deep_Comparison_of_Two_Values_3
-- renamed from 'deepcompare' to 'table.equal'
function table.equal(t1,t2,ignore_mt)
   local ty1 = type(t1)
   local ty2 = type(t2)
   if ty1 ~= ty2 then return false end
   -- non-table types can be directly compared
   if ty1 ~= 'table' and ty2 ~= 'table' then return t1 == t2 end
   -- as well as tables which have the metamethod __eq
   local mt = getmetatable(t1)
   if not ignore_mt and mt and mt.__eq then return t1 == t2 end
   for k1,v1 in pairs(t1) do
      local v2 = t2[k1]
      if v2 == nil or not table.equal(v1,v2) then return false end
   end
   for k2,v2 in pairs(t2) do
      local v1 = t1[k2]
      if v1 == nil or not table.equal(v1,v2) then return false end
   end
   return true
end


-- TEST

local bytes = {1,2,3}
local tab = {u16=513, u8=3}
local spec = {{{'int','U',16}, 'u16'},
              {{'int','U',8},  'u8'}}

function test1()
   local stream = parse.array2stream({1,2,3})
   -- function ones() return 0xFF end
   -- parse.int(ones, {}, 'S', 32)
   -- parse.type(ones, {}, {'int', 'S', 32})
   -- parse.table(ones, {}, {{{'int', 'S', 32}, 'a'}})
   -- parse.table(ones, {}, {{{'int','U',16}, 'u16'}, {{'int','U',8},  'u8'}})
   local tab2 = parse.table(stream, {}, spec)
   return table.equal(tab2, tab)
end


function test2()
   local out2 = {}
   local stream = unparse.array2stream(out2)
   unparse.table(stream, {u16=513,u8=3}, {}, spec)
   return table.equal(out2, bytes)
end

-- Test for array and struct sub-tables.
structs = {
     super_struct=
        {{{'int','U',8},'v'},
         {{'int','U',8},'s'},
         {{'int','U',16},'c'},
         {{'struct','sub_struct'},'t'},
         {{'int','U',64},'l'}},
     sub_struct=
        {{{'int','U',32},'b'},
         {{'array',5,{'int','U',16}},'e'},
         {{'int','U',16},'q'}}
  }

struct_bytes = {11,1,10,0,9,0,0,0,3,0,4,0,5,0,6,0,7,0,8,0,2,0,0,0,0,0,0,0}


struct_tab = {
   s=1,
   l=2,
   t={
      e={3,4,5,6,7},
      q=8,
      b=9},
   c=10,
   v=11}


function test3()
   local tab = parse.array2table(struct_bytes, structs, structs.super_struct)
   return table.equal(tab, struct_tab)
end

function test4() 
   local bytes = unparse.table2array(struct_tab, structs, structs.super_struct)
   return table.equal(bytes, struct_bytes)
end
 
function test5()
   return parse.array2table(nil, structs, structs.super_struct)
end

print (test1())
print (test2())
print (test3())
print (test4())