aboutsummaryrefslogtreecommitdiff
path: root/src/proto/command_complete.zig
diff options
context:
space:
mode:
authorMartin Ashby <martin@ashbysoft.com>2023-09-28 10:54:58 +0100
committerMartin Ashby <martin@ashbysoft.com>2023-09-28 10:54:58 +0100
commit35494bc81b59165ee9264cd1004bb05a120279a3 (patch)
tree8d11946f8fc20e1f254301100e860f28bade5ee0 /src/proto/command_complete.zig
parent0c063d42430077881e563120ebfcf92c2cecf463 (diff)
downloadpgz-35494bc81b59165ee9264cd1004bb05a120279a3.tar.gz
pgz-35494bc81b59165ee9264cd1004bb05a120279a3.tar.bz2
pgz-35494bc81b59165ee9264cd1004bb05a120279a3.tar.xz
pgz-35494bc81b59165ee9264cd1004bb05a120279a3.zip
Reduce allocations, the message takes ownership of the bytes read from
the stream and is responsible for deallocating, rather than copying them to their own storage.
Diffstat (limited to 'src/proto/command_complete.zig')
-rw-r--r--src/proto/command_complete.zig13
1 files changed, 6 insertions, 7 deletions
diff --git a/src/proto/command_complete.zig b/src/proto/command_complete.zig
index 80014e9..ed8e052 100644
--- a/src/proto/command_complete.zig
+++ b/src/proto/command_complete.zig
@@ -10,24 +10,24 @@ pub const Tag: u8 = 'C';
const CommandComplete = @This();
+buf: ?[]const u8 = null, // owned
command_tag: []const u8,
-owned: bool = false,
-pub fn read(a: std.mem.Allocator, b: []const u8) !CommandComplete {
+pub fn read(_: std.mem.Allocator, buf: []const u8) !CommandComplete {
return .{
- .command_tag = try a.dupe(u8, b),
- .owned = true,
+ .buf = buf,
+ .command_tag = buf[0..],
};
}
pub fn write(self: CommandComplete, _: std.mem.Allocator, stream_writer: anytype) !void {
try stream_writer.writeByte(Tag);
- try stream_writer.writeIntBig(u32, @as(u32, @intCast(4+self.command_tag.len)));
+ try stream_writer.writeIntBig(u32, @as(u32, @intCast(4 + self.command_tag.len)));
try stream_writer.writeAll(self.command_tag);
}
pub fn deinit(self: *CommandComplete, a: std.mem.Allocator) void {
- if (self.owned) a.free(self.command_tag);
+ if (self.buf != null) a.free(self.buf.?);
}
test "round trip" {
@@ -47,7 +47,6 @@ test "round trip" {
try std.testing.expectEqual(Tag, tag);
const len = try reader.readIntBig(u32);
const buf = try allocator.alloc(u8, len - 4);
- defer allocator.free(buf);
try reader.readNoEof(buf);
var sm2 = try CommandComplete.read(allocator, buf);
defer sm2.deinit(allocator);