mirror of
https://gitee.com/bianbu-linux/linux-6.6
synced 2025-04-24 14:07:52 -04:00
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>
This commit is contained in:
parent
985f1f09bf
commit
b18cb00e5a
1 changed files with 23 additions and 0 deletions
|
@ -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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue