Skip to content

Commit 1353b8f

Browse files
tamirdojeda
authored andcommitted
rust: str: update c_str! documentation
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: #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>
1 parent b3d161f commit 1353b8f

1 file changed

Lines changed: 16 additions & 3 deletions

File tree

rust/kernel/str.rs

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -379,19 +379,32 @@ impl AsRef<BStr> for CStr {
379379
}
380380
}
381381

382-
/// Creates a new [`CStr`] from a string literal.
382+
/// Creates a new [`CStr`] at compile time.
383383
///
384-
/// The string literal should not contain any `NUL` bytes.
384+
/// Rust supports C string literals since Rust 1.77, and they should be used instead of this macro
385+
/// where possible. This macro exists to allow static *non-literal* C strings to be created at
386+
/// compile time. This is most often used in other macros.
387+
///
388+
/// # Panics
389+
///
390+
/// This macro panics if the operand contains an interior `NUL` byte.
385391
///
386392
/// # Examples
387393
///
388394
/// ```
389395
/// # use kernel::c_str;
390396
/// # use kernel::str::CStr;
391-
/// const MY_CSTR: &CStr = c_str!("My awesome CStr!");
397+
/// // This is allowed, but `c"literal"` should be preferred for literals.
398+
/// const BAD: &CStr = c_str!("literal");
399+
///
400+
/// // `c_str!` is still needed for static non-literal C strings.
401+
/// const GOOD: &CStr = c_str!(concat!(file!(), ":", line!(), ": My CStr!"));
392402
/// ```
393403
#[macro_export]
394404
macro_rules! c_str {
405+
// NB: We could write `($str:lit) => compile_error!("use a C string literal instead");` here but
406+
// that would trigger when the literal is at the top of several macro expansions. That would be
407+
// too limiting to macro authors.
395408
($str:expr) => {{
396409
const S: &str = concat!($str, "\0");
397410
const C: &$crate::str::CStr = match $crate::str::CStr::from_bytes_with_nul(S.as_bytes()) {

0 commit comments

Comments
 (0)