abi_stable/macros/nul_str_macros.rs
1/// Constructs a [`NulStr`] from a string literal,
2/// truncating the string on internal nul bytes.
3///
4/// # Correctness
5///
6/// This truncates the passed in string if it contains nul bytes,
7/// which means that silent truncation can happen with arbitrary inputs,
8/// rather than compile-time errors.
9///
10/// # Example
11///
12/// ```rust
13/// use abi_stable::nulstr_trunc;
14///
15/// assert_eq!(nulstr_trunc!("Huh?").to_str_with_nul(), "Huh?\0");
16///
17/// assert_eq!(nulstr_trunc!("Hello!").to_str_with_nul(), "Hello!\0");
18///
19/// assert_eq!(
20/// nulstr_trunc!("Hello\0, world!").to_str_with_nul(),
21/// "Hello\0"
22/// );
23///
24/// ```
25///
26/// [`NulStr`]: ./sabi_types/struct.NulStr.html
27#[macro_export]
28macro_rules! nulstr_trunc {
29 ($str:expr $(,)*) => {{
30 const __STR_NHPMWYD3NJA: $crate::sabi_types::NulStr<'_> =
31 $crate::sabi_types::NulStr::from_str($crate::pmr::concat!($str, "\0"));
32 __STR_NHPMWYD3NJA
33 }};
34}
35
36/// Constructs a [`NulStr`] from a string literal.
37///
38/// # Error
39///
40/// This causes a compile-time error if the input string contains nul byte(s).
41///
42/// # Example
43///
44/// ```rust
45/// use abi_stable::nulstr;
46///
47/// assert_eq!( nulstr!("Huh?").to_str_with_nul(), "Huh?\0" );
48/// assert_eq!( nulstr!("Hello!").to_str_with_nul(), "Hello!\0" );
49/// ```
50///
51/// Nul bytes in the middle of the string cause compilation errors:
52/// ```compile_fail
53/// use abi_stable::nulstr;
54///
55/// assert_eq!(nulstr!("Hello\0, world!").to_str_with_nul(), "Hello\0");
56/// ```
57///
58/// [`NulStr`]: ./sabi_types/struct.NulStr.html
59#[macro_export]
60macro_rules! nulstr {
61 ($str:expr $(,)*) => {{
62 const __STR_NHPMWYD3NJA: $crate::sabi_types::NulStr<'_> =
63 $crate::sabi_types::NulStr::__try_from_str_unwrapping($crate::pmr::concat!($str, "\0"));
64
65 __STR_NHPMWYD3NJA
66 }};
67}