]> git.lizzy.rs Git - rust.git/blob - src/librustc_data_structures/const_cstr.rs
Disable wasm32 features on emscripten
[rust.git] / src / librustc_data_structures / const_cstr.rs
1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 /// This macro creates a zero-overhead &CStr by adding a NUL terminator to
12 /// the string literal passed into it at compile-time. Use it like:
13 ///
14 /// ```
15 ///     let some_const_cstr = const_cstr!("abc");
16 /// ```
17 ///
18 /// The above is roughly equivalent to:
19 ///
20 /// ```
21 ///     let some_const_cstr = CStr::from_bytes_with_nul(b"abc\0").unwrap()
22 /// ```
23 ///
24 /// Note that macro only checks the string literal for internal NULs if
25 /// debug-assertions are enabled in order to avoid runtime overhead in release
26 /// builds.
27 #[macro_export]
28 macro_rules! const_cstr {
29     ($s:expr) => ({
30         use std::ffi::CStr;
31
32         let str_plus_nul = concat!($s, "\0");
33
34         if cfg!(debug_assertions) {
35             CStr::from_bytes_with_nul(str_plus_nul.as_bytes()).unwrap()
36         } else {
37             unsafe {
38                 CStr::from_bytes_with_nul_unchecked(str_plus_nul.as_bytes())
39             }
40         }
41     })
42 }