feat: add string serialization with static size
This commit is contained in:
@@ -10,21 +10,11 @@ const VERSION: u8 = 1;
|
|||||||
|
|
||||||
// Data format:
|
// Data format:
|
||||||
// u8 -> version
|
// u8 -> version
|
||||||
// u16 -> width
|
// list of 100 u8
|
||||||
// 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
|
|
||||||
|
|
||||||
const Data = struct {
|
const Data = struct {
|
||||||
version: u8,
|
version: u8,
|
||||||
count: u8,
|
message: [100]u8,
|
||||||
};
|
};
|
||||||
|
|
||||||
const SerializationError = error{ VersionDoesNotMatchError, OtherError };
|
const SerializationError = error{ VersionDoesNotMatchError, OtherError };
|
||||||
@@ -34,20 +24,29 @@ fn deserialize(input: []u8) SerializationError!Data {
|
|||||||
return SerializationError.OtherError;
|
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 {
|
fn serialize(allocator: std.mem.Allocator, input: Data) ![]u8 {
|
||||||
const data = try allocator.alloc(u8, 1);
|
const data = try allocator.alloc(u8, 1 + input.message.len);
|
||||||
data[0] = input.count;
|
data[0] = input.version;
|
||||||
|
@memcpy(data[1..], &input.message);
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
test "expect DataV1 can be serialized and deserialized" {
|
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);
|
const serialized = try serialize(std.testing.allocator, expected);
|
||||||
defer std.testing.allocator.free(serialized);
|
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);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user