From: Brendan Hansen Date: Fri, 20 Oct 2023 19:38:40 +0000 (-0500) Subject: added: `json.decode_into` and `json.decode_with_result` X-Git-Url: https://git.brendanfh.com/?a=commitdiff_plain;h=a2b5f8db70ef524b9fec743a36090bb3694d1637;p=onyx.git added: `json.decode_into` and `json.decode_with_result` --- diff --git a/core/container/slice.onyx b/core/container/slice.onyx index 41d12081..169d5172 100644 --- a/core/container/slice.onyx +++ b/core/container/slice.onyx @@ -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 {} diff --git a/core/encoding/json/decoder.onyx b/core/encoding/json/decoder.onyx index 5f617e2e..9937db7f 100644 --- a/core/encoding/json/decoder.onyx +++ b/core/encoding/json/decoder.onyx @@ -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; +}