diff --git a/src/bytes.rs b/src/bytes.rs index 4fc1a49..789fded 100644 --- a/src/bytes.rs +++ b/src/bytes.rs @@ -549,6 +549,8 @@ impl Bytes { /// /// Panics if `at > len` pub fn split_off(&mut self, at: usize) -> Bytes { + assert!(at <= self.len()); + if at == self.len() { return Bytes::new(); } @@ -588,6 +590,8 @@ impl Bytes { /// /// Panics if `at > len` pub fn split_to(&mut self, at: usize) -> Bytes { + assert!(at <= self.len()); + if at == self.len() { return mem::replace(self, Bytes::new()); } diff --git a/tests/test_bytes.rs b/tests/test_bytes.rs index ae50d86..e1938ed 100644 --- a/tests/test_bytes.rs +++ b/tests/test_bytes.rs @@ -238,6 +238,28 @@ fn split_to_uninitialized() { assert_eq!(other.capacity(), 128); } +#[test] +fn split_off_to_at_gt_len() { + fn make_bytes() -> Bytes { + let mut bytes = BytesMut::with_capacity(100); + bytes.put_slice(&[10, 20, 30, 40]); + bytes.freeze() + } + + use std::panic; + + make_bytes().split_to(4); + make_bytes().split_off(4); + + assert!(panic::catch_unwind(move || { + make_bytes().split_to(5); + }).is_err()); + + assert!(panic::catch_unwind(move || { + make_bytes().split_off(5); + }).is_err()); +} + #[test] fn fns_defined_for_bytes_mut() { let mut bytes = BytesMut::from(&b"hello world"[..]);