Add 'incr' and 'decr' commands (32-bit only)

Sun, 01 Aug 2010 13:24:24 +0100

author
Matthew Wild <mwild1@gmail.com>
date
Sun, 01 Aug 2010 13:24:24 +0100
changeset 19
61c4d7f8279c
parent 18
d4822ae9d901
child 20
2cc1720b8633

Add 'incr' and 'decr' commands (32-bit only)

mooncached.lua file | annotate | diff | comparison | revisions
util/memcache.lua file | annotate | diff | comparison | revisions
--- a/mooncached.lua	Sun Aug 01 12:41:10 2010 +0100
+++ b/mooncached.lua	Sun Aug 01 13:24:24 2010 +0100
@@ -89,10 +89,37 @@
 	return generic_store_command(cache.replace, conn, params);
 end
 
+local function generic_increment_decrement_command(method, conn, params)
+	local key, amount = params:match("^(%S+) (%d+)");
+	local reply = params:match(" (noreply)$") ~= "noreply";
+	amount = tonumber(amount);
+	local ok, err;
+	if not (key and amount) then
+		if reply then
+			return false, "Invalid parameter(s)";
+		else
+			return nil;
+		end
+	end
+	local ok, new_value = method(cache, key, amount);
+	if ok and reply then
+		conn:write(new_value.."\r\n");
+	end
+	return true;
+end
+
+function command_handlers.incr(conn, params)
+	return generic_increment_decrement_command(cache.incr, conn, params);
+end
+
+function command_handlers.decr(conn, params)
+	return generic_increment_decrement_command(cache.decr, conn, params);
+end
+
 function command_handlers.get(conn, keys)
 	for key in keys:gmatch("%S+") do
 		local flags, data = cache:get(key);
-		if flags then
+		if data then
 			conn:write("VALUE "..key.." "..flags.." "..#data.."\r\n"..data.."\r\n");
 		end
 	end
--- a/util/memcache.lua	Sun Aug 01 12:41:10 2010 +0100
+++ b/util/memcache.lua	Sun Aug 01 13:24:24 2010 +0100
@@ -48,7 +48,7 @@
 		if expires and expires < now() then
 			self:delete(key);
 		end
-		return _flags[key], _data[key];
+		return _flags[key], tostring(_data[key]);
 	end
 	
 	function cache:delete(key, time)
@@ -63,6 +63,26 @@
 		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
 

mercurial