package mcp-kit

  1. Overview
  2. Docs

Source file util.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
(** Shared utilities for keyword compilers. *)

type nonneg_int_bound = Within_int of int | Above_int

let bound_to_string = function
  | Within_int n -> string_of_int n
  | Above_int -> "greater than max_int"

let actual_greater_than_bound actual = function
  | Within_int n -> actual > n
  | Above_int -> false

let actual_less_than_bound actual = function
  | Within_int n -> actual < n
  | Above_int -> true

let decimal_intlit_bound s =
  let len = String.length s in
  if len = 0 then None
  else
    let rec loop acc i =
      if i = len then Some (Within_int acc)
      else
        match s.[i] with
        | '0' .. '9' as c ->
            let digit = Char.code c - Char.code '0' in
            if acc > (max_int - digit) / 10 then Some Above_int
            else loop ((acc * 10) + digit) (i + 1)
        | _ -> None
    in
    loop 0 0

(** Extract a non-negative integer bound from a schema value. The result keeps
    JSON integers larger than OCaml [max_int] representable for count checks. *)
let to_nonneg_int_bound (j : Yojson.Safe.t) =
  match j with
  | `Int n when n >= 0 -> Some (Within_int n)
  | `Float f when f >= 0.0 && Float.is_integer f && Float.is_finite f ->
      if f > Float.of_int max_int then Some Above_int
      else Some (Within_int (Float.to_int f))
  | `Intlit s -> decimal_intlit_bound s
  | _ -> None

let to_nonneg_int j =
  match to_nonneg_int_bound j with
  | Some (Within_int n) -> Some n
  | Some Above_int | None -> None