falco_event/types/format/bytebuf.rs
1use std::fmt::{Debug, Formatter, Write};
2
3/// Falco-style byte buffer formatter
4///
5/// The default [`Debug`] impl prints out the buffer as an ASCII string, replacing non-printable
6/// characters with dots (`.`).
7///
8/// The hex debug implementation (`{:x?}`) generates a hex dump of the whole buffer.
9pub struct ByteBufFormatter<'a>(pub &'a [u8]);
10
11impl Debug for ByteBufFormatter<'_> {
12 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
13 // https://users.rust-lang.org/t/idiomatic-to-implement-the-debug-trait-for-x-syntax/84955
14 #[allow(deprecated)]
15 if f.flags() & 16 != 0 {
16 let mut first = true;
17 for c in self.0 {
18 if first {
19 first = false;
20 } else {
21 write!(f, " ")?;
22 }
23 write!(f, "{:02x}", *c)?;
24 }
25 } else {
26 for c in self.0 {
27 let c = *c;
28 if !(b' '..=0x7e).contains(&c) {
29 f.write_char('.')?;
30 } else {
31 f.write_char(c as char)?;
32 }
33 }
34 }
35
36 Ok(())
37 }
38}