Format bytestring as escaped literal

I have a bytestring that is almost certainly ascii, with a small chance of being utf-8, and an even smaller chance of being some other encoding.

I want to print it in such a way that looks good in the ascii case and preserves all the information in the non-ascii case, while still being somewhat readable in both cases.

Examples:
abc"abc"
12<NUL>34"12\x0032"

I think bstr::ByteSlice::escape_bytes should do that.

There is also [u8]::escape_ascii in the standard library. For details, see the documentation for std::ascii::escape_default (which it uses under the hood).

This differs from bstr::ByteSlice::escape_bytes in a few ways:

  • escape_ascii escapes quote characters \' and \" while escape_bytes does not.
  • escape_ascii escapes NUL as \x00 while escape_bytes uses \0.
  • escape_ascii escapes all non-ASCII bytes, while escape_bytes passes through non-ASCII Unicode unchanged if it is encoded as UTF-8.
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.