[PATCH v4 2/6] rust: str: provide const fn as_bytes() for BStr

From: Danilo Krummrich
Date: Wed Feb 26 2025 - 12:57:01 EST


`BStr` already dereference to `&[u8]` through the `Deref` trait,
however, this can't be called from const context.

Hence, provide a separate const function for this.

This is used in subsequent nova-core patches.

Signed-off-by: Danilo Krummrich <dakr@xxxxxxxxxx>
---
rust/kernel/str.rs | 6 ++++++
1 file changed, 6 insertions(+)

diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs
index 28e2201604d6..71e8a819016d 100644
--- a/rust/kernel/str.rs
+++ b/rust/kernel/str.rs
@@ -31,6 +31,12 @@ pub const fn from_bytes(bytes: &[u8]) -> &Self {
// SAFETY: `BStr` is transparent to `[u8]`.
unsafe { &*(bytes as *const [u8] as *const BStr) }
}
+
+ /// Same as `self.deref()`, but works in const context.
+ #[inline]
+ pub const fn as_bytes(&self) -> &[u8] {
+ &self.0
+ }
}

impl fmt::Display for BStr {
--
2.48.1