From 092bf2b50067a92e03da024b0406dca1c0e05d12 Mon Sep 17 00:00:00 2001 From: Austin Bonander Date: Tue, 2 Oct 2018 03:42:01 -0700 Subject: [PATCH 1/2] make `CStr::from_bytes_with_nul_unchecked()` a const fn closes #54678 --- src/libstd/ffi/c_str.rs | 12 +++++++++++- src/libstd/lib.rs | 1 + 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 63dd12f782fda..dfec13cd2ec00 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -1040,7 +1040,8 @@ impl CStr { /// ``` #[inline] #[stable(feature = "cstr_from_bytes", since = "1.10.0")] - pub unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr { + #[rustc_const_unstable(feature = "const_cstr_unchecked")] + pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr { &*(bytes as *const [u8] as *const CStr) } @@ -1471,4 +1472,13 @@ mod tests { assert_eq!(&*rc2, cstr); assert_eq!(&*arc2, cstr); } + + #[test] + fn cstr_const_constructor() { + const CSTR: &'static CStr = unsafe { + CStr::from_bytes_with_nul_unchecked(b"Hello, world!\0") + }; + + assert_eq!(CSTR.to_str().unwrap(), "Hello, world!"); + } } diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index 7ae4f2de4c36d..f8b1760975ae4 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -253,6 +253,7 @@ #![feature(min_const_fn)] #![feature(const_int_ops)] #![feature(const_ip)] +#![feature(const_raw_ptr_deref)] #![feature(core_intrinsics)] #![feature(dropck_eyepatch)] #![feature(exact_size_is_empty)] From e0caaec6f92b7d9bf02278c6ed991cdb7139cd06 Mon Sep 17 00:00:00 2001 From: Austin Bonander Date: Tue, 2 Oct 2018 04:26:16 -0700 Subject: [PATCH 2/2] make `CStr::from_bytes_with_nul_unchecked()` a const fn closes #54678 --- src/libstd/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index f8b1760975ae4..afe0b67e33020 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -254,6 +254,7 @@ #![feature(const_int_ops)] #![feature(const_ip)] #![feature(const_raw_ptr_deref)] +#![feature(const_cstr_unchecked)] #![feature(core_intrinsics)] #![feature(dropck_eyepatch)] #![feature(exact_size_is_empty)]