lib/choir/src/core/format.zig
daab053ee43316e1809a84551d573ddd1e5bf3d2
1 const std = @import("std");
2
3 pub fn appendFmt(
4 buf: []u8,
5 pos: usize,
6 comptime fmt: []const u8,
7 args: anytype,
8 ) !usize {
9 const slice = try std.fmt.bufPrint(buf[pos..], fmt, args);
10 return pos + slice.len;
11 }
12
13 pub fn intPayload(buf: []u8, value: anytype) ![]const u8 {
14 return std.fmt.bufPrint(buf, "{d}", .{value});
15 }
16
17 test "format.appendFmt appends and advances position" {
18 const testing = std.testing;
19 var buf: [32]u8 = undefined;
20
21 var pos: usize = 0;
22 pos = try appendFmt(buf[0..], pos, "hello", .{});
23 pos = try appendFmt(buf[0..], pos, " {s} {d}", .{ "world", 42 });
24
25 try testing.expectEqualStrings("hello world 42", buf[0..pos]);
26 }
27
28 test "format.intPayload formats integers" {
29 const testing = std.testing;
30 var buf: [16]u8 = undefined;
31
32 const payload = try intPayload(buf[0..], 12345);
33 try testing.expectEqualStrings("12345", payload);
34 }
35
36 test "format.appendFmt errors on small buffer" {
37 const testing = std.testing;
38 var buf: [4]u8 = undefined;
39
40 try testing.expectError(error.NoSpaceLeft, appendFmt(buf[0..], 0, "hello", .{}));
41 }
42
43 test "format.intPayload errors on small buffer" {
44 const testing = std.testing;
45 var buf: [2]u8 = undefined;
46
47 try testing.expectError(error.NoSpaceLeft, intPayload(buf[0..], 123));
48 }