]> gitweb.ps.run Git - ziglmdb/commitdiff
add reverse iterator to DB
authorpatrick-scho <patrick.schoenberger@posteo.de>
Mon, 21 Apr 2025 14:19:21 +0000 (16:19 +0200)
committerpatrick-scho <patrick.schoenberger@posteo.de>
Mon, 21 Apr 2025 14:19:21 +0000 (16:19 +0200)
src/db.zig

index 71b5272b6b17bacebd5359e8b34272d01fc35d5f..4e8126de4c1c2cc23d5fd6dbdad91a5af4e14d4c 100644 (file)
@@ -29,6 +29,7 @@ pub fn Db(comptime K: type, comptime V: type) type {
         pub const Iterator = struct {
             pub const Result = struct { key: K, val: V };
             cursor: lmdb.Cursor,
+            dir: enum { Forward, Backward },
             k: ?K,
             v: ?V,
 
@@ -37,7 +38,11 @@ pub fn Db(comptime K: type, comptime V: type) type {
                     const result = Result{ .key = self.k.?, .val = self.v.? };
 
                     var k = self.k.?;
-                    self.v = self.cursor.get(&k, V, .Next) catch return null;
+                    if (self.dir == .Forward) {
+                        self.v = self.cursor.get(&k, V, .Next) catch return null;
+                    } else {
+                        self.v = self.cursor.get(&k, V, .Prev) catch return null;
+                    }
                     if (self.v != null) {
                         self.k = k;
                     }
@@ -52,7 +57,14 @@ pub fn Db(comptime K: type, comptime V: type) type {
 
             var k: K = undefined;
             const v = try cursor.get(&k, V, .First);
-            return .{ .cursor = cursor, .k = k, .v = v };
+            return .{ .cursor = cursor, .dir = .Forward, .k = k, .v = v };
+        }
+        pub fn reverse_iterator(self: Self) !Iterator {
+            var cursor = try self.dbi.cursor();
+
+            var k: K = undefined;
+            const v = try cursor.get(&k, V, .Last);
+            return .{ .cursor = cursor, .dir = .Backward, .k = k, .v = v };
         }
     };
 }