Skip to content

Commit 6077dff

Browse files
abonanderischeinkman
authored andcommitted
make CStr::from_bytes_with_nul_unchecked() a const fn
closes rust-lang#54678
1 parent 81355af commit 6077dff

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

src/libstd/ffi/c_str.rs

+11-1
Original file line numberDiff line numberDiff line change
@@ -1090,7 +1090,8 @@ impl CStr {
10901090
/// ```
10911091
#[inline]
10921092
#[stable(feature = "cstr_from_bytes", since = "1.10.0")]
1093-
pub unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
1093+
#[rustc_const_unstable(feature = "const_cstr_unchecked")]
1094+
pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
10941095
&*(bytes as *const [u8] as *const CStr)
10951096
}
10961097

@@ -1521,4 +1522,13 @@ mod tests {
15211522
assert_eq!(&*rc2, cstr);
15221523
assert_eq!(&*arc2, cstr);
15231524
}
1525+
1526+
#[test]
1527+
fn cstr_const_constructor() {
1528+
const CSTR: &'static CStr = unsafe {
1529+
CStr::from_bytes_with_nul_unchecked(b"Hello, world!\0")
1530+
};
1531+
1532+
assert_eq!(CSTR.to_str().unwrap(), "Hello, world!");
1533+
}
15241534
}

src/libstd/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,7 @@
253253
#![feature(min_const_fn)]
254254
#![feature(const_int_ops)]
255255
#![feature(const_ip)]
256+
#![feature(const_raw_ptr_deref)]
256257
#![feature(core_intrinsics)]
257258
#![feature(dropck_eyepatch)]
258259
#![feature(duration_as_u128)]

0 commit comments

Comments
 (0)