]> Git Repo - linux.git/commitdiff
rust: str: add `c_str!` macro
authorGary Guo <[email protected]>
Thu, 10 Nov 2022 16:41:31 +0000 (17:41 +0100)
committerMiguel Ojeda <[email protected]>
Sun, 4 Dec 2022 00:59:15 +0000 (01:59 +0100)
Add `c_str!`, which is a convenience macro that creates a new `CStr`
from a string literal.

It is designed to be similar to a `str` in usage, and it is usable
in const contexts, for instance:

    const X: &CStr = c_str!("Example");

Co-developed-by: Alex Gaynor <[email protected]>
Signed-off-by: Alex Gaynor <[email protected]>
Signed-off-by: Gary Guo <[email protected]>
[Reworded, adapted for upstream and applied latest changes]
Signed-off-by: Miguel Ojeda <[email protected]>
rust/kernel/str.rs

index 3ed685cb5a3c3cc543afe1e2f808b44c6a51de20..a995db36486f72c3fd8807c4fd02d5c456ded8a3 100644 (file)
@@ -321,6 +321,29 @@ where
     }
 }
 
+/// Creates a new [`CStr`] from a string literal.
+///
+/// The string literal should not contain any `NUL` bytes.
+///
+/// # Examples
+///
+/// ```
+/// # use kernel::c_str;
+/// # use kernel::str::CStr;
+/// const MY_CSTR: &CStr = c_str!("My awesome CStr!");
+/// ```
+#[macro_export]
+macro_rules! c_str {
+    ($str:expr) => {{
+        const S: &str = concat!($str, "\0");
+        const C: &$crate::str::CStr = match $crate::str::CStr::from_bytes_with_nul(S.as_bytes()) {
+            Ok(v) => v,
+            Err(_) => panic!("string contains interior NUL"),
+        };
+        C
+    }};
+}
+
 #[cfg(test)]
 mod tests {
     use super::*;
This page took 0.054727 seconds and 4 git commands to generate.