Skip to content

Commit bc1df78

Browse files
Andreas Hindborgjannau
authored andcommitted
rust: str: implement strip_prefix for BStr
Implement `strip_prefix` for `BStr` by deferring to `slice::strip_prefix` on the underlying `&[u8]`. Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Daniel Almeida <daniel.almeida@collabora.com> Tested-by: Daniel Almeida <daniel.almeida@collabora.com> Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
1 parent 7a0ce5c commit bc1df78

1 file changed

Lines changed: 16 additions & 0 deletions

File tree

rust/kernel/str.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,22 @@ impl BStr {
3131
// SAFETY: `BStr` is transparent to `[u8]`.
3232
unsafe { &*(bytes as *const [u8] as *const BStr) }
3333
}
34+
35+
/// Strip a prefix from `self`. Delegates to [`slice::strip_prefix`].
36+
///
37+
/// # Example
38+
/// ```
39+
/// use kernel::b_str;
40+
/// assert_eq!(Some(b_str!("bar")), b_str!("foobar").strip_prefix(b_str!("foo")));
41+
/// assert_eq!(None, b_str!("foobar").strip_prefix(b_str!("bar")));
42+
/// assert_eq!(Some(b_str!("foobar")), b_str!("foobar").strip_prefix(b_str!("")));
43+
/// assert_eq!(Some(b_str!("")), b_str!("foobar").strip_prefix(b_str!("foobar")));
44+
/// ```
45+
pub fn strip_prefix(&self, pattern: impl AsRef<Self>) -> Option<&BStr> {
46+
self.deref()
47+
.strip_prefix(pattern.as_ref().deref())
48+
.map(Self::from_bytes)
49+
}
3450
}
3551

3652
impl fmt::Display for BStr {

0 commit comments

Comments
 (0)