cstr_array

Macro cstr_array 

Source
macro_rules! cstr_array {
    (@impl item
        ($([$attr:meta])*)
        ($($item_kind:tt)*)
        $name:ident = $val:expr; $($rest:tt)*
    ) => { ... };
    ($(#[$attr:meta])* static mut $($rest:tt)*) => { ... };
    ($(#[$attr:meta])* static $($rest:tt)*) => { ... };
    ($(#[$attr:meta])* const $($rest:tt)*) => { ... };
    ($val:expr) => { ... };
    () => { ... };
}
Expand description

Builds CStrArray from constant strings of various types.

This macro can construct a CStrArray<N> from a constant expression of any of these input types:

  • &CStr
  • &str
  • &[u8]
  • &[u8; N]

This performs the necessary nul presence checks at compile time.

§Examples

Pass a const expression of &CStr to build a CStrArray with the same length.

let x = cstr_array!(c"Buzz");
assert_eq!(x.len(), 4);

const NAME: &CStr = c"Sally";
let y = cstr_array!(NAME);
assert_eq!(y, c"Sally");

Pass a const expression of &str or &[u8] to build a CStrArray with the same length. A nul terminator is appended automatically.

assert_eq!(cstr_array!("Buzz"), cstr_array!(b"Buzz"));

It’s a compile-time failure to invoke cstr_array! with a nul inside the string.

_ = cstr_array!("nul is appended by the macro; don't include it\0");
_ = cstr_array!(b"nul\0in the middle");

Define static or const items by eliding the type.

The length of the CStrArray uses the length of the assigned string. Note that the assignment expression currently is evaluated twice, but this should have no effect due to it being in const.

const BYTE_ARRAY: [u8; 12] = *b"direct array";

cstr_array! {
    static STATIC = c"static";
    static mut STATIC_MUT = c"static_mut";
    const CONST = c"constant";

    static FROM_STR = concat!("checked", " for ", "nul");
    static FROM_BYTES_REF = b"also checked for nul";
    static FROM_BYTES_ARRAY = &BYTE_ARRAY;  // doesn't construct directly from array
}

assert_eq!(STATIC, c"static");
assert_eq!(unsafe { &*addr_of!(STATIC_MUT) }, c"static_mut");
assert_eq!(CONST, c"constant");

assert_eq!(FROM_STR, c"checked for nul");
assert_eq!(FROM_BYTES_REF, c"also checked for nul");
assert_eq!(FROM_BYTES_ARRAY, *c"direct array");