first try on binary serialization

This commit is contained in:
2025-12-07 20:29:50 +01:00
parent 815331f323
commit c3e99821dd
3 changed files with 40 additions and 18 deletions

View File

@@ -16,22 +16,18 @@ pub fn build(b: *std.Build) void {
b.installArtifact(exe);
const run_step = b.step("run", "Run the app");
const run_cmd = b.addRunArtifact(exe);
run_step.dependOn(&run_cmd.step);
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const exe_tests = b.addTest(.{
const tests = b.addTest(.{
.root_module = exe.root_module,
});
const run_exe_tests = b.addRunArtifact(exe_tests);
const run_tests = b.addRunArtifact(tests);
const test_step = b.step("test", "Run tests");
test_step.dependOn(&run_exe_tests.step);
test_step.dependOn(&run_tests.step);
}

View File

@@ -1,9 +1,14 @@
const std = @import("std");
const x = @import("protocol.zig");
pub fn main() !void {
std.debug.print("All your {s} are belong to us.\n", .{"codebase"});
}
test {
_ = @import("protocol.zig");
}
test "simple test" {
const gpa = std.testing.allocator;
var list: std.ArrayList(i32) = .empty;
@@ -11,14 +16,3 @@ test "simple test" {
try list.append(gpa, 42);
try std.testing.expectEqual(@as(i32, 42), list.pop());
}
test "fuzz example" {
const Context = struct {
fn testOne(context: @This(), input: []const u8) anyerror!void {
_ = context;
// Try passing `--fuzz` to `zig build test` and see if it manages to fail this test case!
try std.testing.expect(!std.mem.eql(u8, "canyoufindme", input));
}
};
try std.testing.fuzz(Context{}, Context.testOne, .{});
}

32
src/protocol.zig Normal file
View File

@@ -0,0 +1,32 @@
const std = @import("std");
const DataV1 = struct {
// TODO: Implement version!!
// version: i8,
count: u8,
};
const SerializationError = error{ VersionDoesNotMatchError, OtherError };
fn deserialize(input: []u8) SerializationError!DataV1 {
if (input.len == 0) {
return SerializationError.OtherError;
}
return .{ .count = input[0] };
}
fn serialize(allocator: std.mem.Allocator, input: DataV1) ![]u8 {
const data = try allocator.alloc(u8, 1);
data[0] = input.count;
return data;
}
test "expect DataV1 can be serialized and deserialized" {
const expected: DataV1 = .{ .count = 128 };
const serialized = try serialize(std.testing.allocator, expected);
defer std.testing.allocator.free(serialized);
const actual = try deserialize(serialized);
try std.testing.expectEqual(expected, actual);
}