(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) module C = Jsonb_core type t = C.t let of_string = C.of_blob let to_string = C.contents let root t = t.C.at <- 0; t.C.path <- "$" let to_path t = t.C.path let pp ppf t = Fmt.string ppf t.C.path let sort t = Jsonb_sort.of_code (C.byte t t.C.at land 0x0f) let get c t = Jsonb_codec.dec_at c t t.C.at let length t = if C.byte t t.C.at land 0x0f = C.t_array then C.array_count t t.C.at else 0 let failure rc : Jsonb_error.path = if rc = C.not_array then Not_array_element else if rc = C.lookup_error then Malformed else if rc = C.path_too_deep then Path_too_deep else Bad_path let dollar path = String.length path > 0 && String.unsafe_get path 0 = '$' let seek path t = if not (dollar path) then Error Jsonb_error.Bad_path else begin t.C.op <- Search; let rc = C.search t path 1 in if rc >= 0 then begin t.C.at <- rc; t.C.path <- path; Ok true end else if rc = C.not_found then Ok false else Error (failure rc) end (* jsonInsertIntoBlob for one path and value, and jsonRemoveFunc for one path: the edit leaves the focus at the root *) let edit op path ins t = t.C.at <- 0; t.C.path <- "$"; let rc = if String.length path = 1 then begin if op = C.Repl || op = C.Put then begin t.C.delta <- 0; C.blob_edit t 0 t.C.n (Some ins) (String.length ins) end; 0 end else begin t.C.op <- op; t.C.ins <- ins; C.search t path 1 end in t.C.op <- Search; if rc >= 0 || rc = C.not_found then Ok () else Error (failure rc) let editor op path c v t = if not (dollar path) then Error Jsonb_error.Bad_path else edit op path (Jsonb_codec.to_bytes c v) t let insert path c v t = editor C.Ins path c v t let replace path c v t = editor C.Repl path c v t let set path c v t = editor C.Put path c v t let array_insert path c v t = editor C.Ains path c v t let remove path t = if not (dollar path) then Error Jsonb_error.Bad_path else if String.length path = 1 then begin root t; t.C.delta <- 0; C.blob_edit t 0 t.C.n None 0; Ok () end else edit C.Del path "" t