From d864d6b90c8eceb1443d7f5fad8b99fba670c800 Mon Sep 17 00:00:00 2001 From: Tim Wundenberg Date: Wed, 10 Dec 2025 22:24:00 +0100 Subject: [PATCH] feat: add string serialization with static size --- build.zig.zon | 2 +- src/protocol.zig | 35 +++++++++++++++++------------------ 2 files changed, 18 insertions(+), 19 deletions(-) diff --git a/build.zig.zon b/build.zig.zon index 7313c97..663336a 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -2,7 +2,7 @@ .name = .websockets, .version = "0.0.0", - .fingerprint = 0xa9f10aa30d7b02d1, + .fingerprint = 0xa9f10aa30d7b02d1, .minimum_zig_version = "0.15.2", .paths = .{ diff --git a/src/protocol.zig b/src/protocol.zig index d746c3c..f1ae911 100644 --- a/src/protocol.zig +++ b/src/protocol.zig @@ -10,21 +10,11 @@ const VERSION: u8 = 1; // Data format: // u8 -> version -// u16 -> width -// u16 -> height -// u8,u8,u8 list of rgb for each pixel, going from left to right, top to bottom -// -// UDP Packet Size: 65,535 Bytes -// 1 Byte = 8 Bits -// 8+16+16 = 40 Bits header -// (65k * 8) - 40 = 524,240 -// 8+8+8 = 24 -// 24 / 524,240 = 21,843 pixel -// 1920*1080 = 2,073,600 pixel +// list of 100 u8 const Data = struct { version: u8, - count: u8, + message: [100]u8, }; const SerializationError = error{ VersionDoesNotMatchError, OtherError }; @@ -34,20 +24,29 @@ fn deserialize(input: []u8) SerializationError!Data { return SerializationError.OtherError; } - return .{ .count = input[0] }; + if (input[0] != VERSION) { + return SerializationError.VersionDoesNotMatchError; + } + + var message = [_]u8{0} ** 100; + + @memcpy(&message, input[1..101]); + + return .{ .version = VERSION, .message = message }; } fn serialize(allocator: std.mem.Allocator, input: Data) ![]u8 { - const data = try allocator.alloc(u8, 1); - data[0] = input.count; + const data = try allocator.alloc(u8, 1 + input.message.len); + data[0] = input.version; + @memcpy(data[1..], &input.message); return data; } test "expect DataV1 can be serialized and deserialized" { - const expected: Data = .{ .count = 128 }; + const expected: Data = .{ .version = VERSION, .message = [_]u8{ 'T', 'e', 's', 't' } ++ [_]u8{0} ** 96 }; const serialized = try serialize(std.testing.allocator, expected); defer std.testing.allocator.free(serialized); - const actual = try deserialize(serialized); + // const actual = try deserialize(serialized); - try std.testing.expectEqual(expected, actual); + try std.testing.expectEqual(expected, null); }