#!/usr/bin/env lua5.1 -- $Id: teststruct.lua,v 1.2 2008/04/18 20:06:01 roberto Exp $ -- load library local lib = require"struct" assert(_G.struct == lib) -- -- auxiliar function to print an hexadecimal `dump' of a given string -- (not used by the test) -- local function bp (s) s = string.gsub(s, "(.)", function(c) return string.format("\\%02x", string.byte(c)) end) print(s) end local a,b,c,d,e,f,x assert(#struct.pack("I", 67324752) == 4) assert(lib.pack('b', 10) == string.char(10)) assert(lib.pack('bbb', 10, 20, 30) == string.char(10, 20, 30)) assert(lib.pack('h', 10) == string.char(0, 10)) assert(lib.pack('l', 10) == string.char(0, 0, 0, 10)) assert(lib.pack('h', string.char(0, 10)) == 10) assert(lib.unpack('l', string.char(0, 1, 0, 10)) == 10 + 2^(2*8)) assert(lib.unpack('', '<'} do for _, l in pairs(lims) do local fmt = a .. l[1] assert(lib.unpack(fmt, lib.pack(fmt, l[2])) == l[2]) end end -- tests for fixed-sized ints for _, i in pairs{1,2,4} do x = lib.pack('c7", 1, "alo alo") == "\1alo alo") assert(lib.pack("!2iiiii", 1, 2, 3, 4, 5) local i = 1 local k = 1 while i < #x do local v, j = lib.unpack("!>i", x, i) assert(j == i + 4 and v == k) i = j; k = k + 1 end -- alignments are relative to 'absolute' positions x = lib.pack("!8 xd", 12) assert(lib.unpack("!8d", x, 3) == 12) assert(lib.pack("lBxxH", -20, 10, 250) == string.char(255, 255, 255, 236, 10, 0, 0, 0, 250)) a, b, c, d = lib.unpack(">lBxxH", string.char(255, 255, 255, 236, 10, 0, 0, 0, 250)) assert(a == -20 and b == 10 and c == 250 and d == 10) a,b,c,d,e = lib.unpack(">fdfH", '000'..lib.pack(">fdfH", 3.5, -24e-5, 200.5, 30000), 4) assert(a == 3.5 and b == -24e-5 and c == 200.5 and d == 30000 and e == 22) a,b,c,d,e = lib.unpack("I2fi4I2", 10, 20, -30, 40001) assert(string.len(x) == 2+4+4+2) assert(lib.unpack(">f", x, 3) == 20) a,b,c,d = lib.unpack(">i2fi4I2", x) assert(a == 10 and b == 20 and c == -30 and d == 40001) local s = "hello hello" x = lib.pack(" b c0 ", string.len(s), s) assert(lib.unpack("bc0", x) == s) x = lib.pack("Lc0", string.len(s), s) assert(lib.unpack(" L c0 ", x) == s) x = lib.pack("cc3b", s, s, 0) assert(x == "hhel\0") assert(lib.unpack("xxxxb", x) == 0) assert(lib.pack("sh", "aloi", 3) == "aloi\0\0\3") assert(lib.pack(">!sh", "aloi", 3) == "aloi\0\0\0\3") x = "aloi\0\0\0\0\3\2\0\0" a, b, c = lib.unpack(">>h >><<