From 1b2aca05dad39de2402299b57c996517088bd3bb Mon Sep 17 00:00:00 2001 From: Brendan Hansen Date: Fri, 19 Jan 2024 22:40:24 -0600 Subject: [PATCH] added: `json.as_any` and `json.encode_string_opt` --- CHANGELOG | 2 ++ core/encoding/json/encoder.onyx | 16 ++++++++++++++++ tests/json_test | 1 + tests/json_test.onyx | 6 ++++++ 4 files changed, 25 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index 635ff2cc..726792a8 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -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. diff --git a/core/encoding/json/encoder.onyx b/core/encoding/json/encoder.onyx index 2182f227..e6fd38c4 100644 --- a/core/encoding/json/encoder.onyx +++ b/core/encoding/json/encoder.onyx @@ -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 @@ -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); diff --git a/tests/json_test b/tests/json_test index 2ac867d5..5c8f0a4c 100644 --- a/tests/json_test +++ b/tests/json_test @@ -7,3 +7,4 @@ main.Union_Test { v1 = None, v2 = Some(123) } {"v1":null,"v2":123} {"v1":null,"v2":123} +[ { foo = 1 }, { foo = 2 } ] diff --git a/tests/json_test.onyx b/tests/json_test.onyx index c471c0a7..c9c9c336 100644 --- a/tests/json_test.onyx +++ b/tests/json_test.onyx @@ -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(); } -- 2.25.1