@@ -50,6 +50,34 @@ impl ByteString {
50
50
pub const unsafe fn from_bytes_unchecked ( src : Bytes ) -> ByteString {
51
51
Self ( src)
52
52
}
53
+
54
+ /// Returns a slice of self that is equivalent to the given `subset`. Corresponds to [`Bytes::slice_ref`].
55
+ ///
56
+ /// When processing a `ByteString` buffer with other tools, one often gets a
57
+ /// `&str` which is in fact a slice of the `ByteString`, i.e. a subset of it.
58
+ /// This function turns that `&str` into another `ByteString`, as if one had
59
+ /// sliced the `ByteString` with the offsets that correspond to `subset`.
60
+ ///
61
+ /// This operation is `O(1)`.
62
+ ///
63
+ /// # Examples
64
+ ///
65
+ /// ```
66
+ /// use bytestring::ByteString;
67
+ ///
68
+ /// let string = ByteString::from_static(" foo ");
69
+ /// let subset = string.trim();
70
+ /// let substring = string.slice_ref(subset);
71
+ /// assert_eq!(substring, "foo");
72
+ /// ```
73
+ ///
74
+ /// # Panics
75
+ ///
76
+ /// Requires that the given `subset` str is in fact contained within the
77
+ /// `ByteString` buffer; otherwise this function will panic.
78
+ pub fn slice_ref ( & self , subset : & str ) -> Self {
79
+ Self ( self . 0 . slice_ref ( subset. as_bytes ( ) ) )
80
+ }
53
81
}
54
82
55
83
impl PartialEq < str > for ByteString {
@@ -349,4 +377,10 @@ mod test {
349
377
let s = serde_json:: to_string ( & ByteString :: from_static ( "nice bytes" ) ) . unwrap ( ) ;
350
378
assert_eq ! ( s, r#""nice bytes""# ) ;
351
379
}
380
+
381
+ #[ test]
382
+ #[ should_panic]
383
+ fn test_slice_ref_catches_not_a_subset ( ) {
384
+ ByteString :: from_static ( "foo bar" ) . slice_ref ( "foo" ) ;
385
+ }
352
386
}
0 commit comments