]> git.ipfire.org Git - thirdparty/kernel/linux.git/commitdiff
rust: str: update `c_str!` documentation
authorTamir Duberstein <tamird@kernel.org>
Mon, 9 Mar 2026 17:01:57 +0000 (13:01 -0400)
committerMiguel Ojeda <ojeda@kernel.org>
Sun, 15 Mar 2026 19:28:45 +0000 (20:28 +0100)
Now that all literals are C-Strings, update the documentation to explain
that use of this macro should be limited to non-literal strings.

Link: https://github.com/Rust-for-Linux/linux/issues/1075
Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Tamir Duberstein <tamird@kernel.org>
Reviewed-by: Gary Guo <gary@garyguo.net>
Link: https://patch.msgid.link/20260309-cstr-rename-macro-v2-1-25f7de75944e@kernel.org
[ Apply sentence case to comment. Reword title. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
rust/kernel/str.rs

index 97bf9427af59b7559ddca565d80afa32e3d3f422..9f547ba068bb4e183a5d7dc8643ee0fb21d2c422 100644 (file)
@@ -379,19 +379,32 @@ impl AsRef<BStr> for CStr {
     }
 }
 
-/// Creates a new [`CStr`] from a string literal.
+/// Creates a new [`CStr`] at compile time.
 ///
-/// The string literal should not contain any `NUL` bytes.
+/// Rust supports C string literals since Rust 1.77, and they should be used instead of this macro
+/// where possible. This macro exists to allow static *non-literal* C strings to be created at
+/// compile time. This is most often used in other macros.
+///
+/// # Panics
+///
+/// This macro panics if the operand contains an interior `NUL` byte.
 ///
 /// # Examples
 ///
 /// ```
 /// # use kernel::c_str;
 /// # use kernel::str::CStr;
-/// const MY_CSTR: &CStr = c_str!("My awesome CStr!");
+/// // This is allowed, but `c"literal"` should be preferred for literals.
+/// const BAD: &CStr = c_str!("literal");
+///
+/// // `c_str!` is still needed for static non-literal C strings.
+/// const GOOD: &CStr = c_str!(concat!(file!(), ":", line!(), ": My CStr!"));
 /// ```
 #[macro_export]
 macro_rules! c_str {
+    // NB: We could write `($str:lit) => compile_error!("use a C string literal instead");` here but
+    // that would trigger when the literal is at the top of several macro expansions. That would be
+    // too limiting to macro authors.
     ($str:expr) => {{
         const S: &str = concat!($str, "\0");
         const C: &$crate::str::CStr = match $crate::str::CStr::from_bytes_with_nul(S.as_bytes()) {