From 35494bc81b59165ee9264cd1004bb05a120279a3 Mon Sep 17 00:00:00 2001 From: Martin Ashby Date: Thu, 28 Sep 2023 10:54:58 +0100 Subject: 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. --- src/proto/parameter_status.zig | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) (limited to 'src/proto/parameter_status.zig') diff --git a/src/proto/parameter_status.zig b/src/proto/parameter_status.zig index 5f95695..7bc306b 100644 --- a/src/proto/parameter_status.zig +++ b/src/proto/parameter_status.zig @@ -11,13 +11,14 @@ buf: ?[]const u8 = null, // owned name: []const u8, value: []const u8, -pub fn read(allocator: std.mem.Allocator, b: []const u8) !ParameterStatus { - var res: ParameterStatus = undefined; - res.buf = try allocator.dupe(u8, b); - var it = std.mem.splitScalar(u8, res.buf.?, 0); - res.name = it.first(); - res.value = it.next() orelse return ProtocolError.MissingField; - return res; +pub fn read(a: std.mem.Allocator, buf: []const u8) !ParameterStatus { + errdefer a.free(buf); + var it = std.mem.splitScalar(u8, buf, 0); + return .{ + .buf = buf, + .name = it.first(), + .value = it.next() orelse return ProtocolError.MissingField, + }; } pub fn write(self: ParameterStatus, a: std.mem.Allocator, stream_writer: anytype) !void { try stream_writer.writeByte(Tag); @@ -30,7 +31,7 @@ pub fn write(self: ParameterStatus, a: std.mem.Allocator, stream_writer: anytype try writer.writeByte(0); try writer.writeAll(self.value); try writer.writeByte(0); - std.mem.writeIntBig(u32, al.items[0..4], @as(u32,@intCast(cw.bytes_written))); // Fix length + std.mem.writeIntBig(u32, al.items[0..4], @as(u32, @intCast(cw.bytes_written))); // Fix length try stream_writer.writeAll(al.items); } pub fn deinit(self: *ParameterStatus, allocator: std.mem.Allocator) void { @@ -55,7 +56,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 ParameterStatus.read(allocator, buf); defer sm2.deinit(allocator); -- cgit v1.2.3-ZIG