Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

rust: str: add `c_str!` macro

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 <alex.gaynor@gmail.com>
Signed-off-by: Alex Gaynor <alex.gaynor@gmail.com>
Signed-off-by: Gary Guo <gary@garyguo.net>
[Reworded, adapted for upstream and applied latest changes]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>

authored by

Gary Guo and committed by
Miguel Ojeda
b18cb00e 985f1f09

+23
+23
rust/kernel/str.rs
··· 321 321 } 322 322 } 323 323 324 + /// Creates a new [`CStr`] from a string literal. 325 + /// 326 + /// The string literal should not contain any `NUL` bytes. 327 + /// 328 + /// # Examples 329 + /// 330 + /// ``` 331 + /// # use kernel::c_str; 332 + /// # use kernel::str::CStr; 333 + /// const MY_CSTR: &CStr = c_str!("My awesome CStr!"); 334 + /// ``` 335 + #[macro_export] 336 + macro_rules! c_str { 337 + ($str:expr) => {{ 338 + const S: &str = concat!($str, "\0"); 339 + const C: &$crate::str::CStr = match $crate::str::CStr::from_bytes_with_nul(S.as_bytes()) { 340 + Ok(v) => v, 341 + Err(_) => panic!("string contains interior NUL"), 342 + }; 343 + C 344 + }}; 345 + } 346 + 324 347 #[cfg(test)] 325 348 mod tests { 326 349 use super::*;