about summary refs log tree commit diff
path: root/src/librustc_data_structures
diff options
context:
space:
mode:
authorMichael Woerister <michaelwoerister@posteo>2018-08-07 16:03:57 +0200
committerMichael Woerister <michaelwoerister@posteo>2018-08-10 10:22:44 +0200
commit9585c5dc1fa3cef34ebdc5a5d39af88db60c6f15 (patch)
treee8c9e6ad76c04c6efd5ad85fbe6946f528cf5e54 /src/librustc_data_structures
parentf6d43ed84207c7e58f363f46e5a438ff40f2b311 (diff)
Introduce const_cstr!() macro and use it where applicable.
Diffstat (limited to 'src/librustc_data_structures')
-rw-r--r--src/librustc_data_structures/const_cstr.rs42
-rw-r--r--src/librustc_data_structures/lib.rs1
2 files changed, 43 insertions, 0 deletions
diff --git a/src/librustc_data_structures/const_cstr.rs b/src/librustc_data_structures/const_cstr.rs
new file mode 100644
index 00000000000..4589d973b6a
--- /dev/null
+++ b/src/librustc_data_structures/const_cstr.rs
@@ -0,0 +1,42 @@
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+/// This macro creates a zero-overhead &CStr by adding a NUL terminator to
+/// the string literal passed into it at compile-time. Use it like:
+///
+/// ```
+///     let some_const_cstr = const_cstr!("abc");
+/// ```
+///
+/// The above is roughly equivalent to:
+///
+/// ```
+///     let some_const_cstr = CStr::from_bytes_with_nul(b"abc\0").unwrap()
+/// ```
+///
+/// Note that macro only checks the string literal for internal NULs if
+/// debug-assertions are enabled in order to avoid runtime overhead in release
+/// builds.
+#[macro_export]
+macro_rules! const_cstr {
+    ($s:expr) => ({
+        use std::ffi::CStr;
+
+        let str_plus_nul = concat!($s, "\0");
+
+        if cfg!(debug_assertions) {
+            CStr::from_bytes_with_nul(str_plus_nul.as_bytes()).unwrap()
+        } else {
+            unsafe {
+                CStr::from_bytes_with_nul_unchecked(str_plus_nul.as_bytes())
+            }
+        }
+    })
+}
diff --git a/src/librustc_data_structures/lib.rs b/src/librustc_data_structures/lib.rs
index 3aa15f472a2..bd11a2977ff 100644
--- a/src/librustc_data_structures/lib.rs
+++ b/src/librustc_data_structures/lib.rs
@@ -60,6 +60,7 @@ pub mod array_vec;
 pub mod base_n;
 pub mod bitslice;
 pub mod bitvec;
+pub mod const_cstr;
 pub mod flock;
 pub mod fx;
 pub mod graph;