Skip to content

Commit 650ec51

Browse files
nbdd0121ojeda
authored andcommitted
rust: str: add b_str! macro
Add the `b_str!` macro, which creates a new `BStr` from a string literal. It is usable in const contexts, for instance: const X: &BStr = b_str!("Example"); Signed-off-by: Gary Guo <gary@garyguo.net> [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
1 parent 7c59774 commit 650ec51

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

rust/kernel/str.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,27 @@ use core::fmt;
99
/// `BStr` is simply an alias to `[u8]`, but has a more evident semantical meaning.
1010
pub type BStr = [u8];
1111

12+
/// Creates a new [`BStr`] from a string literal.
13+
///
14+
/// `b_str!` converts the supplied string literal to byte string, so non-ASCII
15+
/// characters can be included.
16+
///
17+
/// # Examples
18+
///
19+
/// ```
20+
/// # use kernel::b_str;
21+
/// # use kernel::str::BStr;
22+
/// const MY_BSTR: &BStr = b_str!("My awesome BStr!");
23+
/// ```
24+
#[macro_export]
25+
macro_rules! b_str {
26+
($str:literal) => {{
27+
const S: &'static str = $str;
28+
const C: &'static $crate::str::BStr = S.as_bytes();
29+
C
30+
}};
31+
}
32+
1233
/// Allows formatting of [`fmt::Arguments`] into a raw buffer.
1334
///
1435
/// It does not fail if callers write past the end of the buffer so that they can calculate the

0 commit comments

Comments
 (0)