]> git.proxmox.com Git - rustc.git/blame - vendor/rustc-ap-rustc_data_structures/src/const_cstr.rs
Update upstream source from tag 'upstream/1.52.1+dfsg1'
[rustc.git] / vendor / rustc-ap-rustc_data_structures / src / const_cstr.rs
CommitLineData
f20569fa
XL
1/// This macro creates a zero-overhead &CStr by adding a NUL terminator to
2/// the string literal passed into it at compile-time. Use it like:
3///
4/// ```
5/// let some_const_cstr = const_cstr!("abc");
6/// ```
7///
8/// The above is roughly equivalent to:
9///
10/// ```
11/// let some_const_cstr = CStr::from_bytes_with_nul(b"abc\0").unwrap()
12/// ```
13///
14/// Note that macro only checks the string literal for internal NULs if
15/// debug-assertions are enabled in order to avoid runtime overhead in release
16/// builds.
17#[macro_export]
18macro_rules! const_cstr {
19 ($s:expr) => {{
20 use std::ffi::CStr;
21
22 let str_plus_nul = concat!($s, "\0");
23
24 if cfg!(debug_assertions) {
25 CStr::from_bytes_with_nul(str_plus_nul.as_bytes()).unwrap()
26 } else {
27 unsafe { CStr::from_bytes_with_nul_unchecked(str_plus_nul.as_bytes()) }
28 }
29 }};
30}