Skip to content

Commit

Permalink
Rollup merge of #54745 - abonander:cstr-const, r=oli-obk
Browse files Browse the repository at this point in the history
make `CStr::from_bytes_with_nul_unchecked()` a const fn

closes #54678
  • Loading branch information
pietroalbini authored Oct 2, 2018
2 parents 1826970 + e0caaec commit 00e4b27
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/libstd/ffi/c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down Expand Up @@ -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!");
}
}
2 changes: 2 additions & 0 deletions src/libstd/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,8 @@
#![feature(min_const_fn)]
#![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)]
Expand Down

0 comments on commit 00e4b27

Please sign in to comment.