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 137d5ba
Showing 1 changed file with 24 additions and 43 deletions.
67 changes: 24 additions & 43 deletions eio/angstrom_eio.ml
Original file line number Diff line number Diff line change
Expand Up @@ -31,65 +31,46 @@
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 =
(match state with
| Done _
|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 () = ()
let finalize = function
| Partial feed -> feed `Eof
| state -> state

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

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 All @@ -99,9 +80,9 @@ let rec buffered_state_loop pushback state src (buf : Cstruct.t) =

let with_buffered_parse_state ?(pushback = default_pushback) state src =
let buf = Cstruct.create default_buffer_size in
(match state with
( match state with
| Partial _ -> buffered_state_loop pushback state src buf
| _ -> state)
| _ -> state )
|> handle_parse_result

let async_many e k = Angstrom.(skip_many (e <* commit >>| k) <?> "async_many")
Expand Down

0 comments on commit 137d5ba

Please sign in to comment.