added: `json.decode_into` and `json.decode_with_result`
authorBrendan Hansen <brendan.f.hansen@gmail.com>
Fri, 20 Oct 2023 19:38:40 +0000 (14:38 -0500)
committerBrendan Hansen <brendan.f.hansen@gmail.com>
Fri, 20 Oct 2023 19:38:40 +0000 (14:38 -0500)
core/container/slice.onyx
core/encoding/json/decoder.onyx

index 41d12081b72efd834e219781162f8f4780b5da39..169d5172cca5d4b2908b2d15d7a82b39d04ce444 100644 (file)
@@ -621,6 +621,11 @@ chunks :: (arr: [] $T, width: i32) -> Iterator([] T) {
 
 
 #doc """
+    Groups a slice into sub-slices using the comparison function.
+
+    `comp` should evaluate to a boolean value.
+
+    Expects slice to sorted so all equal values are next to each other.
 """
 group_by :: #match #local {}
 
index 5f617e2e34cb13ad3f675ce8ce97afe2dd05a203..9937db7f35c7569aeb71f49dbba4fb7111c59381 100644 (file)
@@ -3,6 +3,12 @@ package core.encoding.json
 
 use core {*}
 
+#doc """
+    Unsafely decodes a strings into a json object, returning an invalid
+    Json value if it failed to parse.
+
+    This procedure is not very useful and should be considered deprecated.
+"""
 decode :: (data: str, allocator := context.allocator, print_errors := true) -> Json {
     json: Json;
     json.allocator = allocator;
@@ -38,6 +44,12 @@ Decode_Error :: #distinct ^_Decode_Error;
     position  :: (this: Decode_Error) => (cast(^_Decode_Error) this).pos;
 }
 
+#doc """
+    Decodes a string into a Json object, and returns the Json object and
+    and a `Decode_Error` that is non-null if an error occured.
+
+    This procedure should be considered deprecated in favor of `decode_with_result`.
+"""
 decode_with_error :: (data: str, allocator := context.allocator) -> (Json, Decode_Error) {
     json: Json;
     json.allocator = allocator;
@@ -61,3 +73,32 @@ decode_with_error :: (data: str, allocator := context.allocator) -> (Json, Decod
     json.root = root;
     return json, Decode_Error.{null};
 }
+
+#doc """
+    Decodes a string into a possible Json object. If parsing fails, an error is returned instead.
+"""
+decode_with_result :: (data: str, allocator := context.allocator) -> Result(Json, Error) {
+    root, err := parse(data, allocator);
+    if err.kind != .None {
+        return .{ Err = err };
+    }
+
+    return .{
+        Ok = .{ allocator, root }
+    };
+}
+
+#doc """
+    Decodes a string into any Onyx type.
+
+    Internally uses `decode_with_result` and `as_any`.
+"""
+decode_into :: (data: str, out: &$T) -> Error {
+    obj := decode_with_result(data)->catch([err] {
+        return return err;
+    });
+    defer delete(obj);
+
+    as_any(obj.root, out);
+    return .None;
+}