From 07ff30f89ce6468d3a8318e19fc52c735b8801e3 Mon Sep 17 00:00:00 2001 From: chrox Date: Thu, 19 Feb 2015 22:12:11 +0800 Subject: [PATCH] add md5:update and md5:sum methods --- frontend/MD5.lua | 23 +++++++++++++++++------ frontend/cache.lua | 4 ++-- spec/unit/md5_spec.lua | 13 ++++++++++--- 3 files changed, 29 insertions(+), 11 deletions(-) diff --git a/frontend/MD5.lua b/frontend/MD5.lua index 26c94759a..c8d73ea1f 100644 --- a/frontend/MD5.lua +++ b/frontend/MD5.lua @@ -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)) diff --git a/frontend/cache.lua b/frontend/cache.lua index fda092f8e..5f9b92431 100644 --- a/frontend/cache.lua +++ b/frontend/cache.lua @@ -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 diff --git a/spec/unit/md5_spec.lua b/spec/unit/md5_spec.lua index fb59b864a..4efbe212a 100644 --- a/spec/unit/md5_spec.lua +++ b/spec/unit/md5_spec.lua @@ -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)