Summary

c"…" string literals.

Motivation

Looking at the amount of cstr!() invocations just on GitHub (about 3.2k files with matches) it seems like C string literals are a widely used feature. Implementing cstr!() as a macro_rules or proc_macro requires non-trivial code to get it completely right (e.g. refusing embedded nul bytes), and is still less flexible than it should be (e.g. in terms of accepted escape codes).

In Rust 2021, we reserved prefixes for (string) literals, so let’s make use of that.

Guide-level explanation

c"abc" is a &CStr. A nul byte (b'\0') is appended to it in memory and the result is a &CStr.

All escape codes and characters accepted by "" and b"" literals are accepted, except nul bytes. So, both UTF-8 and non-UTF-8 data can co-exist in a C string. E.g. c"hello\x80我叫\u{1F980}".

The raw string literal variant is prefixed with cr. For example, cr"\" and cr##"Hello "world"!"##. (Just like r"" and br"".)

Reference-level explanation

Two new string literal types: c"…" and cr#"…"#.

Accepted escape codes: Quote & Unicode & Byte.

Nul bytes are disallowed, whether as escape code or source character (e.g. "\0", "\x00", "\u{0}" or "␀").

Unicode characters are accepted and encoded as UTF-8. That is, c"🦀", c"\u{1F980}" and c"\xf0\x9f\xa6\x80" are all accepted and equivalent.

The type of the expression is &core::ffi::CStr. So, the CStr type will have to become a lang item. (no_core programs that don’t use c"" string literals won’t need to define this lang item.)

Interactions with string related macros:

(This might change in the future. E.g. format_args!(c"…") would be cool, but that would require generalizing the macro and fmt::Arguments to work for other kinds of strings. (Ideally also for b"…".))

Rationale and alternatives

Drawbacks

Prior art

Unresolved questions

Future possibilities

(These aren’t necessarily all good ideas.)