(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) (* Finally tagged: the combinators build a GADT over the element types, and the interpreters below walk it to read JSONB bytes in place, to write them, and to cross to and from {!Jsonb_value.t}. *) module C = Jsonb_core module V = Jsonb_value type _ t = | Null : 'a -> 'a t | Bool : bool t | Int : string t | Float : string t | Text : string t | Element : string t | Ignore : unit t | Array : 'a t -> 'a list t | Members : 'a t -> (string * 'a) list t | Map : ('a, 'b) map -> 'b t | Any : 'a any -> 'a t | Value : V.t t | Json_value : Json.t t and ('a, 'b) map = { kind : string; dec : ('a -> 'b) option; enc : ('b -> 'a) option; inner : 'a t; } and 'a any = { any_kind : string; null : 'a t option; bool : 'a t option; int : 'a t option; float : 'a t option; text : 'a t option; array : 'a t option; object_ : 'a t option; pick : ('a -> 'a t) option; } let null v = Null v let bool = Bool let int = Int let float = Float let text = Text let element = Element let ignore = Ignore let array c = Array c let members c = Members c let map ?(kind = "map") ?dec ?enc inner = Map { kind; dec; enc; inner } let any ?(kind = "any") ?null ?bool ?int ?float ?text ?array ?object' ?enc () = Any { any_kind = kind; null; bool; int; float; text; array; object_ = object'; pick = enc; } let json = Json_value module Value = struct let t = Value end let rec kind : type a. a t -> string = function | Null _ -> "null" | Bool -> "bool" | Int -> "int" | Float -> "float" | Text -> "text" | Element -> "element" | Ignore -> "ignore" | Array c -> "array of " ^ kind c | Members c -> "members of " ^ kind c | Map m -> m.kind | Any a -> a.any_kind | Value -> "value" | Json_value -> "JSON value" let malformed () = Jsonb_error.fail_malformed () let mismatch c ty = Jsonb_error.fail_sort ~exp:(kind c) ~fnd:(Jsonb_sort.of_code ty) (* An INT whose text is hexadecimal is JSON5's INT5. *) let int_type s = if String.contains s 'x' || String.contains s 'X' then C.t_int + 1 else C.t_int (* ── Reading the bytes ───────────────────────────────────────── *) (* the codec [a] holds for the element type [ty] *) let pick_any a ty = match ty with | 0 -> a.null | 1 | 2 -> a.bool | 3 | 4 -> a.int | 5 | 6 -> a.float | 7 | 8 | 9 | 10 -> a.text | 11 -> a.array | 12 -> a.object_ | _ -> malformed () let rec value_at t i depth = let n = C.size t i in if n = 0 then malformed (); let sz = t.C.sz and p = i + n in let payload () = Bytes.sub_string t.C.a p sz in match C.byte t i land 0x0f with | 0 -> V.Null | 1 -> V.True | 2 -> V.False | 3 -> V.Int (payload ()) | 4 -> V.Int5 (payload ()) | 5 -> V.Float (payload ()) | 6 -> V.Float5 (payload ()) | 7 -> V.Text (payload ()) | 8 -> V.Textj (payload ()) | 9 -> V.Text5 (payload ()) | 10 -> V.Textraw (payload ()) | (11 | 12) as ty -> if depth > C.max_depth then Jsonb_error.fail_too_deep (); let stop = p + sz in let rec go j acc = if j >= stop then List.rev acc else let n = C.size t j in if n = 0 then malformed (); let next = j + n + t.C.sz in if next > stop then malformed (); go next (value_at t j (depth + 1) :: acc) in let vs = go p [] in if ty = 11 then V.Array vs else let rec pairs = function | [] -> [] | ((V.Text _ | V.Textj _ | V.Text5 _ | V.Textraw _) as k) :: v :: rest -> (k, v) :: pairs rest | _ -> malformed () in V.Object (pairs vs) | _ -> malformed () (* A number's RFC 8259 text as nox-json's number, the text kept where [Number] would not write it back as it is ([-0], [1.50], [9e999]). *) let number_of_text s = let n = Json.Number.of_string s in match n with | Some n when Json.Number.source_lexeme n = Some s -> n | Some ((Int _ | Uint _) as n) when Json.Number.to_string n = s -> n | _ -> let value = Option.value ~default:Float.nan (float_of_string_opt s) in Json.Number.Decimal { lexeme = s; value } (* the element at [i] as nox-json's value: an INT5 or FLOAT5 as json() writes it, a TEXTJ or TEXT5 with its escapes read *) let rec json_at t i depth : Json.t = let n = C.size t i in if n = 0 then malformed (); let sz = t.C.sz and p = i + n in let payload () = Bytes.sub_string t.C.a p sz in let number s = Json.Number (number_of_text s, Json.Meta.none) in match C.byte t i land 0x0f with | 0 -> Json.Value.null () | 1 -> Json.Value.bool true | 2 -> Json.Value.bool false | 3 | 5 -> number (payload ()) | 4 | 6 -> number (Json_text.text_at t i) | 7 | 10 -> Json.Value.string (payload ()) | 8 | 9 -> Json.Value.string (C.unescaped (payload ())) | (11 | 12) as ty -> if depth > C.max_depth then Jsonb_error.fail_too_deep (); let stop = p + sz in let rec go j acc = if j >= stop then List.rev acc else let n = C.size t j in if n = 0 then malformed (); let next = j + n + t.C.sz in if next > stop then malformed (); go next (json_at t j (depth + 1) :: acc) in let vs = go p [] in if ty = 11 then Json.Value.list vs else let rec members = function | [] -> [] | Json.String (k, _) :: v :: rest -> Json.Value.member (Json.Value.name k) v :: members rest | _ -> malformed () in Json.Value.object' (members vs) | _ -> malformed () let payload : type a. a t -> C.t -> int -> (int -> bool) -> string = fun c t i ok -> let n = C.size t i in if n = 0 then malformed (); let sz = t.C.sz and ty = C.byte t i land 0x0f in if not (ok ty) then mismatch c ty else if sz = 0 then malformed () else Bytes.sub_string t.C.a (i + n) sz let rec dec_at : type a. a t -> C.t -> int -> a = fun c t i -> match c with | Map m -> ( match m.dec with | Some f -> f (dec_at m.inner t i) | None -> Jsonb_error.fail_no_decoder m.kind) | Any a -> ( let n = C.size t i in if n = 0 then malformed (); match pick_any a (C.byte t i land 0x0f) with | Some c -> dec_at c t i | None -> mismatch (Any a) (C.byte t i land 0x0f)) | Value -> value_at t i 1 | Json_value -> json_at t i 1 | Element -> let n = C.size t i in if n = 0 then malformed (); Bytes.sub_string t.C.a i (n + t.C.sz) | Ignore -> if C.size t i = 0 then malformed () | Null v -> ( let n = C.size t i in if n = 0 then malformed (); match C.byte t i land 0x0f with | 0 -> if t.C.sz <> 0 then malformed () else v | ty -> mismatch c ty) | Bool -> ( let n = C.size t i in if n = 0 then malformed (); match C.byte t i land 0x0f with | (1 | 2) as ty -> if t.C.sz <> 0 then malformed () else ty = 1 | ty -> mismatch c ty) | Int -> payload c t i (fun ty -> ty = 3 || ty = 4) | Float -> payload c t i (fun ty -> ty = 5 || ty = 6) | Text -> ( let n = C.size t i in if n = 0 then malformed (); let sz = t.C.sz in match C.byte t i land 0x0f with | 7 | 10 -> Bytes.sub_string t.C.a (i + n) sz | 8 | 9 -> C.unescaped (Bytes.sub_string t.C.a (i + n) sz) | ty -> mismatch c ty) | Array e -> ( let n = C.size t i in if n = 0 then malformed (); match C.byte t i land 0x0f with | 11 -> let stop = i + n + t.C.sz in let rec go j acc = if j >= stop then List.rev acc else let n = C.size t j in if n = 0 then malformed (); let next = j + n + t.C.sz in if next > stop then malformed (); go next (dec_at e t j :: acc) in go (i + n) [] | ty -> mismatch c ty) | Members e -> ( let n = C.size t i in if n = 0 then malformed (); match C.byte t i land 0x0f with | 12 -> let stop = i + n + t.C.sz in let next j = let n = C.size t j in if n = 0 then malformed (); let next = j + n + t.C.sz in if next > stop then malformed (); next in let rec go j acc = if j >= stop then List.rev acc else let ty = C.byte t j land 0x0f in if ty < C.t_text || ty > C.t_textraw then malformed (); let v = next j in if v >= stop then malformed (); let after = next v in let k = dec_at Text t j in go after ((k, dec_at e t v) :: acc) in go (i + n) [] | ty -> mismatch c ty) (* ── Writing the bytes ───────────────────────────────────────── *) let container t typ elements = let start = t.C.n in C.append_byte t typ; elements (); Stdlib.ignore (C.change_payload_size t start (t.C.n - start - 1) : int) let rec value_into t (v : V.t) = let node typ s = C.append_node t typ s 0 (String.length s) in match v with | Null -> C.append_byte t C.t_null | True -> C.append_byte t C.t_true | False -> C.append_byte t C.t_false | Int s -> node C.t_int s | Int5 s -> node (C.t_int + 1) s | Float s -> node C.t_float s | Float5 s -> node (C.t_float + 1) s | Text s -> node C.t_text s | Textj s -> node C.t_textj s | Text5 s -> node C.t_text5 s | Textraw s -> node C.t_textraw s | Array vs -> container t C.t_array (fun () -> List.iter (value_into t) vs) | Object ms -> container t C.t_object (fun () -> List.iter (fun (k, v) -> value_into t k; value_into t v) ms) (* nox-json's value as JSONB: a number as the text it was read from, or as sqlite3 writes the integer or real, NaN as NULL; a string TEXTRAW *) let rec json_into t (v : Json.t) = let node typ s = C.append_node t typ s 0 (String.length s) in match v with | Null _ -> C.append_byte t C.t_null | Bool (b, _) -> C.append_byte t (if b then C.t_true else C.t_false) | Number (n, _) -> ( match Json.Number.source_lexeme n with | Some s -> let real = String.exists (fun c -> c = '.' || c = 'e' || c = 'E') s in node (if real then C.t_float else C.t_int) s | None -> ( match n with | Int i -> node C.t_int (Int64.to_string i) | Uint u -> node C.t_int (Fmt.str "%Lu" u) | Float f | Decimal { value = f; _ } -> if Float.is_nan f then C.append_byte t C.t_null else if f = Float.infinity then node C.t_float "9e999" else if f = Float.neg_infinity then node C.t_float "-9e999" else node C.t_float (Value_ops.text_of_float f))) | String (s, _) -> node C.t_textraw s | Array (vs, _) -> container t C.t_array (fun () -> List.iter (json_into t) vs) | Object (ms, _) -> container t C.t_object (fun () -> List.iter (fun ((k, _), v) -> node C.t_textraw k; json_into t v) ms) let rec enc_into : type a. a t -> a -> C.t -> unit = fun c v t -> match c with | Null _ -> C.append_byte t C.t_null | Bool -> C.append_byte t (if v then C.t_true else C.t_false) | Int -> C.append_node t (int_type v) v 0 (String.length v) | Float -> C.append_node t C.t_float v 0 (String.length v) | Text -> C.append_node t C.t_textraw v 0 (String.length v) | Element -> C.reserve t (t.C.n + String.length v); Bytes.blit_string v 0 t.C.a t.C.n (String.length v); t.C.n <- t.C.n + String.length v | Ignore -> Jsonb_error.fail_no_encoder "ignore" | Array e -> container t C.t_array (fun () -> List.iter (fun x -> enc_into e x t) v) | Members e -> container t C.t_object (fun () -> List.iter (fun (k, x) -> C.append_node t C.t_textraw k 0 (String.length k); enc_into e x t) v) | Map m -> ( match m.enc with | Some f -> enc_into m.inner (f v) t | None -> Jsonb_error.fail_no_encoder m.kind) | Any a -> ( match a.pick with | Some f -> enc_into (f v) v t | None -> Jsonb_error.fail_no_encoder a.any_kind) | Value -> value_into t v | Json_value -> json_into t v (* One element as its bytes, a scalar under its exact header with no intermediate buffer. *) let rec to_bytes : type a. a t -> a -> string = fun c v -> match c with | Element -> v | Null _ -> "\000" | Bool -> if v then "\001" else "\002" | Int -> C.node (int_type v) v | Float -> C.node C.t_float v | Text -> C.node C.t_textraw v | Map m -> ( match m.enc with | Some f -> to_bytes m.inner (f v) | None -> Jsonb_error.fail_no_encoder m.kind) | Any a -> ( match a.pick with | Some f -> to_bytes (f v) v | None -> Jsonb_error.fail_no_encoder a.any_kind) | Ignore | Array _ | Members _ | Value | Json_value -> let t = C.empty 16 in enc_into c v t; C.contents t (* ── Values ──────────────────────────────────────────────────── *) let pick_value a (v : V.t) = match v with | Null -> a.null | True | False -> a.bool | Int _ | Int5 _ -> a.int | Float _ | Float5 _ -> a.float | Text _ | Textj _ | Text5 _ | Textraw _ -> a.text | Array _ -> a.array | Object _ -> a.object_ let value_mismatch c v = Jsonb_error.fail_sort ~exp:(kind c) ~fnd:(Some (V.sort v)) let rec decode : type a. a t -> V.t -> a = fun c v -> match (c, v) with | Value, v -> v | Json_value, v -> let t = C.empty 16 in value_into t v; json_at t 0 1 | Map m, v -> ( match m.dec with | Some f -> f (decode m.inner v) | None -> Jsonb_error.fail_no_decoder m.kind) | Any a, v -> ( match pick_value a v with | Some c -> decode c v | None -> value_mismatch (Any a) v) | Ignore, _ -> () | Element, v -> let t = C.empty 16 in value_into t v; C.contents t | Null x, V.Null -> x | Bool, V.True -> true | Bool, V.False -> false | Int, (V.Int s | V.Int5 s) -> s | Float, (V.Float s | V.Float5 s) -> s | Text, (V.Text s | V.Textraw s) -> s | Text, (V.Textj s | V.Text5 s) -> C.unescaped s | Array e, V.Array vs -> List.map (decode e) vs | Members e, V.Object ms -> List.map (fun (k, v) -> (decode Text k, decode e v)) ms | (Null _ | Bool | Int | Float | Text | Array _ | Members _), v -> value_mismatch c v let rec encode : type a. a t -> a -> V.t = fun c x -> match c with | Value -> x | Json_value -> let t = C.empty 16 in json_into t x; value_at t 0 1 | Null _ -> V.Null | Bool -> if x then V.True else V.False | Int -> if int_type x = C.t_int then V.Int x else V.Int5 x | Float -> V.Float x | Text -> V.Textraw x | Element -> let t = C.of_blob x in if C.validity t 0 (String.length x) 1 <> 0 then malformed (); value_at t 0 1 | Ignore -> Jsonb_error.fail_no_encoder "ignore" | Array e -> V.Array (List.map (encode e) x) | Members e -> V.Object (List.map (fun (k, v) -> (V.Textraw k, encode e v)) x) | Map m -> ( match m.enc with | Some f -> encode m.inner (f x) | None -> Jsonb_error.fail_no_encoder m.kind) | Any a -> ( match a.pick with | Some f -> encode (f x) x | None -> Jsonb_error.fail_no_encoder a.any_kind)