Closed as not planned
Description
Proposal
Problem statement
Now that core::ffi::CStr
is stabilized, there should be an ergonomic way to create &CStr
constants.
Motivation, use-cases
On stable there is currently no good way to create a &'static CStr
, the simplest solution needs unsafe
, i.e.
const MY_C_STRING: &CStr = unsafe { CStr::from_bytes_with_nul_unchecked(b"Hello, world!\0") };
On nightly, it is possible since rust-lang/rust#100291 without unsafe
, but these are even more verbose or don't provide meaningful error messages:
#![feature(const_cstr_methods)]
const MY_C_STRING: &CStr = if let Ok(s) = CStr::from_bytes_with_nul(b"Hello, world!\0") {
s
} else {
panic!("contains interior nul bytes")
};
#![feature(const_cstr_methods)]
#![feature(const_option)]
const MY_C_STRING: &CStr = CStr::from_bytes_with_nul(b"Hello, world!\0").ok().unwrap();
Solution sketches
With a cstr!
, the example above becomes both easier to write and easier to read, i.e.
const MY_C_STRING: &CStr = cstr!("Hello, world!");
Links and related work
- The
cstr_core
crate contains such a macro: https://docs.rs/cstr_core/0.2.6/cstr_core/macro.cstr.html - The
cstr
crate provides such a macro: https://docs.rs/cstr/0.2.10/cstr/index.html - Pull request adding this as
core::ffi::cstr
is here: Addcstr!
macro. rust#101607
What happens now?
This issue is part of the libs-api team API change proposal process. Once this issue is filed the libs-api team will review open proposals in its weekly meeting. You should receive feedback within a week or two.