authorgravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2022-01-16 23:38:08-08:00
committergravatar for kubkon@jakubkonka.comJakub Konka <kubkon@jakubkonka.com> 2022-01-17 12:32:02+01:00
log0d0f277954e8809ac537d11ff536639aed8f2724
treead3749963859c1850fedf0800d5478a42c5cd8e6
parentf72a0a290735636775f83eaebf689357bee50778

std: add json.stringifyAlloc


1 files changed, 20 insertions(+), 0 deletions(-)

lib/std/json.zig+20
......@@ -3333,3 +3333,23 @@ test "stringify null optional fields" {
33333333 .{ .allocator = std.testing.allocator },
33343334 ));
33353335}
3336
3337// Same as `stringify` but accepts an Allocator and stores result in dynamically allocated memory instead of using a Writer.
3338// Caller owns returned memory.
3339pub fn stringifyAlloc(allocator: std.mem.Allocator, value: anytype, options: StringifyOptions) ![]const u8 {
3340 var list = std.ArrayList(u8).init(allocator);
3341 errdefer list.deinit();
3342 try stringify(value, options, list.writer());
3343 return list.toOwnedSlice();
3344}
3345
3346test "stringify alloc" {
3347 const allocator = std.testing.allocator;
3348 const expected =
3349 \\{"foo":"bar","answer":42,"my_friend":"sammy"}
3350 ;
3351 const actual = try stringifyAlloc(allocator, .{ .foo = "bar", .answer = 42, .my_friend = "sammy" }, .{});
3352 defer allocator.free(actual);
3353
3354 try std.testing.expectEqualStrings(expected, actual);
3355}