From 2ee92d2548dc2c11288831b912d0b67426e6e27e Mon Sep 17 00:00:00 2001 From: CJ van den Berg Date: Thu, 22 Jan 2026 15:34:19 +0100 Subject: [PATCH] refactor: move TypedInt to a module --- build.zig | 8 ++++++++ src/TypedInt.zig | 28 ++++++++++++++++++++++++++++ src/buffer/Buffer.zig | 19 ++----------------- 3 files changed, 38 insertions(+), 17 deletions(-) create mode 100644 src/TypedInt.zig diff --git a/build.zig b/build.zig index 04b8cd5..494476c 100644 --- a/build.zig +++ b/build.zig @@ -434,11 +434,19 @@ pub fn build_exe( .root_source_file = b.path("src/lsp_types.zig"), }); + const TypedInt_mod = b.createModule(.{ + .root_source_file = b.path("src/TypedInt.zig"), + .imports = &.{ + .{ .name = "cbor", .module = cbor_mod }, + }, + }); + const Buffer_mod = b.createModule(.{ .root_source_file = b.path("src/buffer/Buffer.zig"), .imports = &.{ .{ .name = "cbor", .module = cbor_mod }, .{ .name = "thespian", .module = thespian_mod }, + .{ .name = "TypedInt", .module = TypedInt_mod }, .{ .name = "vaxis", .module = vaxis_mod }, .{ .name = "file_type_config", .module = file_type_config_mod }, }, diff --git a/src/TypedInt.zig b/src/TypedInt.zig new file mode 100644 index 0000000..f46c6fe --- /dev/null +++ b/src/TypedInt.zig @@ -0,0 +1,28 @@ +pub fn Tagged(T: type, tag: []const u8) type { + return enum(T) { + _, + + pub const TAG = tag; + + pub fn cborEncode(self: @This(), writer: *Writer) Writer.Error!void { + const value: T = @intFromEnum(self); + try cbor.writeValue(writer, .{ TAG, value }); + } + + pub fn cborExtract(self: *@This(), iter: *[]const u8) cbor.Error!bool { + var value: T = 0; + if (try cbor.matchValue(iter, .{ TAG, cbor.extract(&value) })) { + self.* = @enumFromInt(value); + return true; + } + return false; + } + + pub fn format(self: @This(), writer: anytype) !void { + return writer.print("{s}:{d}", .{ TAG, @intFromEnum(self) }); + } + }; +} + +const Writer = @import("std").Io.Writer; +const cbor = @import("cbor"); diff --git a/src/buffer/Buffer.zig b/src/buffer/Buffer.zig index fa084b4..a7d547e 100644 --- a/src/buffer/Buffer.zig +++ b/src/buffer/Buffer.zig @@ -1,6 +1,7 @@ const std = @import("std"); const builtin = @import("builtin"); const cbor = @import("cbor"); +const TypedInt = @import("TypedInt"); const file_type_config = @import("file_type_config"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; @@ -1755,20 +1756,4 @@ pub fn to_ref(self: *Self) Ref { return @enumFromInt(@intFromPtr(self)); } -pub const Ref = enum(usize) { - _, - - pub fn cborEncode(self: @This(), writer: *std.Io.Writer) std.io.Writer.Error!void { - const value: usize = @intFromEnum(self); - try cbor.writeValue(writer, .{ "BREF", value }); - } - - pub fn cborExtract(self: *@This(), iter: *[]const u8) cbor.Error!bool { - var value: usize = 0; - if (try cbor.matchValue(iter, .{ "BREF", cbor.extract(&value) })) { - self.* = @enumFromInt(value); - return true; - } - return false; - } -}; +pub const Ref = TypedInt.Tagged(usize, "BREF");