Skip to content

Commit

Permalink
std.json: allow returning custom errors from custom stringify
Browse files Browse the repository at this point in the history
  • Loading branch information
mateusz834 authored Apr 7, 2023
1 parent dac6242 commit 0866396
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
19 changes: 18 additions & 1 deletion lib/std/json.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2268,7 +2268,7 @@ pub fn stringify(
value: anytype,
options: StringifyOptions,
out_stream: anytype,
) @TypeOf(out_stream).Error!void {
) !void {
const T = @TypeOf(value);
switch (@typeInfo(T)) {
.Float, .ComptimeFloat => {
Expand Down Expand Up @@ -2767,3 +2767,20 @@ test "deserializing string with escape sequence into sentinel slice" {
// Double-check that we're getting the right result
try testing.expect(mem.eql(u8, result, "\n"));
}

test "stringify struct with custom stringify that returns a custom error" {
var ret = std.json.stringify(struct {
field: Field = .{},

pub const Field = struct {
field: ?[]*Field = null,

const Self = @This();
pub fn jsonStringify(_: Self, _: StringifyOptions, _: anytype) error{CustomError}!void {
return error.CustomError;
}
};
}{}, StringifyOptions{}, std.io.null_writer);

try std.testing.expectError(error.CustomError, ret);
}
2 changes: 1 addition & 1 deletion src/Autodoc.zig
Original file line number Diff line number Diff line change
Expand Up @@ -770,7 +770,7 @@ const DocData = struct {
self: Expr,
opts: std.json.StringifyOptions,
w: anytype,
) !void {
) @TypeOf(w).Error!void {
const active_tag = std.meta.activeTag(self);
var jsw = std.json.writeStream(w, 15);
if (opts.whitespace) |ws| jsw.whitespace = ws;
Expand Down

0 comments on commit 0866396

Please sign in to comment.