Skip to content

Commit

Permalink
added: json.as_any and json.encode_string_opt
Browse files Browse the repository at this point in the history
  • Loading branch information
brendanfh committed Jan 20, 2024
1 parent 51f549e commit 1b2aca0
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ Additions:
- `core.list.empty`
- `core.conv.parse`
- `core.conv.parse_with_allocator`
- `core.encoding.json.encode_string_opt`
- `core.encoding.json.as_any` overload

Removals:
- Compiler test cases are no longer shipped with toolchain.
Expand Down
16 changes: 16 additions & 0 deletions core/encoding/json/encoder.onyx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@ encode_string :: (v: $T, allocator := context.allocator) -> (str, Encoding_Error
return s, .None;
}

encode_string_opt :: (v: $T, allocator := context.allocator) -> ? str {
s, err := encode_string(v, allocator);
if err != .None {
return .None;
}

return s;
}

//
// This could be changed to use the "any" type now, which would allow for any type to be
// represented as a json value. However, this eliminates the control that you get from
Expand Down Expand Up @@ -388,6 +397,13 @@ to_any :: as_any

as_any :: #match #local {}

#overload
as_any :: macro (value: Value, $T: type_expr) -> T {
x: T;
#this_package.as_any(value, &x);
return x;
}

#overload
as_any :: macro (value: Value, out: ^$T) {
#this_package.to_any(value, T, out);
Expand Down
1 change: 1 addition & 0 deletions tests/json_test
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@
main.Union_Test { v1 = None, v2 = Some(123) }
{"v1":null,"v2":123}
{"v1":null,"v2":123}
[ { foo = 1 }, { foo = 2 } ]
6 changes: 6 additions & 0 deletions tests/json_test.onyx
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,10 @@ main :: () {
core.print("\n");
json.encode(&core.stdio.print_writer, ut);
core.print("\n");

json.as_any(j.root, [] struct {
@json.Custom_Key.{"x"}
foo: i32
})
|> core.println();
}

0 comments on commit 1b2aca0

Please sign in to comment.