feat headers: expose parsing helper

This commit is contained in:
Simon Cruanes 2024-12-02 14:19:06 -05:00
parent bde09435b4
commit e1bfe70991
No known key found for this signature in database
GPG key ID: EBFFF6F283F3A2B4
2 changed files with 23 additions and 10 deletions

View file

@ -46,6 +46,21 @@ let for_all pred s =
true true
with Exit -> false with Exit -> false
let parse_line_ (line : string) : _ result =
try
let i =
try String.index line ':'
with Not_found -> failwith "invalid header, missing ':'"
in
let k = String.sub line 0 i in
if not (for_all is_tchar k) then
failwith (Printf.sprintf "Invalid header key: %S" k);
let v =
String.sub line (i + 1) (String.length line - i - 1) |> String.trim
in
Ok (k, v)
with Failure msg -> Error msg
let parse_ ~(buf : Buf.t) (bs : IO.Input.t) : t = let parse_ ~(buf : Buf.t) (bs : IO.Input.t) : t =
let rec loop acc = let rec loop acc =
match IO.Input.read_line_using_opt ~buf bs with match IO.Input.read_line_using_opt ~buf bs with
@ -56,16 +71,10 @@ let parse_ ~(buf : Buf.t) (bs : IO.Input.t) : t =
bad_reqf 400 "bad header line, not ended in CRLF" bad_reqf 400 "bad header line, not ended in CRLF"
| Some line -> | Some line ->
let k, v = let k, v =
try match parse_line_ line with
let i = String.index line ':' in | Ok r -> r
let k = String.sub line 0 i in | Error msg ->
if not (for_all is_tchar k) then bad_reqf 400 "invalid header line: %s\nline is: %S" msg line
invalid_arg (Printf.sprintf "Invalid header key: %S" k);
let v =
String.sub line (i + 1) (String.length line - i - 1) |> String.trim
in
k, v
with _ -> bad_reqf 400 "invalid header line: %S" line
in in
loop ((String.lowercase_ascii k, v) :: acc) loop ((String.lowercase_ascii k, v) :: acc)
in in

View file

@ -33,3 +33,7 @@ val pp : Format.formatter -> t -> unit
(** Pretty print the headers. *) (** Pretty print the headers. *)
val parse_ : buf:Buf.t -> IO.Input.t -> t val parse_ : buf:Buf.t -> IO.Input.t -> t
(**/*)
val parse_line_ : string -> (string * string, string) result
(**/*)