Skip to content

Commit d9d5c59

Browse files
authored
Guarantee address in slice() for empty slices. (#780)
1 parent 5c90b11 commit d9d5c59

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

src/bytes.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -401,7 +401,7 @@ impl Bytes {
401401
);
402402

403403
if end == begin {
404-
return Bytes::new();
404+
return Bytes::new_empty_with_ptr(self.ptr.wrapping_add(begin));
405405
}
406406

407407
let mut ret = self.clone();

tests/test_bytes.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1421,6 +1421,26 @@ fn try_reclaim_arc() {
14211421
assert_eq!(true, buf.try_reclaim(6));
14221422
}
14231423

1424+
#[test]
1425+
fn slice_empty_addr() {
1426+
let buf = Bytes::from(vec![0; 1024]);
1427+
1428+
let ptr_start = buf.as_ptr();
1429+
let ptr_end = ptr_start.wrapping_add(1024);
1430+
1431+
let empty_end = buf.slice(1024..);
1432+
assert_eq!(empty_end.len(), 0);
1433+
assert_eq!(empty_end.as_ptr(), ptr_end);
1434+
1435+
let empty_start = buf.slice(..0);
1436+
assert_eq!(empty_start.len(), 0);
1437+
assert_eq!(empty_start.as_ptr(), ptr_start);
1438+
1439+
// Is miri happy about the provenance?
1440+
let _ = &empty_end[..];
1441+
let _ = &empty_start[..];
1442+
}
1443+
14241444
#[test]
14251445
fn split_off_empty_addr() {
14261446
let mut buf = Bytes::from(vec![0; 1024]);

0 commit comments

Comments
 (0)