Closed
Description
Why?
Currently, creating a CStr
, even from a bytestring literal, is quite noisy.
// NOTE: Don't forget to add \0 at the end or this is unsound!
let cstr = unsafe { CStr::from_bytes_with_nul_unchecked(b"Hello, World\0") };
Furthermore, there's no way to ensure the well formed-ness of that literal at compile time¹, despite hardcoded C-strings being fairly common when creating bindings for C libraries.
How?
To address this, I would like to propose a new string literal type:
let cstr = c"Hello, World!";
It would function nearly identical to byte-string literals, with the following key differences:
- Its type is
&CStr
, not&[u8]
- It may not contain any nul bytes (
\0
,\x00
as well as a 'physical' nul byte are forbidden) - The compiler automatically adds a nul byte at the end of the string.
See also "Alternatives?" below.
Pros?
- Fills a niche in the language people are forced to build around²
- Allows creation of
const
CStr
items (currently not possible on stable)
Cons?
- Have to commit to adding a new literal (sub)type to the language, which may require small tweaks to the parser
Alternatives?
- Make associated functions on
CStr
const. This would still leave the burden of checking on the user. - Add a
cstr!
macro taking a byte-string literal and applying the needed checks and transformations.
¹ It is possible using proc-macros, though this poses different issues regarding ergonomics and stability.
² GitHub code search for CStr::from_bytes_with_nul_unchecked