| ... | ... | @@ -3333,3 +3333,23 @@ test "stringify null optional fields" { |
| 3333 | 3333 | .{ .allocator = std.testing.allocator }, |
| 3334 | 3334 | )); |
| 3335 | 3335 | } |
| 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. |
| 3339 | pub 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 | |
| 3346 | test "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 | } |