(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) (* The JSONB bytes as sqlite/src/json.c at version-3.54.1 reads and edits them (jsonb.html): headers and sizes, validity, labels and their escapes, and the path search that also edits in place. Indexes, sizes and error codes follow the C, so an edit leaves the bytes sqlite3 leaves; C's NUL-terminated reads become [byte] and [zc], which answer 0 past the end. *) (* ── Element types and limits ─────────────────────────────────── *) let t_null = 0 let t_true = 1 let t_false = 2 let t_int = 3 (* INT5 = 4 *) let t_float = 5 (* FLOAT5 = 6 *) let t_text = 7 let t_textj = 8 let t_text5 = 9 let t_textraw = 10 let t_array = 11 let t_object = 12 (* JSON_MAX_DEPTH *) let max_depth = 1000 (* ── Character classes (sqlite3CtypeMap, jsonIsOk, jsonIsSpace) ─ *) let is_space c = c = 0x20 || c = 0x09 || c = 0x0a || c = 0x0d let is_digit c = c >= 0x30 && c <= 0x39 let is_xdigit c = is_digit c || (c >= 0x61 && c <= 0x66) || (c >= 0x41 && c <= 0x46) let is_alpha c = (c >= 0x61 && c <= 0x7a) || (c >= 0x41 && c <= 0x5a) let is_alnum c = is_alpha c || is_digit c (* the characters a string holds without an escape; '\'' is JSON5's *) let is_ok c = c >= 0x20 && c <> 0x22 && c <> 0x27 && c <> 0x5c (* jsonHexToInt *) let hex_value h = let h = h + (9 * (1 land (h lsr 6))) in h land 0xf (* ── The blob under construction or edit (JsonParse) ──────────── *) type op = Search | Del | Repl | Ins | Put | Ains type t = { mutable a : Bytes.t; mutable n : int; mutable sz : int; mutable has_nonstd : bool; mutable depth : int; mutable err : int; mutable op : op; mutable delta : int; mutable ins : string; mutable at : int; mutable path : string; } let empty cap = { a = Bytes.make (max cap 16) '\000'; n = 0; sz = 0; has_nonstd = false; depth = 0; err = 0; op = Search; delta = 0; ins = ""; at = 0; path = "$"; } let of_blob s = let t = empty (String.length s + 16) in Bytes.blit_string s 0 t.a 0 (String.length s); t.n <- String.length s; t let contents t = Bytes.sub_string t.a 0 t.n let pp ppf t = for i = 0 to t.n - 1 do Fmt.pf ppf "%02X" (Char.code (Bytes.get t.a i)) done let byte t i = if i < Bytes.length t.a then Char.code (Bytes.unsafe_get t.a i) else 0 let set t i c = Bytes.unsafe_set t.a i (Char.unsafe_chr (c land 0xff)) (* jsonBlobExpand *) let reserve t need = if need > Bytes.length t.a then begin let cap = max need (2 * Bytes.length t.a) + 100 in let a = Bytes.make cap '\000' in Bytes.blit t.a 0 a 0 t.n; t.a <- a end let append_byte t c = reserve t (t.n + 1); set t t.n c; t.n <- t.n + 1 let size_bytes sz = if sz <= 11 then 0 else if sz <= 0xff then 1 else if sz <= 0xffff then 2 else 4 let write_bytes a i typ sz extra = let set i c = Bytes.unsafe_set a i (Char.unsafe_chr (c land 0xff)) in match extra with | 0 -> set i (typ lor (sz lsl 4)) | 1 -> set i (typ lor 0xc0); set (i + 1) sz | 2 -> set i (typ lor 0xd0); set (i + 1) (sz lsr 8); set (i + 2) sz | _ -> set i (typ lor 0xe0); set (i + 1) (sz lsr 24); set (i + 2) (sz lsr 16); set (i + 3) (sz lsr 8); set (i + 4) sz let write_header t i typ sz extra = write_bytes t.a i typ sz extra let append_header t typ sz = reserve t (t.n + sz + 9); let extra = size_bytes sz in write_header t t.n typ sz extra; t.n <- t.n + 1 + extra let append_node t typ s off len = append_header t typ len; Bytes.blit_string s off t.a t.n len; t.n <- t.n + len let node typ s = let len = String.length s in let extra = size_bytes len in let a = Bytes.create (1 + extra + len) in write_bytes a 0 typ len extra; Bytes.blit_string s 0 a (1 + extra) len; Bytes.unsafe_to_string a let header typ sz = let extra = size_bytes sz in let a = Bytes.create (1 + extra) in write_bytes a 0 typ sz extra; Bytes.unsafe_to_string a let be t i k = let rec go v j = if j >= k then v else go ((v lsl 8) lor byte t (i + j)) (j + 1) in go 0 0 (* jsonbPayloadSize: the header's length at [i], 0 if it is malformed, with the payload's size left in [t.sz] *) let size t i = let nb = t.n in let fail () = t.sz <- 0; 0 in let fits n sz = if i + sz + n > nb && i + sz + n > nb - t.delta then fail () else begin t.sz <- sz; n end in if i >= nb then fail () else match byte t i lsr 4 with | x when x <= 11 -> fits 1 x | 12 -> if i + 1 >= nb then fail () else fits 2 (byte t (i + 1)) | 13 -> if i + 2 >= nb then fail () else fits 3 (be t (i + 1) 2) | 14 -> if i + 4 >= nb then fail () else fits 5 (be t (i + 1) 4) | _ -> if i + 8 >= nb || be t (i + 1) 4 <> 0 then fail () else fits 9 (be t (i + 5) 4) (* jsonBlobChangePayloadSize *) let change_payload_size t i sz = let extra = match byte t i lsr 4 with | x when x <= 11 -> 0 | 12 -> 1 | 13 -> 2 | 14 -> 4 | _ -> 8 in let needed = size_bytes sz in let delta = needed - extra in if delta > 0 then begin reserve t (t.n + delta); Bytes.blit t.a (i + 1) t.a (i + 1 + delta) (t.n - (i + 1)) end else if delta < 0 then Bytes.blit t.a (i + 1 - delta) t.a (i + 1) (t.n - (i + 1 - delta)); t.n <- t.n + delta; write_header t i (byte t i land 0x0f) sz needed; delta (* ── Escapes and labels ──────────────────────────────────────── *) (* the byte of [z] at [i], or 0 past its end *) let zc z i = if i < String.length z then Char.code (String.unsafe_get z i) else 0 let is_2hex z i = is_xdigit (zc z i) && is_xdigit (zc z (i + 1)) let is_4hex z i = is_2hex z i && is_2hex z (i + 2) let invalid_char = 0x99999 (* sqlite3Utf8ReadLimited *) let utf8_read_limited z off n = let c0 = zc z off in if c0 < 0xc0 then (c0, 1) else let lead = if c0 < 0xe0 then c0 land 0x1f else if c0 < 0xf0 then c0 land 0x0f else if c0 < 0xf8 then c0 land 0x07 else if c0 < 0xfc then c0 land 0x03 else if c0 < 0xfe then c0 land 0x01 else 0 in let n = min n 4 in let rec go c i = if i < n && zc z (off + i) land 0xc0 = 0x80 then go ((c lsl 6) + (zc z (off + i) land 0x3f)) (i + 1) else (c land 0xffff_ffff, i) in go lead 1 (* jsonBytesToBypass *) let bytes_to_bypass z off n = let c i = zc z (off + i) in let rec go i = if i + 1 >= n || c i <> 0x5c then i else if c (i + 1) = 0x0a then go (i + 2) else if c (i + 1) = 0x0d then if i + 2 < n && c (i + 2) = 0x0a then go (i + 3) else go (i + 2) else if c (i + 1) = 0xe2 && i + 3 < n && c (i + 2) = 0x80 && (c (i + 3) = 0xa8 || c (i + 3) = 0xa9) then go (i + 4) else i in go 0 let hex4_value z i = (hex_value (zc z i) lsl 12) lor (hex_value (zc z (i + 1)) lsl 8) lor (hex_value (zc z (i + 2)) lsl 4) lor hex_value (zc z (i + 3)) let unicode_escape z off n = if n < 6 then (invalid_char, n) else let v = hex4_value z (off + 2) in if v land 0xfc00 = 0xd800 && n >= 12 && zc z (off + 6) = 0x5c && zc z (off + 7) = 0x75 && hex4_value z (off + 8) land 0xfc00 = 0xdc00 then ( ((v land 0x3ff) lsl 10) + (hex4_value z (off + 8) land 0x3ff) + 0x10000, 12 ) else (v, 6) (* jsonUnescapeOneChar *) let rec unescape_one z off n = let c i = zc z (off + i) in if n < 2 then (invalid_char, n) else match c 1 with | 0x75 -> unicode_escape z off n | 0x62 -> (0x08, 2) | 0x66 -> (0x0c, 2) | 0x6e -> (0x0a, 2) | 0x72 -> (0x0d, 2) | 0x74 -> (0x09, 2) | 0x76 -> (0x0b, 2) | 0x30 -> ((if n > 2 && is_digit (c 2) then invalid_char else 0), 2) | (0x27 | 0x22 | 0x2f | 0x5c) as x -> (x, 2) | 0x78 -> if n < 4 then (invalid_char, n) else ((hex_value (c 2) lsl 4) lor hex_value (c 3), 4) | 0xe2 | 0x0d | 0x0a -> continuation z off n | _ -> (invalid_char, 2) and continuation z off n = let skip = bytes_to_bypass z off n in if skip = 0 then (invalid_char, n) else if skip = n then (0, n) else let v, k = if zc z (off + skip) = 0x5c then unescape_one z (off + skip) (n - skip) else utf8_read_limited z (off + skip) (n - skip) in (v, skip + k) let add_utf8 b v = let add c = Buffer.add_char b (Char.chr (c land 0xff)) in if v <= 0x7f then add v else if v <= 0x7ff then begin add (0xc0 lor (v lsr 6)); add (0x80 lor (v land 0x3f)) end else if v < 0x10000 then begin add (0xe0 lor (v lsr 12)); add (0x80 lor ((v lsr 6) land 0x3f)); add (0x80 lor (v land 0x3f)) end else begin add (0xf0 lor (v lsr 18)); add (0x80 lor ((v lsr 12) land 0x3f)); add (0x80 lor ((v lsr 6) land 0x3f)); add (0x80 lor (v land 0x3f)) end let unescaped z = let sz = String.length z in let b = Buffer.create sz in let rec go k = if k < sz then ( if z.[k] <> '\\' then begin Buffer.add_char b z.[k]; go (k + 1) end else let v, len = unescape_one z k (sz - k) in if v <> invalid_char then add_utf8 b v; go (k + len)) in go 0; Buffer.contents b type label = { z : string; off : int; len : int; raw : bool } let label_char l = if l.len = 0 then (0, l) else let c, k = if l.raw || zc l.z l.off <> 0x5c then if zc l.z l.off >= 0xc0 then utf8_read_limited l.z l.off l.len else (zc l.z l.off, 1) else unescape_one l.z l.off l.len in (c, { l with off = l.off + k; len = l.len - k }) (* jsonLabelCompare *) let label_equal l r = if l.raw && r.raw then l.len = r.len && String.sub l.z l.off l.len = String.sub r.z r.off r.len else let rec go l r = let cl, l = label_char l in let cr, r = label_char r in cl = cr && (cl = 0 || go l r) in go l r (* ── Validity (jsonbValidityCheck, jsonArgIsJsonb) ────────────── *) let rec scan_bytes t ok j k = if j >= k then 0 else if ok (byte t j) then scan_bytes t ok (j + 1) k else j + 1 let valid_int t i p sz = let neg = byte t p = 0x2d in if sz < 1 || (neg && sz < 2) then i + 1 else scan_bytes t is_digit (if neg then p + 1 else p) (p + sz) let valid_int5 t i p sz = let neg = byte t p = 0x2d in if sz < 3 || (neg && sz < 4) then i + 1 else let j = if neg then p + 1 else p in if byte t j <> 0x30 then i + 1 else if byte t (j + 1) <> 0x78 && byte t (j + 1) <> 0x58 then j + 2 else scan_bytes t is_xdigit (j + 2) (p + sz) let rec float_digits t ~json5 i j k seen = if j >= k then if seen = 0 then i + 1 else 0 else let c = byte t j in if is_digit c then float_digits t ~json5 i (j + 1) k seen else if c = 0x2e then if seen > 0 then j + 1 else if (not json5) && (j = k - 1 || not (is_digit (byte t (j + 1)))) then j + 1 else float_digits t ~json5 i (j + 1) k 1 else if c = 0x65 || c = 0x45 then if seen = 2 || j = k - 1 then j + 1 else if byte t (j + 1) = 0x2b || byte t (j + 1) = 0x2d then if j + 1 = k - 1 then j + 2 else float_digits t ~json5 i (j + 2) k 2 else float_digits t ~json5 i (j + 1) k 2 else j + 1 let valid_float t ~json5 i p sz = let k = p + sz in let neg = byte t p = 0x2d in if sz < 2 || (neg && sz < 3) then i + 1 else let j = if neg then p + 1 else p in if byte t j = 0x2e then if (not json5) || not (is_digit (byte t (j + 1))) then j + 1 else float_digits t ~json5 i (j + 2) k 1 else if byte t j = 0x30 && not json5 then let c = byte t (j + 1) in if j + 3 > k || (c <> 0x2e && c <> 0x65 && c <> 0x45) then j + 1 else float_digits t ~json5 i (j + 1) k 0 else float_digits t ~json5 i j k 0 let valid_escaped t ~json5 p sz = let k = p + sz in let s = Bytes.sub_string t.a p sz in let rec go j = if j >= k then 0 else let c = byte t j in if is_ok c || c = 0x27 then go (j + 1) else if c = 0x22 || c <= 0x1f then if json5 then go (j + 1) else j + 1 else if c <> 0x5c || j + 1 >= k then j + 1 else escape j (byte t (j + 1)) and escape j c1 = (* strchr finds the terminating NUL too *) if c1 = 0 || String.contains "\"\\/bfnrt" (Char.chr c1) then go (j + 2) else if c1 = 0x75 then if j + 5 >= k || not (is_4hex s (j + 2 - p)) then j + 1 else go (j + 2) else if not json5 then j + 1 else let v, len = unescape_one s (j - p) (k - j) in if v = invalid_char then j + 1 else go (j + len) in go p let rec validity t i stop depth = let n = size t i in let sz = t.sz and p = i + n in if depth > max_depth || n = 0 || i + n + sz <> stop then i + 1 else match byte t i land 0x0f with | 0 | 1 | 2 -> if n + sz = 1 then 0 else i + 1 | 3 -> valid_int t i p sz | 4 -> valid_int5 t i p sz | (5 | 6) as x -> valid_float t ~json5:(x = 6) i p sz | 7 -> scan_bytes t (fun c -> is_ok c || c = 0x27) p (p + sz) | (8 | 9) as x -> valid_escaped t ~json5:(x = 9) p sz | 10 -> 0 | (11 | 12) as x -> valid_elements t ~obj:(x = 12) p (p + sz) depth | _ -> i + 1 and valid_elements t ~obj j k depth = let rec go j cnt = if j >= k then if obj && cnt land 1 <> 0 then j + 1 else 0 else let n = size t j in let sz = t.sz in let ty = byte t j land 0x0f in if n = 0 || j + n + sz > k then j + 1 else if obj && cnt land 1 = 0 && (ty < t_text || ty > t_textraw) then j + 1 else let sub = validity t j (j + n + sz) (depth + 1) in if sub <> 0 then sub else go (j + n + sz) (cnt + 1) in go j 0 let is_jsonb s = let len = String.length s in len > 0 && let t = of_blob s in let c = byte t 0 in c land 0x0f <= t_object && let n = size t 0 in n > 0 && t.sz + n = len && (c land 0x0f > t_false || t.sz = 0) && (t.sz > 7 || (c <> 0x7b && c <> 0x5b && not (is_digit c)) || validity t 0 len 1 = 0) (* ── Path search and edit (jsonLookupStep) ────────────────────── *) let lookup_error = -1 let not_found = -2 let not_array = -3 let path_too_deep = -4 let path_error = -5 (* jsonbArrayCount *) let array_count t root = let n = size t root in let stop = root + n + t.sz in let rec go i k n = if n > 0 && i < stop then let n = size t i in go (i + t.sz + n) (k + 1) n else k in go (root + n) 0 n (* jsonAfterEditSizeAdjust *) let after_edit_size_adjust t root = let nb = t.n in t.n <- Bytes.length t.a; ignore (size t root : int); t.n <- nb; let sz = t.sz + t.delta in t.delta <- t.delta + change_payload_size t root sz (* the header width and the width before it that [ins], widened by [d] bytes, takes, if one exists (jsonBlobOverwrite) *) let widened c0 d = match c0 lsr 4 with | 12 -> if (1 lsl d) land 0x8a = 0 then None else Some (d + 2, 2) | 13 -> if d <> 2 && d <> 6 then None else Some (d + 3, 3) | 14 -> if d <> 4 then None else Some (9, 5) | 15 -> None | _ -> if (1 lsl d) land 0x116 = 0 then None else Some (d + 1, 1) (* jsonBlobOverwrite *) let overwrite t at ins d = let c0 = Char.code ins.[0] in match if c0 land 0x0f <= 2 then None else widened c0 d with | None -> false | Some (hdr, old_hdr) -> let top = [| 0xc0; 0xd0; 0; 0xe0; 0; 0; 0; 0xf0 |] in let payload = String.length ins - old_hdr in set t at (c0 land 0x0f lor top.(hdr - 2)); Bytes.blit_string ins old_hdr t.a (at + hdr) payload; for i = 1 to hdr - 1 do set t (at + i) (payload lsr (8 * (hdr - 1 - i))) done; true (* jsonBlobEdit *) let blob_edit t del ndel ins nins = let d = nins - ndel in let done_ = match ins with | Some s when d < 0 && d >= -8 -> overwrite t del s (-d) | _ -> false in if not done_ then begin if d <> 0 then begin reserve t (t.n + d); Bytes.blit t.a (del + ndel) t.a (del + nins) (t.n - (del + ndel)); t.n <- t.n + d; t.delta <- t.delta + d end; match ins with | Some s when nins > 0 -> Bytes.blit_string s 0 t.a del nins | _ -> () end let pc path k = zc path k let edit_at t path off root label = let n = size t root in let sz = t.sz + n in match t.op with | Del -> if label > 0 then blob_edit t label (sz + root - label) None 0 else blob_edit t root sz None 0 | Ains when pc path (off - 1) <> 0x5d -> raise_notrace Exit | Ains -> blob_edit t root 0 (Some t.ins) (String.length t.ins) | Repl | Put -> blob_edit t root sz (Some t.ins) (String.length t.ins) | Ins | Search -> () let path_key path off = if pc path off = 0x22 then let rec close i = if pc path (off + i) = 0 || pc path (off + i) = 0x22 then i else if pc path (off + i) = 0x5c && pc path (off + i + 1) <> 0 then close (i + 2) else close (i + 1) in let i = close 1 in if pc path (off + i) = 0 then None else let key = String.sub path (off + 1) (i - 1) in Some ( { z = path; off = off + 1; len = i - 1; raw = not (String.contains key '\\'); }, off + i + 1 ) else let rec close i = let c = pc path (off + i) in if c = 0 || c = 0x2e || c = 0x5b then i else close (i + 1) in let i = close 0 in if i = 0 then None else Some ({ z = path; off; len = i; raw = true }, off + i) let path_index t root path off = let cap = 0xffffffff in let rec number i v = if is_digit (pc path (off + i)) then number (i + 1) (if v < cap then (v * 10) + pc path (off + i) - 0x30 else v) else (i, v) in let i, kk = number 1 0 in if i >= 2 && pc path (off + i) = 0x5d then Ok (kk, off + i + 1) else if pc path (off + 1) <> 0x23 then Error path_error else let count = array_count t root in let i, kk = if pc path (off + 2) = 0x2d && is_digit (pc path (off + 3)) then let i, nn = number 3 0 in (i, if nn > count then -1 else count - nn) else (2, count) in if kk < 0 then Error not_found else if pc path (off + i) <> 0x5d then Error path_error else Ok (kk, off + i + 1) let inserting t = t.op = Ins || t.op = Put || t.op = Ains let rec lookup t root path off label = match pc path off with | 0 -> if t.op <> Search then edit_at t path off root label; root | 0x2e -> ( match path_key path (off + 1) with | None -> path_error | Some (key, rest) -> if byte t root land 0x0f <> t_object then not_found else lookup_key t root path key rest) | 0x5b -> ( if byte t root land 0x0f <> t_array then not_found else match path_index t root path off with | Error rc -> rc | Ok (kk, rest) -> lookup_index t root path kk rest) | _ -> path_error and descend t root v path rest label = t.depth <- t.depth + 1; if t.depth >= max_depth then path_too_deep else let rc = lookup t v path rest label in t.depth <- t.depth - 1; if t.delta <> 0 then after_edit_size_adjust t root; rc and lookup_key t root path key rest = let n = size t root in let stop = root + n + t.sz in let rec labels j = let x = byte t j land 0x0f in let n = size t j in let sz = t.sz and k = j + n in if j >= stop then `Absent j else if x < t_text || x > t_textraw || n = 0 || k + sz >= stop then `Code lookup_error else let label = { z = Bytes.sub_string t.a k sz; off = 0; len = sz; raw = x = t_text || x = t_textraw; } in let v = k + sz in let vn = if byte t v land 0x0f > t_object then 0 else size t v in if vn = 0 then `Code lookup_error else if label_equal key label then if v + vn + t.sz > stop then `Code lookup_error else `Code (descend t root v path rest j) else labels (v + vn + t.sz) in match labels (root + n) with | `Code rc -> rc | `Absent j -> if j > stop then lookup_error else if inserting t then insert_label t root path key rest j else not_found and insert_label t root path key rest j = if t.op = Ains && not (String.ends_with ~suffix:"]" (String.sub path rest (String.length path - rest))) then not_array else let hdr = header (if key.raw then t_textraw else t_text5) key.len in let rc, v = edit_substructure t path rest in if rc < 0 then rc else begin let nhdr = String.length hdr in blob_edit t j 0 None (nhdr + key.len + String.length v); Bytes.blit_string hdr 0 t.a j nhdr; Bytes.blit_string path key.off t.a (j + nhdr) key.len; Bytes.blit_string v 0 t.a (j + nhdr + key.len) (String.length v); if t.delta <> 0 then after_edit_size_adjust t root; rc end and lookup_index t root path kk rest = let n = size t root in let stop = root + n + t.sz in let rec walk j kk = if j >= stop then `End (j, kk) else if kk = 0 then `Code (descend t root j path rest 0) else let n = size t j in if n = 0 then `Code lookup_error else walk (j + n + t.sz) (kk - 1) in match walk (root + n) kk with | `Code rc -> rc | `End (j, kk) -> if j > stop then lookup_error else if kk > 0 then not_found else if inserting t then begin let rc, v = edit_substructure t path rest in if rc >= 0 then blob_edit t j 0 (Some v) (String.length v); if t.delta <> 0 then after_edit_size_adjust t root; rc end else not_found (* jsonCreateEditSubstructure *) and edit_substructure t path off = if pc path off = 0 then (0, t.ins) else let ins = empty 16 in append_byte ins (if pc path off = 0x2e then t_object else t_array); ins.op <- t.op; ins.ins <- t.ins; ins.depth <- t.depth + 1; if ins.depth >= max_depth then (path_too_deep, "") else let rc = try lookup ins 0 path off 0 with Exit -> not_array in t.depth <- t.depth - 1; (rc, contents ins) let search t path off = t.delta <- 0; t.depth <- 0; try lookup t 0 path off 0 with Exit -> not_array