Skip to content

Commit 5928642

Browse files
Andreas Hindborgojeda
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 <[email protected]> Reviewed-by: Alice Ryhl <[email protected]> Reviewed-by: Daniel Almeida <[email protected]> Tested-by: Daniel Almeida <[email protected]> Signed-off-by: Andreas Hindborg <[email protected]> Tested-by: Daniel Gomez <[email protected]> Link: https://lore.kernel.org/r/[email protected] [ Pluralized section name. Hid `use`. - Miguel ] Signed-off-by: Miguel Ojeda <[email protected]>
1 parent d2e3f79 commit 5928642

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

rust/kernel/str.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,23 @@ 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+
/// # Examples
38+
///
39+
/// ```
40+
/// # use kernel::b_str;
41+
/// assert_eq!(Some(b_str!("bar")), b_str!("foobar").strip_prefix(b_str!("foo")));
42+
/// assert_eq!(None, b_str!("foobar").strip_prefix(b_str!("bar")));
43+
/// assert_eq!(Some(b_str!("foobar")), b_str!("foobar").strip_prefix(b_str!("")));
44+
/// assert_eq!(Some(b_str!("")), b_str!("foobar").strip_prefix(b_str!("foobar")));
45+
/// ```
46+
pub fn strip_prefix(&self, pattern: impl AsRef<Self>) -> Option<&BStr> {
47+
self.deref()
48+
.strip_prefix(pattern.as_ref().deref())
49+
.map(Self::from_bytes)
50+
}
3451
}
3552

3653
impl fmt::Display for BStr {

0 commit comments

Comments
 (0)