package mcp-kit

  1. Overview
  2. Docs

Source file json_pointer.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
(** JSON Pointer (RFC 6901). *)

type t = string list

let empty = []

let unescape token =
  let buf = Buffer.create (String.length token) in
  let len = String.length token in
  let i = ref 0 in
  while !i < len do
    if !i + 1 < len && token.[!i] = '~' then begin
      (match token.[!i + 1] with
      | '0' -> Buffer.add_char buf '~'
      | '1' -> Buffer.add_char buf '/'
      | c ->
          Buffer.add_char buf '~';
          Buffer.add_char buf c);
      i := !i + 2
    end
    else begin
      Buffer.add_char buf token.[!i];
      i := !i + 1
    end
  done;
  Buffer.contents buf

let escape token =
  let buf = Buffer.create (String.length token) in
  String.iter
    (fun c ->
      match c with
      | '~' -> Buffer.add_string buf "~0"
      | '/' -> Buffer.add_string buf "~1"
      | c -> Buffer.add_char buf c)
    token;
  Buffer.contents buf

let of_string s =
  if String.length s = 0 then Ok []
  else if s.[0] <> '/' then Error ("JSON Pointer must start with /: " ^ s)
  else
    let rest = String.sub s 1 (String.length s - 1) in
    let tokens = String.split_on_char '/' rest in
    Ok (List.map unescape tokens)

let to_string t =
  match t with [] -> "" | _ -> "/" ^ String.concat "/" (List.map escape t)

let array_index_in_bounds token length =
  let token_len = String.length token in
  if length = 0 || token_len = 0 then None
  else if token_len > 1 && token.[0] = '0' then None
  else
    let max_index = length - 1 in
    let rec loop acc i =
      if i = token_len then Some acc
      else
        match token.[i] with
        | '0' .. '9' as c ->
            let digit = Char.code c - Char.code '0' in
            if acc > (max_index - digit) / 10 then None
            else loop ((acc * 10) + digit) (i + 1)
        | _ -> None
    in
    loop 0 0

let resolve t json =
  let step json token =
    match json with
    | `Assoc pairs -> (
        match List.assoc_opt token pairs with Some v -> Some v | None -> None)
    | `List items -> (
        match array_index_in_bounds token (List.length items) with
        | Some i -> Some (List.nth items i)
        | _ -> None)
    | _ -> None
  in
  List.fold_left
    (fun acc token ->
      match acc with None -> None | Some json -> step json token)
    (Some json) t

let append t token = t @ [ token ]