From d9d5c59ef81038d7b50f61c4250a132c2f5dc91c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20F=C3=A4rber?= <01mf02@gmail.com> Date: Tue, 20 May 2025 14:52:05 +0200 Subject: [PATCH] Guarantee address in `slice()` for empty slices. (#780) --- src/bytes.rs | 2 +- tests/test_bytes.rs | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/bytes.rs b/src/bytes.rs index e2c187c..5c2ca18 100644 --- a/src/bytes.rs +++ b/src/bytes.rs @@ -401,7 +401,7 @@ impl Bytes { ); if end == begin { - return Bytes::new(); + return Bytes::new_empty_with_ptr(self.ptr.wrapping_add(begin)); } let mut ret = self.clone(); diff --git a/tests/test_bytes.rs b/tests/test_bytes.rs index f36abaa..e147783 100644 --- a/tests/test_bytes.rs +++ b/tests/test_bytes.rs @@ -1421,6 +1421,26 @@ fn try_reclaim_arc() { assert_eq!(true, buf.try_reclaim(6)); } +#[test] +fn slice_empty_addr() { + let buf = Bytes::from(vec![0; 1024]); + + let ptr_start = buf.as_ptr(); + let ptr_end = ptr_start.wrapping_add(1024); + + let empty_end = buf.slice(1024..); + assert_eq!(empty_end.len(), 0); + assert_eq!(empty_end.as_ptr(), ptr_end); + + let empty_start = buf.slice(..0); + assert_eq!(empty_start.len(), 0); + assert_eq!(empty_start.as_ptr(), ptr_start); + + // Is miri happy about the provenance? + let _ = &empty_end[..]; + let _ = &empty_start[..]; +} + #[test] fn split_off_empty_addr() { let mut buf = Bytes::from(vec![0; 1024]);