#binary-data #byte-slice #logging #ascii #ascii-byte #no-std

no-std try-ascii

Helper to format byte slices that probably/mostly contain ASCII-encoded text

2 stable releases

1.1.0 Feb 23, 2024
1.0.0 Jan 23, 2024

#490 in Debugging

Download history 50/week @ 2024-07-25 21/week @ 2024-08-01 7/week @ 2024-08-08 12/week @ 2024-08-15 5/week @ 2024-08-29 67/week @ 2024-09-05 91/week @ 2024-09-12 73/week @ 2024-09-19 29/week @ 2024-09-26 70/week @ 2024-10-03 133/week @ 2024-10-10 13/week @ 2024-10-17 47/week @ 2024-10-24 12/week @ 2024-10-31 11/week @ 2024-11-07

101 downloads per month
Used in 3 crates

OLFL-1.3

9KB
106 lines

Try ASCII

Helper to format byte slices that probably/mostly contain ASCII-encoded text

This can be used to log binary data which is expected to be text but which is not guaranteed to be valid UTF-8. In these cases, it can be unfeasible to use std::str::from_utf8 because whenever that function fails, an Utf8Error would be logged instead of the actual data. Using try_ascii, the text parts are formatted as text while the binary parts fall back to the default Debug implementation for &[u8]:

use try_ascii::try_ascii;
println!("{:x?}", try_ascii(b"Hello, \xa0\xa1\xa2\xa3"));

Prints as:

Hello, [a0, a1, a2, a3]

You can either use the provided try_ascii function, or import the TryToAscii trait, that automatically implements try_ascii() for [u8], &[u8] and everything that implements AsRef<[u8]>:

use try_ascii::TryAscii;

// You can use .try_ascii() directly on a [u8]-slice:
println!("{:x?}", b"Hello, \xa0\xa1\xa2\xa3".try_ascii());

// ... or on &[u8] :
let slice: &[u8] = b"Hello, \xa0\xa1\xa2\xa3";
println!("{:x?}", slice.try_ascii());

// ... or on things that implement AsRef<[u8]>:
let slice: [u8; 11] = *b"Hello, \xa0\xa1\xa2\xa3";
println!("{:x?}", slice.as_ref().try_ascii());

License

Open Logistics Foundation License
Version 1.3, January 2023

See the LICENSE file in the top-level directory.

Contact

Fraunhofer IML Embedded Rust Group - embedded-rust@iml.fraunhofer.de

No runtime deps