try_bytes

Macro try_bytes 

Source
macro_rules! try_bytes {
    ($x:literal) => { ... };
}
Expand description

Macro for creating a ByteArray from a string literal with automatic format detection.

§Format Detection

  • With 0x prefix: Parses as hexadecimal
  • With 0b prefix: Parses as binary
  • With 0o prefix: Parses as octal (not yet implemented)
  • No prefix: CAVEAT - Silently converts to UTF-8 encoding

§CAVEAT

When no format prefix (0x, 0b, 0o) is provided, this macro will silently interpret the input as UTF-8 and convert it to bytes. If you intend to parse hex or binary data, you must include the appropriate prefix, or use try_hex! or try_bin! instead.

§Examples

use byte_array_ops::try_bytes;

// Hex with prefix
let hex = try_bytes!("0xdeadbeef").unwrap();
assert_eq!(hex.as_bytes(), [0xde, 0xad, 0xbe, 0xef]);

// Binary with prefix
let bin = try_bytes!("0b11110000").unwrap();
assert_eq!(bin.as_bytes(), [0xf0]);

// No prefix - silently converts to UTF-8
let utf8 = try_bytes!("hello").unwrap();
assert_eq!(utf8.as_bytes(), b"hello");