add md5:update and md5:sum methods

pull/1441/head
chrox 9 years ago
parent efe8e65dd9
commit 07ff30f89c

@ -208,14 +208,25 @@ local function bin2str(output, input, len)
end
end
local function md5(luastr)
local md5 = {}
function md5:new()
self.ctx = ffi.new("MD5_CTX")
MD5Init(self.ctx)
end
function md5:update(luastr)
MD5Update(self.ctx, ffi.cast("const char*", luastr), #luastr)
end
function md5:sum(luastr)
local buf = ffi.new("char[33]")
local hash = ffi.new("uint8_t[16]")
local ctx = ffi.new("MD5_CTX")
MD5Init(ctx)
MD5Update(ctx, ffi.cast("const char*", luastr), #luastr)
MD5Final(hash, ctx)
if luastr then
md5:new()
md5:update(luastr)
end
MD5Final(hash, self.ctx)
bin2str(buf, hash, ffi.sizeof(hash))

@ -122,7 +122,7 @@ function Cache:check(key, ItemClass)
end
return self.cache[key]
elseif ItemClass then
local cached = self.cached[md5(key)]
local cached = self.cached[md5:sum(key)]
if cached then
local item = ItemClass:new{}
local ok, msg = pcall(item.load, item, cached)
@ -159,7 +159,7 @@ function Cache:serialize()
-- only dump cache item that requests serialization explicitly
if cache_item.persistent and cache_item.dump then
DEBUG("dump cache item", key)
cache_size = cache_item:dump(cache_path..md5(key)) or 0
cache_size = cache_item:dump(cache_path..md5:sum(key)) or 0
if cache_size > 0 then break end
end
end

@ -4,9 +4,16 @@ local md5 = require("MD5")
describe("MD5 module", function()
it("should calculate correct MD5 hashes", function()
assert.is_equal(md5(""), "d41d8cd98f00b204e9800998ecf8427e")
assert.is_equal(md5("\0"), "93b885adfe0da089cdf634904fd59f71")
assert.is_equal(md5("0123456789abcdefX"), "1b05aba914a8b12315c7ee52b42f3d35")
assert.is_equal(md5:sum(""), "d41d8cd98f00b204e9800998ecf8427e")
assert.is_equal(md5:sum("\0"), "93b885adfe0da089cdf634904fd59f71")
assert.is_equal(md5:sum("0123456789abcdefX"), "1b05aba914a8b12315c7ee52b42f3d35")
end)
it("should calculate MD5 sum by updating", function()
md5:new()
md5:update("0123456789")
md5:update("abcdefghij")
local md5sum = md5:sum()
assert.is_equal(md5sum, md5:sum("0123456789abcdefghij"))
end)
end)

Loading…
Cancel
Save