local now = os.time;
module("memcache", package.seeall);
local max_expires_seconds = 60*60*24*30;
function new()
local cache = {};
local _data = {};
local _flags = {};
local _expiry = {};
local _deleted = {};
function cache:set(key, flags, expires, data)
_flags[key] = flags;
if expires > 0 then
if expires <= max_expires_seconds then
expires = now() + expires;
end
_expiry[key] = expires;
end
_deleted[key] = nil;
_data[key] = data;
return true, true;
end
function cache:add(key, flags, expires, data)
if not(_data[key]) and (not(_deleted[key]) or _deleted[key] < now()) then
return self:set(key, flags, expires, data);
end
return true, false; -- No error, but data was not stored
end
function cache:replace(key, flags, expires, data)
if _data[key] and (not(_deleted[key]) or _deleted[key] < now()) then
return self:set(key, flags, expires, data);
end
return true, false; -- No error, but data was not stored
end
function cache:exists(key)
return not not _data[key];
end
function cache:get(key)
local expires = _expiry[key];
if expires and expires < now() then
self:delete(key);
end
return _flags[key], tostring(_data[key]);
end
function cache:delete(key, time)
local existed = _data[key];
_flags[key], _data[key], _expiry[key] = nil, nil, nil;
if existed and time then
if time <= max_expires_seconds then
time = now() + time;
end
_deleted[key] = time;
end
return true, existed;
end
function cache:incr(key, amount)
local current_value = tonumber((select(2, self:get(key)))) or 0;
local new_value = (current_value + amount)%4294967296;
local ok, err = cache:set(key, 0, 0, new_value);
if not ok then
return ok, err;
end
return ok, new_value;
end
function cache:decr(key, amount)
local current_value = tonumber((select(2, self:get(key)))) or 0;
local new_value = math.max(0, current_value - amount);
local ok, err = cache:set(key, 0, 0, new_value);
if not ok then
return ok, err;
end
return ok, new_value;
end
return cache;
end
return _M;