Printf.printf and 'Bytes' argument


#1

With Printf.printf “%s…” we can directly insert a “String” argument.

What about inserting a “Bytes” argument?


#2

I believe that was overlooked when rushing in the bytes stuff. It would indeed both be logical and convenient if there was such a thing.


#3

You can use Printf.printf "%s" (Bytes.to_string b).


#4

or Printf.printf "%a" output_bytes bytes.

It saves a copy so in theory it’s more efficient, but I don’t like that it works only for Printf.printf and Printf.fprintf.


#5

In many cases Bytes.unsafe_of_string is reasonable to use in a Printf expression. Clearly depends on the case, but have a look at the Unsafe conversion chapter in the ocaml manual


#6

@mseri I believe you mean Bytes.unsafe_to_string (“to”) to convert it to a string. :wink:

Having to use memory-unsafe type coercion to produce a printf converter for bytes kind of defeats the point of having a nicely typed printf module in the first place IMHO.


#7

There’s some discussion about this in Mantis PR 6429: A format specifier for bytes.

One option for the moment is to use ppx_custom_printf, which allows you to write %{Bytes} as the format specifier, like this:

let b = Bytes.of_string "abc" in
Printf.printf !"a bytes value: %{Bytes}.\n" b