macro_rules! cstr8 { ($s:expr) => { ... }; }
Expand description
Create a const &’static CStr8
from a const string.
The macro accepts any of the following string-like types as input, causing a compile error if they contain a nul byte or aren’t UTF-8:
&str
&CStr
&[u8]
&[u8; N]
[u8; N]
§Examples
use core::ffi::CStr;
use cstr8::{cstr8, CStr8};
const LITERAL: &CStr8 = cstr8!("literal");
assert_eq!(LITERAL, "literal");
assert_eq!(LITERAL.as_bytes_with_nul(), b"literal\0");
const CONSTANT: &str = "constant";
const WITH_NUL: &CStr8 = cstr8!(CONSTANT);
assert_eq!(WITH_NUL, "constant");
assert_eq!(WITH_NUL.as_bytes_with_nul(), b"constant\0");
const CSTR_CONSTANT: &CStr = c"cstr constant";
assert_eq!(cstr8!(CSTR_CONSTANT).as_bytes_with_nul(), b"cstr constant\0");
const BYTES_CONSTANT: &[u8] = b"bytes constant";
assert_eq!(cstr8!(BYTES_CONSTANT).as_bytes_with_nul(), b"bytes constant\0");
const BYTE_ARRAY_REF_CONSTANT: &[u8; 23] = b"byte array ref constant";
assert_eq!(cstr8!(BYTE_ARRAY_REF_CONSTANT).as_bytes_with_nul(), b"byte array ref constant\0");
const BYTE_ARRAY_CONSTANT: [u8; 19] = *b"byte array constant";
assert_eq!(cstr8!(BYTE_ARRAY_CONSTANT).as_bytes_with_nul(), b"byte array constant\0");
Internal nul bytes will cause a compilation error:
ⓘ
const ERROR: &CStr8 = cstr8!("oh \0 no");
//~^ ERROR: cstr8: input contains nul byte
Invalid UTF-8 will also cause a compilation error:
ⓘ
const ERROR: &CStr8 = cstr8!(b"Invalid sequence identifier: \xa0\xa1");
//~^ ERROR: cstr8: input is not valid UTF-8
§Restrictions
The cstr8!
macro can’t reference any generic types, even if constant.
Once inline_const
stabilizes, this restriction can be lifted.
ⓘ
use cstr8::{cstr8, CStr8};
trait Name {
const NAME: &'static str = "sample name";
}
fn cstr8_name<T: Name>() -> &'static CStr8 {
cstr8!(T::NAME)
//~^ ERROR: can't use generic parameters from outer item
}