1-- Test cases for bit operations library. Public domain.
2
3local bit = require"bit"
4
5local vb = {
6  0, 1, -1, 2, -2, 0x12345678, 0x87654321,
7  0x33333333, 0x77777777, 0x55aa55aa, 0xaa55aa55,
8  0x7fffffff, 0x80000000, 0xffffffff
9}
10
11local function cksum(name, s, r)
12  local z = 0
13  for i=1,#s do z = (z + string.byte(s, i)*i) % 2147483629 end
14  if z ~= r then
15    error("bit."..name.." test failed (got "..z..", expected "..r..")", 0)
16  end
17end
18
19local function check_unop(name, r)
20  local f = bit[name]
21  local s = ""
22  if pcall(f) or pcall(f, "z") or pcall(f, true) then
23    error("bit."..name.." fails to detect argument errors", 0)
24  end
25  for _,x in ipairs(vb) do s = s..","..tostring(f(x)) end
26  cksum(name, s, r)
27end
28
29local function check_binop(name, r)
30  local f = bit[name]
31  local s = ""
32  if pcall(f) or pcall(f, "z") or pcall(f, true) then
33    error("bit."..name.." fails to detect argument errors", 0)
34  end
35  for _,x in ipairs(vb) do
36    for _,y in ipairs(vb) do s = s..","..tostring(f(x, y)) end
37  end
38  cksum(name, s, r)
39end
40
41local function check_binop_range(name, r, yb, ye)
42  local f = bit[name]
43  local s = ""
44  if pcall(f) or pcall(f, "z") or pcall(f, true) or pcall(f, 1, true) then
45    error("bit."..name.." fails to detect argument errors", 0)
46  end
47  for _,x in ipairs(vb) do
48    for y=yb,ye do s = s..","..tostring(f(x, y)) end
49  end
50  cksum(name, s, r)
51end
52
53local function check_shift(name, r)
54  check_binop_range(name, r, 0, 31)
55end
56
57-- Minimal sanity checks.
58assert(0x7fffffff == 2147483647, "broken hex literals")
59assert(0xffffffff == -1 or 0xffffffff == 2^32-1, "broken hex literals")
60assert(tostring(-1) == "-1", "broken tostring()")
61assert(tostring(0xffffffff) == "-1" or tostring(0xffffffff) == "4294967295", "broken tostring()")
62
63-- Basic argument processing.
64assert(bit.tobit(1) == 1)
65assert(bit.band(1) == 1)
66assert(bit.bxor(1,2) == 3)
67assert(bit.bor(1,2,4,8,16,32,64,128) == 255)
68
69-- Apply operations to test vectors and compare checksums.
70check_unop("tobit", 277312)
71check_unop("bnot", 287870)
72check_unop("bswap", 307611)
73
74check_binop("band", 41206764)
75check_binop("bor", 51253663)
76check_binop("bxor", 79322427)
77
78check_shift("lshift", 325260344)
79check_shift("rshift", 139061800)
80check_shift("arshift", 111364720)
81check_shift("rol", 302401155)
82check_shift("ror", 302316761)
83
84check_binop_range("tohex", 47880306, -8, 8)
85
86