diff --git a/src/batch.zig b/src/batch.zig new file mode 100644 index 0000000..76aa581 --- /dev/null +++ b/src/batch.zig @@ -0,0 +1,46 @@ +const std = @import("std"); +const encode = @import("encode.zig"); + +const Allocator = std.mem.Allocator; +const Kind = encode.Kind; + +pub const Op = struct { + kind: Kind, + key: []u8, + value: []u8, +}; + +pub const WriteBatch = struct { + allocator: Allocator, + ops: std.ArrayList(Op), + + pub fn init(allocator: Allocator) WriteBatch { + return .{ .allocator = allocator, .ops = std.ArrayList(Op).init(allocator) }; + } + + pub fn deinit(self: *WriteBatch) void { + for (self.ops.items) |op| { + self.allocator.free(op.key); + self.allocator.free(op.value); + } + self.ops.deinit(); + } + + pub fn put(self: *WriteBatch, key: []const u8, value: []const u8) !void { + const keyCopy = try self.allocator.dupe(u8, key); + errdefer self.allocator.free(keyCopy); + const valueCopy = try self.allocator.dupe(u8, value); + try self.ops.append(.{ .kind = .value, .key = keyCopy, .value = valueCopy }); + } + + pub fn delete(self: *WriteBatch, key: []const u8) !void { + const keyCopy = try self.allocator.dupe(u8, key); + errdefer self.allocator.free(keyCopy); + const valueCopy = try self.allocator.dupe(u8, &.{}); + try self.ops.append(.{ .kind = .tombstone, .key = keyCopy, .value = valueCopy }); + } + + pub fn count(self: *const WriteBatch) usize { + return self.ops.items.len; + } +};