From 0d0f277954e8809ac537d11ff536639aed8f2724 Mon Sep 17 00:00:00 2001 From: Meghan Denny Date: Sun, 16 Jan 2022 23:38:08 -0800 Subject: [PATCH] std: add json.stringifyAlloc --- lib/std/json.zig | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/lib/std/json.zig b/lib/std/json.zig index 658fec6b79..4009bf9c7f 100644 --- a/lib/std/json.zig +++ b/lib/std/json.zig @@ -3333,3 +3333,23 @@ test "stringify null optional fields" { .{ .allocator = std.testing.allocator }, )); } + +// Same as `stringify` but accepts an Allocator and stores result in dynamically allocated memory instead of using a Writer. +// Caller owns returned memory. +pub fn stringifyAlloc(allocator: std.mem.Allocator, value: anytype, options: StringifyOptions) ![]const u8 { + var list = std.ArrayList(u8).init(allocator); + errdefer list.deinit(); + try stringify(value, options, list.writer()); + return list.toOwnedSlice(); +} + +test "stringify alloc" { + const allocator = std.testing.allocator; + const expected = + \\{"foo":"bar","answer":42,"my_friend":"sammy"} + ; + const actual = try stringifyAlloc(allocator, .{ .foo = "bar", .answer = 42, .my_friend = "sammy" }, .{}); + defer allocator.free(actual); + + try std.testing.expectEqualStrings(expected, actual); +}