Skip to content

Commit 363984a

Browse files
authored
Add ByteString::slice_ref (#470)
1 parent 00654aa commit 363984a

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

bytestring/CHANGES.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22

33
## Unreleased - 2022-xx-xx
44
- Minimum supported Rust version (MSRV) is now 1.57.
5+
- Add `ByteString::slice_ref` which can safely slice a `ByteString` into a new one with zero copy. [#470]
56

7+
[#470]: https://github.com/actix/actix-net/pull/470
68

79
## 1.1.0 - 2022-06-11
810
- Implement `From<Box<str>>` for `ByteString`. [#458]

bytestring/src/lib.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,34 @@ impl ByteString {
5050
pub const unsafe fn from_bytes_unchecked(src: Bytes) -> ByteString {
5151
Self(src)
5252
}
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+
}
5381
}
5482

5583
impl PartialEq<str> for ByteString {
@@ -349,4 +377,10 @@ mod test {
349377
let s = serde_json::to_string(&ByteString::from_static("nice bytes")).unwrap();
350378
assert_eq!(s, r#""nice bytes""#);
351379
}
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+
}
352386
}

0 commit comments

Comments
 (0)