From 46e77092326ec6a944e025afd707f656f4871458 Mon Sep 17 00:00:00 2001 From: CJ van den Berg Date: Thu, 12 Mar 2026 21:42:13 +0100 Subject: [PATCH] feat: add slightly more robust fmtBuf API --- src/cbor.zig | 6 ++++++ test/tests.zig | 14 ++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/src/cbor.zig b/src/cbor.zig index 65cc773..c6cbfa8 100644 --- a/src/cbor.zig +++ b/src/cbor.zig @@ -301,6 +301,12 @@ pub fn fmt(buf: []u8, value: anytype) []const u8 { return writer.buffered(); } +pub fn fmtBuf(buf: []u8, value: anytype) Io.Writer.Error![]const u8 { + var writer: Io.Writer = .fixed(buf); + try writeValue(&writer, value); + return writer.buffered(); +} + const CborType = struct { type: u8, minor: u5, major: u3 }; pub fn decodeType(iter: *[]const u8) error{TooShort}!CborType { diff --git a/test/tests.zig b/test/tests.zig index 6015882..538409d 100644 --- a/test/tests.zig +++ b/test/tests.zig @@ -9,6 +9,7 @@ const expectEqualStrings = std.testing.expectEqualStrings; const expectError = std.testing.expectError; const fmt = cbor_mod.fmt; +const fmtBuf = cbor_mod.fmtBuf; const toJson = cbor_mod.toJson; const toJsonPretty = cbor_mod.toJsonPretty; const fromJson = cbor_mod.fromJson; @@ -44,6 +45,19 @@ test "cbor simple" { ); } +test "cbor.fmtBuf success" { + var buf: [128]u8 = undefined; + try expectEqualDeep( + try fmtBuf(&buf, .{ "five", 5, "four", 4, .{ "three", 3 } }), + &[_]u8{ 0x85, 0x64, 0x66, 0x69, 0x76, 0x65, 0x05, 0x64, 0x66, 0x6f, 0x75, 0x72, 0x04, 0x82, 0x65, 0x74, 0x68, 0x72, 0x65, 0x65, 0x03 }, + ); +} + +test "cbor.fmtBuf overflow" { + var buf: [4]u8 = undefined; + try expectError(error.NoSpaceLeft, fmtBuf(&buf, .{ "five", 5, "four", 4, .{ "three", 3 } })); +} + test "cbor exit message" { var buf: [128]u8 = undefined; try expectEqualDeep(