From: Andreas Hindborg Date: Thu, 27 Feb 2025 14:38:10 +0000 (+0100) Subject: rust: str: implement `strip_prefix` for `BStr` X-Git-Tag: v6.15-rc1~93^2~7 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=5928642b11cb6aee8f6250c762857e713e7112da;p=thirdparty%2Fkernel%2Fstable.git 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 Reviewed-by: Alice Ryhl Reviewed-by: Daniel Almeida Tested-by: Daniel Almeida Signed-off-by: Andreas Hindborg Tested-by: Daniel Gomez Link: https://lore.kernel.org/r/20250227-module-params-v3-v8-4-ceeee85d9347@kernel.org [ Pluralized section name. Hid `use`. - Miguel ] Signed-off-by: Miguel Ojeda --- diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index c6bd2c69543dc..878111cb77bc8 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -31,6 +31,23 @@ impl BStr { // SAFETY: `BStr` is transparent to `[u8]`. unsafe { &*(bytes as *const [u8] as *const BStr) } } + + /// Strip a prefix from `self`. Delegates to [`slice::strip_prefix`]. + /// + /// # Examples + /// + /// ``` + /// # use kernel::b_str; + /// assert_eq!(Some(b_str!("bar")), b_str!("foobar").strip_prefix(b_str!("foo"))); + /// assert_eq!(None, b_str!("foobar").strip_prefix(b_str!("bar"))); + /// assert_eq!(Some(b_str!("foobar")), b_str!("foobar").strip_prefix(b_str!(""))); + /// assert_eq!(Some(b_str!("")), b_str!("foobar").strip_prefix(b_str!("foobar"))); + /// ``` + pub fn strip_prefix(&self, pattern: impl AsRef) -> Option<&BStr> { + self.deref() + .strip_prefix(pattern.as_ref().deref()) + .map(Self::from_bytes) + } } impl fmt::Display for BStr {