From 747c6e55cbe2283fd85ef8cd930e88d2bb0b7db2 Mon Sep 17 00:00:00 2001 From: Martin Ashby Date: Wed, 27 Sep 2023 23:34:46 +0100 Subject: Add a tagged union for all backend messages. Move read_message to proto.zig and make it return the tagged union rather than expecting a message type. --- src/main.zig | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) (limited to 'src/main.zig') diff --git a/src/main.zig b/src/main.zig index 818b3b7..9ce8de9 100644 --- a/src/main.zig +++ b/src/main.zig @@ -3,8 +3,9 @@ const testing = std.testing; pub const ProtocolError = error{ InvalidProtocolVersion, - InvalidKeyValuePair, + InvalidMessageType, InvalidMessageLength, + InvalidKeyValuePair, InvalidAuthType, MissingField, WrongMessageType, @@ -41,17 +42,6 @@ pub fn enum_from_int(comptime e: type, i: anytype) ?e { } } -// Tag should already have been read in order to determine msg_type! -pub fn read_message(comptime msg_type: type, allocator: std.mem.Allocator, stream_reader: anytype) !msg_type { - if (!@hasDecl(msg_type, "Tag")) @compileError("msg_type must have a Tag declaration!"); - if (!@hasDecl(msg_type, "read")) @compileError("msg_type must have a read() function!"); - const len = try stream_reader.readIntBig(u32); - const buf = try allocator.alloc(u8, @as(u32, @intCast(len - 4))); - defer allocator.free(buf); - try stream_reader.readNoEof(buf); - return try msg_type.read(allocator, buf); -} - pub fn diagnosticReader(comptime n: usize, base_reader: anytype) DiagnosticReader(n, @TypeOf(base_reader)) { return .{ .child_reader = base_reader }; } @@ -81,7 +71,7 @@ pub fn DiagnosticReader(comptime n: usize, comptime ReaderType: anytype) type { } // Caller frees - pub fn get(self: @This(), allocator: std.mem.Allocator) ![]const u8 { + pub fn get(self: @This(), allocator: std.mem.Allocator) ![]u8 { var buf = try allocator.alloc(u8, n); errdefer allocator.free(buf); @memcpy(buf[0..(n - self.pos)], self.ring[self.pos..n]); -- cgit v1.2.3-ZIG