Add Buf_write.printf (symbolic formatter) #652
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR adds
Eio.Buf_write.printf
andEio.Buf_write.get_formatter
.I decided to work on this when I saw this exchange:
@mbarbin in #642
@talex5
The
Format
module is surprisingly powerful and I wanted to support its full breadth of features. This is not possible by dropping down to a string withFormat.sprintf
.There are 2 ways to do this:
Format.make_formatter do_write do_flush
do_write
is(string -> int -> int -> unit)
do_flush
is(unit -> unit)
Format.make_symbolic_output_buffer
,Format.formatter_of_symbolic_output_buffer
andFormat.flush_symbolic_output_buffer
On the surface, using a Custom Formatter appears to be the way to go. It exposes the formatter's internal buffer (along with
pos
andlen
) in thedo_write
callback, letting us copy it into theBuf_write
buffer. The problem is that the formatter has its own buffering and we're forced to track whetherprintf
has been called in order to issue manual flushes of the formatter every time the user calls another writing function (likeBuf_write.string
,Buf_write.cstruct
, etc). It adds a lot of messy state toBuf_write.t
.With a symbolic formatter, the lifecycle of a call to
Buf_write.printf
does not leak into a dozen of other functions and it doesn't add mutable state toBuf_write.t
. I'm also able to "look ahead" in the pattern and issue exactly one call toensure_space
, one call towritable_exn
, and the minimal number of calls towake_writer
. The full range ofFormat
features is supported, including%a
and explicit flushes (%!
,@.
). The downside of the symbolic formatter is the increased allocations: it's a list of variants with nice sliced strings, not just offsets in a buffer. Overall I believe this is acceptable because of the other optimizations it enables.