Merge pull request #2 from Positive07/patch-1

Use BitOp or Bit32 libraries where available
This commit is contained in:
Enrique García 2015-02-09 11:13:46 +01:00
commit b56a8a1e93

51
md5.lua

@ -33,15 +33,23 @@ local md5 = {
local floor, abs, max = math.floor, math.abs, math.max
local char, byte, format, rep, sub =
string.char, string.byte, string.format, string.rep, string.sub
local bit_or, bit_and, bit_not, bit_xor, bit_rshift, bit_lshift
local function check_int(n)
local ok, bit = pcall(require, 'bit')
if not ok then ok, bit = pcall(require, 'bit32') end
if ok then
bit_or, bit_and, bit_not, bit_xor = bit.bor, bit.band, bit.bnot, bit.bxor
bit_rshift, bit_lshift = bit.rshift, bit.lshift
else
local function check_int(n)
-- checking not float
if(n - floor(n) > 0) then
error("trying to use bitwise operation on non-integer!")
end
end
end
local function tbl2number(tbl)
local function tbl2number(tbl)
local n = #tbl
local rslt = 0
@ -52,9 +60,9 @@ local function tbl2number(tbl)
end
return rslt
end
end
local function expand(tbl_m, tbl_n)
local function expand(tbl_m, tbl_n)
local big = {}
local small = {}
if(#tbl_m > #tbl_n) then
@ -69,11 +77,11 @@ local function expand(tbl_m, tbl_n)
small[i] = 0
end
end
end
local to_bits -- needs to be declared before bit_not
local to_bits -- needs to be declared before bit_not
local function bit_not(n)
function bit_not(n)
local tbl = to_bits(n)
local size = max(#tbl, 32)
for i = 1, size do
@ -84,10 +92,10 @@ local function bit_not(n)
end
end
return tbl2number(tbl)
end
end
-- defined as local above
to_bits = function (n)
-- defined as local above
to_bits = function (n)
check_int(n)
if(n < 0) then
-- negative
@ -108,9 +116,9 @@ to_bits = function (n)
end
return tbl
end
end
local function bit_or(m, n)
function bit_or(m, n)
local tbl_m = to_bits(m)
local tbl_n = to_bits(n)
expand(tbl_m, tbl_n)
@ -126,9 +134,9 @@ local function bit_or(m, n)
end
return tbl2number(tbl)
end
end
local function bit_and(m, n)
function bit_and(m, n)
local tbl_m = to_bits(m)
local tbl_n = to_bits(n)
expand(tbl_m, tbl_n)
@ -144,9 +152,9 @@ local function bit_and(m, n)
end
return tbl2number(tbl)
end
end
local function bit_xor(m, n)
function bit_xor(m, n)
local tbl_m = to_bits(m)
local tbl_n = to_bits(n)
expand(tbl_m, tbl_n)
@ -162,9 +170,9 @@ local function bit_xor(m, n)
end
return tbl2number(tbl)
end
end
local function bit_rshift(n, bits)
function bit_rshift(n, bits)
check_int(n)
local high_bit = 0
@ -179,9 +187,9 @@ local function bit_rshift(n, bits)
n = bit_or(floor(n), high_bit)
end
return floor(n)
end
end
local function bit_lshift(n, bits)
function bit_lshift(n, bits)
check_int(n)
if(n < 0) then
@ -193,6 +201,7 @@ local function bit_lshift(n, bits)
n = n*2
end
return bit_and(n, 4294967295) -- 0xFFFFFFFF
end
end
-- convert little-endian 32-bit int to a 4-char string