X-Git-Url: https://gitweb.ps.run/ziglmdb/blobdiff_plain/88cb74a430fa9629c8127c3a866c40e79a8e4612..364d2904bd4c9928a08b9e083fa2d3251d6cf836:/src/db.zig?ds=sidebyside diff --git a/src/db.zig b/src/db.zig index 71b5272..3e1b186 100644 --- a/src/db.zig +++ b/src/db.zig @@ -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 }; } }; } @@ -84,7 +96,7 @@ fn SetListBase(comptime K: type, comptime V: type) type { idx: ?Index = null, fn open_dbi(txn: lmdb.Txn) !lmdb.Dbi { - return try txn.dbi("SetList"); + return try txn.dbi(null); } pub fn init(txn: lmdb.Txn) !Self { const head = View.Head{}; @@ -132,6 +144,15 @@ fn SetListViewBase(comptime K: type, comptime V: type) type { idx: SetListBase(K, V).Index, head: Head, + fn gen(self: @This()) !Key { + // TODO: limit loop + while (true) { + const key = try Prng.gen(self.dbi, Key); + if (!try self.dbi.has(self.item_idx(key))) { + return key; + } + } + } fn item_idx(self: Self, k: K) ItemIndex { return .{ self.idx, k }; } @@ -159,7 +180,7 @@ fn SetListViewBase(comptime K: type, comptime V: type) type { try self.item_put(item.next.?, next); } - if (self.head.first == k) self.head.first = item.next; + if (std.mem.eql(K, self.head.first, k)) self.head.first = item.next; if (self.head.last == k) self.head.last = item.prev; self.head.len -= 1; try self.head_update(); @@ -300,15 +321,6 @@ pub fn List(comptime V: type) type { base: ViewBase, - fn gen(self: @This()) !Key { - // TODO: limit loop - while (true) { - const key = try Prng.gen(self.base.dbi, Key); - if (!try self.base.dbi.has(self.base.item_idx(key))) { - return key; - } - } - } pub fn del(self: *@This(), key: Key) !void { try self.base.del(key); } @@ -319,7 +331,7 @@ pub fn List(comptime V: type) type { return self.base.len(); } pub fn append(self: *@This(), val: Val) !Key { - const key = try self.gen(); + const key = try self.base.gen(); try self.base.append(key, val); return key; }