Do not panic on Bytes::slice_ref on empty slice (#355)

Use case:

```
let bytes: Bytes = ...
let subbytes = bytes.slice(a..b); // where a == b
let slice = &subbytes[..];
let slice_bytes = bytes.slice_ref(slice);
```

Last line should not panic, because `slice` object is derived from
the original `Bytes` object.

Before this commit it panics, because `Bytes::slice` returns a fresh
`Bytes` object when `begin == end`.
This commit is contained in:
Stepan Koltsov
2020-01-23 10:29:42 -08:00
committed by Sean McArthur
parent 87b75cce16
commit f330ef6c4d
2 changed files with 20 additions and 15 deletions
+6
View File
@@ -270,6 +270,12 @@ impl Bytes {
/// Requires that the given `sub` slice is in fact contained within the
/// `Bytes` buffer; otherwise this function will panic.
pub fn slice_ref(&self, subset: &[u8]) -> Bytes {
// Empty slice and empty Bytes may have their pointers reset
// so explicitly allow empty slice to be a subslice of any slice.
if subset.is_empty() {
return Bytes::new();
}
let bytes_p = self.as_ptr() as usize;
let bytes_len = self.len();