Commit 0866396308

mateusz <19653795+mateusz834@users.noreply.github.com>
2023-04-07 14:01:09
std.json: allow returning custom errors from custom stringify
1 parent dac6242
Changed files (2)
lib/std/json.zig
@@ -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 => {
@@ -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);
+}
src/Autodoc.zig
@@ -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;