git » nmdb » commit 4925883

Implement incr in the Ruby bindings.

author Alberto Bertogli
2007-09-02 01:02:32 UTC
committer Alberto Bertogli
2007-09-02 01:02:32 UTC
parent 5dd2e65e9d1565974995b014138db30432c7a8fc

Implement incr in the Ruby bindings.

Signed-off-by: Alberto Bertogli <albertito@gmail.com>

bindings/ruby/nmdb.rb +27 -0
bindings/ruby/nmdb_ll.c +31 -0

diff --git a/bindings/ruby/nmdb.rb b/bindings/ruby/nmdb.rb
index 7079406..09672af 100644
--- a/bindings/ruby/nmdb.rb
+++ b/bindings/ruby/nmdb.rb
@@ -138,6 +138,30 @@ class GenericDB
 	end
 
 
+	def generic_incr(gfunc, key, increment)
+		if @automarshal then
+			key = Marshal.dump(key)
+		end
+		r = gfunc.call(key, increment)
+		if r == 0 then
+			# key not in the database
+			return nil
+		elsif r == 1 or r < 0 then
+			raise NetworkException
+		else
+			return r
+		end
+	end
+
+	def normal_incr(key, increment)
+		return generic_incr(@db.method(:incr), key, increment)
+	end
+
+	def cache_incr(key, increment)
+		return generic_incr(@db.method(:cache_incr), key, increment)
+	end
+
+
 	# The following functions asume we have set(), get(), delete() and
 	# cas(), which are supposed to be implemented by our subclasses
 
@@ -161,6 +185,7 @@ class DB < GenericDB
 	alias get normal_get
 	alias delete normal_delete
 	alias cas normal_cas
+	alias incr normal_incr
 end
 
 class Cache < GenericDB
@@ -168,6 +193,7 @@ class Cache < GenericDB
 	alias get cache_get
 	alias delete cache_delete
 	alias cas cache_cas
+	alias incr cache_cas
 end
 
 class Sync < GenericDB
@@ -175,6 +201,7 @@ class Sync < GenericDB
 	alias get normal_get
 	alias delete delete_sync
 	alias cas normal_cas
+	alias incr normal_cas
 end
 
 end
diff --git a/bindings/ruby/nmdb_ll.c b/bindings/ruby/nmdb_ll.c
index 6bcfb97..1ef13cc 100644
--- a/bindings/ruby/nmdb_ll.c
+++ b/bindings/ruby/nmdb_ll.c
@@ -202,6 +202,34 @@ static VALUE m_cache_cas(VALUE self, VALUE key, VALUE oldval, VALUE newval) {
 }
 
 
+/* Del functions */
+typedef int (*incrf_t) (nmdb_t *db, const unsigned char *k, size_t ks,
+		int64_t increment);
+VALUE generic_incr(VALUE self, VALUE key, VALUE increment, incrf_t incr_func)
+{
+	ssize_t rv;
+	unsigned char *k;
+	size_t ksize;
+	int64_t cincr;
+	nmdb_t *db;
+	Data_Get_Struct(self, nmdb_t, db);
+
+	k = rb_str2cstr(key, &ksize);
+	cincr = rb_num2ll(increment);
+
+	rv = incr_func(db, k, ksize, cincr);
+	return INT2NUM(rv);
+}
+
+VALUE m_incr(VALUE self, VALUE key, VALUE increment) {
+	return generic_incr(self, key, increment, nmdb_incr);
+}
+
+VALUE m_cache_incr(VALUE self, VALUE key, VALUE increment) {
+	return generic_incr(self, key, increment, nmdb_cache_incr);
+}
+
+
 /* Module initialization */
 void Init_nmdb_ll()
 {
@@ -227,5 +255,8 @@ void Init_nmdb_ll()
 
 	rb_define_method(rb_cDB, "cas", m_cas, 3);
 	rb_define_method(rb_cDB, "cache_cas", m_cache_cas, 3);
+
+	rb_define_method(rb_cDB, "incr", m_incr, 2);
+	rb_define_method(rb_cDB, "cache_incr", m_cache_incr, 2);
 }