Skip to main content

format_bytes

Macro format_bytes 

Source
macro_rules! format_bytes {
    ($($args: tt)*) => { ... };
}
Expand description

Creates a Vec<u8> using interpolation of runtime expressions.

The first argument format_bytes! receives is a format string. This must be a string literal, or a bytestring literal holding valid UTF-8. The power of the formatting string is in the {}s contained.

Literal braces are written {{ and }}.

Additional arguments passed to format_bytes! replace the {}s within the formatting string in the order given. Named arguments, given after positional ones as name = value, replace each {name}. A {name} with no such argument uses the variable name from the caller’s scope. Each argument is evaluated once.

These additional arguments may have any type that implements the DisplayBytes trait.

§Examples

use format_bytes::format_bytes;

assert_eq!(format_bytes!(b""), b"");
assert_eq!(format_bytes!(b"here"), b"here");
assert_eq!(format_bytes!("é{}", b"\xe9"), b"\xc3\xa9\xe9");
assert_eq!(format_bytes!(b"this {{ escapes }}"), b"this { escapes }");
assert_eq!(format_bytes!(b"also this {{}}"), b"also this {}");
assert_eq!(format_bytes!(b"this works {{{}}}", b"a"), b"this works {a}");
assert_eq!(
    format_bytes!(b"look at those {} bytes", &[0u8, 1, 2]),
    b"look at those \x00\x01\x02 bytes"
);

let bytes = vec![0u8, 1, 2];

assert_eq!(
    format_bytes!(b"look at those {} bytes", bytes),
    b"look at those \x00\x01\x02 bytes"
);
assert_eq!(
    format_bytes!(b"{}.{}.{}.{}", 1_i32, 2_u8, 3_f32, &4),
    b"1.2.3.4"
);
assert_eq!(
    format_bytes!(b"what about this very very long message {}?", "here".as_bytes()),
    b"what about this very very long message here?".to_vec()
);
assert_eq!(format_bytes!(b"{}", std::borrow::Cow::Borrowed("cow".as_bytes())), b"cow");