Skip to content

Commit

Permalink
Simplify Eio by bypassing Eio.Flow.copy
Browse files Browse the repository at this point in the history
  • Loading branch information
SGrondin committed Jun 12, 2023
1 parent effcce6 commit b7ee038
Showing 1 changed file with 26 additions and 36 deletions.
62 changes: 26 additions & 36 deletions eio/angstrom_eio.ml
Original file line number Diff line number Diff line change
Expand Up @@ -31,65 +31,55 @@
POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------------*)

open Eio.Std
open Angstrom.Buffered

let default_buffer_size = 4096

let default_pushback () = ()

let handle_parse_result state =
match state_to_unconsumed state with
| None -> assert false
| Some us -> us, state_to_result state

let finalize w state =
let finalize r state =
(match state with
| Done _
|Fail _ ->
| Fail _ ->
state
| Partial feed -> feed `Eof)
|> handle_parse_result
|> Promise.resolve w

class ['a] parser_sink (parser : 'a Angstrom.t) pushback =
let p, w = Promise.create () in
object
inherit Eio.Flow.sink

method copy src =
let buf = Cstruct.create default_buffer_size in
let rec loop = function
| (Done _ as state)
|(Fail _ as state) ->
finalize w state
| Partial feed as state -> (
match src#read_into buf with
| 0
|(exception End_of_file) ->
finalize w state
| len ->
let next = feed (`Bigstring (Bigstringaf.sub buf.buffer ~off:0 ~len)) in
pushback ();
loop next )
in
loop (parse parser)

method data = Promise.await p
end

let default_pushback () = ()
|> fun x -> r := Some x

let parse ?(pushback = default_pushback) parser src =
let sink = new parser_sink parser pushback in
Eio.Flow.copy src sink;
sink#data
let r = ref None in
let buf = Cstruct.create default_buffer_size in
let rec loop = function
| (Done _ as state)
| (Fail _ as state) ->
finalize r state
| Partial feed as state -> (
match src#read_into buf with
| 0
| (exception End_of_file) ->
finalize r state
| len ->
let next = feed (`Bigstring (Bigstringaf.sub buf.buffer ~off:0 ~len)) in
pushback ();
loop next )
in
loop (parse parser);
match !r with
| None -> assert false
| Some x -> x

let rec buffered_state_loop pushback state src (buf : Cstruct.t) =
match state with
| Partial k ->
let next =
match src#read_into buf with
| 0
|(exception End_of_file) ->
| (exception End_of_file) ->
k `Eof
| len -> k (`Bigstring (Bigstringaf.sub buf.buffer ~off:0 ~len))
in
Expand Down

0 comments on commit b7ee038

Please sign in to comment.