Made md5.lua use BitOp or Bit32 libraries where available

This commit is contained in:
Pablo Mayobre 2015-02-07 23:13:01 -03:00
parent 191b026807
commit e7df9d53cf
1 changed files with 153 additions and 145 deletions

50
md5.lua
View File

@ -33,15 +33,22 @@ 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)
if require "bit" or require "bit32" then
local bit = require "bit" or require "bit32"
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 +59,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 +76,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 +91,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 +115,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 +133,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 +151,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 +169,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 +186,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 +200,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