From 91c4f5249ac84416d654c1c5dc8b4b8dd90a7c2b Mon Sep 17 00:00:00 2001 From: Dione Julek Date: Thu, 25 Apr 2024 12:48:37 -0300 Subject: [PATCH] add printf to handle strings --- src/vshelper.zig | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/vshelper.zig b/src/vshelper.zig index fa0d08f..a37b8e6 100644 --- a/src/vshelper.zig +++ b/src/vshelper.zig @@ -106,3 +106,10 @@ pub fn mapGetN(comptime T: type, in: ?*const vs.Map, key: [*]const u8, index: c_ return if (err == .Success) val else null; } + +/// Format the string with a null-terminator to work properly with C API, you need to free the buf manually. +pub fn printf(allocator: std.mem.Allocator, buf: *?[]u8, comptime fmt: []const u8, args: anytype) []const u8 { + const err_msg = "Out of memory occurred while writing string."; + buf.* = allocator.alloc(u8, std.fmt.count(fmt, args) + 1) catch null; // +1 for "\x00" in bufPrintZ + return if (buf.*) |b| std.fmt.bufPrintZ(b, fmt, args) catch err_msg else err_msg; +}