Source

calcoq / reader.ml

open Str
open Util

(** decode : string -> string **)
let decode text =
  let parce_char c = match c with
    | '0'..'9' -> int_of_char c - int_of_char '0'
    | 'a'..'f' -> 10 + int_of_char c - int_of_char 'a'
    | 'A'..'F' -> 10 + int_of_char c - int_of_char 'A'
    | _ -> failwith ("decode parce_char: " ^ String.make 1 c)
  in
  let rec aux i s =
    if i < String.length s then
      match s.[i] with
      | '+' -> (s.[i] <- ' '; aux (i+1) s)
      | '%' -> String.sub s 0 i
          ^ String.make 1 (char_of_int (16 * parce_char s.[i+1] + parce_char s.[i+2]))
          ^ aux 0 (String.sub s (i+3) (String.length s - i - 3))
      | _ -> aux (i+1) s
    else s
  in aux 0 text

(* TODO
let get_input () =
  let parse_16char = function
    | '0'..'9' -> int_of_char c - int_of_char '0'
    | 'a'..'f' -> 10 + int_of_char c - int_of_char 'a'
    | 'A'..'F' -> 10 + int_of_char c - int_of_char 'A'
    | _ -> failwith ("decode parse_16char: " ^ String.make 1 c)
	try
	  begin match read_char () with
	  | '+' -> (' '::)
*)

let read_all () =
  let rec iter store =
    try iter (read_line () :: store) with
    | End_of_file -> String.concat "" (List.rev store)
  in iter []

let get_text () =
  let input = decode (read_all ()) in
  if input = "" then ""
  else
    try
    let ps = List.map (split (regexp "=")) (split (regexp "&") input) in
    match List.find (function | "formula"::_ -> true | _ -> false) ps with
    | [formula] -> ""
    | [formula; t] -> t
    | _ -> failwith @@ "Reader.get_text: " ^ input
    with
    | e -> Printexc.to_string e ^ ": " ^ input