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
1 changed files with 153 additions and 144 deletions

21
md5.lua
View File

@ -33,7 +33,15 @@ 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 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
@ -73,7 +81,7 @@ end
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
@ -110,7 +118,7 @@ to_bits = function (n)
return tbl
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)
@ -128,7 +136,7 @@ local function bit_or(m, n)
return tbl2number(tbl)
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)
@ -146,7 +154,7 @@ local function bit_and(m, n)
return tbl2number(tbl)
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)
@ -164,7 +172,7 @@ local function bit_xor(m, n)
return tbl2number(tbl)
end
local function bit_rshift(n, bits)
function bit_rshift(n, bits)
check_int(n)
local high_bit = 0
@ -181,7 +189,7 @@ local function bit_rshift(n, bits)
return floor(n)
end
local function bit_lshift(n, bits)
function bit_lshift(n, bits)
check_int(n)
if(n < 0) then
@ -194,6 +202,7 @@ local function bit_lshift(n, bits)
end
return bit_and(n, 4294967295) -- 0xFFFFFFFF
end
end
-- convert little-endian 32-bit int to a 4-char string
local function lei2str(i)