feat: add string serialization with static size

This commit is contained in:
2025-12-10 22:24:00 +01:00
parent 5ee6550073
commit d864d6b90c
2 changed files with 18 additions and 19 deletions

View File

@@ -2,7 +2,7 @@
.name = .websockets,
.version = "0.0.0",
.fingerprint = 0xa9f10aa30d7b02d1,
.fingerprint = 0xa9f10aa30d7b02d1,
.minimum_zig_version = "0.15.2",
.paths = .{

View File

@@ -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);
}