cstr

Macro cstr 

Source
macro_rules! cstr {
    ($bytes:expr) => { ... };
}
Expand description

A macro to create a C-style *str pointer from a byte slice (does not allocate!) Returns a pointer to a null-terminated C-style *const _ (type inferred by caller, i8 or u8)

§Examples

Works with different pointer types:

let as_i8 = unsafe{ cstr!(b"hello")} as *const i8;
let as_u8 = unsafe{cstr!(b"world")} as *const u8;
unsafe {
    assert_eq!(*as_i8.offset(0), b'h' as i8);
    assert_eq!(*as_u8.offset(0), b'w' as u8);
}

Proper null termination:

let s:*const u8 = unsafe{cstr!(b"test")};
unsafe {
    assert_eq!(*s.offset(0), b't' );
    assert_eq!(*s.offset(1), b'e' );
    assert_eq!(*s.offset(2), b's' );
    assert_eq!(*s.offset(3), b't' );
    assert_eq!(*s.offset(4), 0);
}

Empty string case:

let empty:*const u8 = unsafe{cstr!(b"")};
unsafe {
    assert_eq!(*empty.offset(0), 0);
}

The macro will panic in debug mode if the input exceeds LOCAL_PATH_MAX: (Simplified example)

let long_string = [b'a'; 5000];
let will_crash:*const u8 = unsafe{cstr!(&long_string)}; // will crash yay!