Skip to content

Commit ddcb7ce

Browse files
committed
testing drop on owner as_ref panic
1 parent d1aed1d commit ddcb7ce

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

tests/test_bytes.rs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use bytes::{Buf, BufMut, Bytes, BytesMut};
44
use std::sync::atomic::{AtomicUsize, Ordering};
55
use std::sync::Arc;
66

7+
use std::panic::{self, AssertUnwindSafe};
78
use std::usize;
89

910
const LONG: &[u8] = b"mary had a little lamb, little lamb, little lamb";
@@ -1486,16 +1487,24 @@ fn split_to_empty_addr_mut() {
14861487
struct OwnedTester<const L: usize> {
14871488
buf: [u8; L],
14881489
drop_count: Arc<AtomicUsize>,
1490+
pub panic_as_ref: bool,
14891491
}
14901492

14911493
impl<const L: usize> OwnedTester<L> {
14921494
fn new(buf: [u8; L], drop_count: Arc<AtomicUsize>) -> Self {
1493-
Self { buf, drop_count }
1495+
Self {
1496+
buf,
1497+
drop_count,
1498+
panic_as_ref: false,
1499+
}
14941500
}
14951501
}
14961502

14971503
impl<const L: usize> AsRef<[u8]> for OwnedTester<L> {
14981504
fn as_ref(&self) -> &[u8] {
1505+
if self.panic_as_ref {
1506+
panic!("test-triggered panic in `AsRef<[u8]> for OwnedTester`");
1507+
}
14991508
self.buf.as_slice()
15001509
}
15011510
}
@@ -1570,3 +1579,18 @@ fn owned_to_vec() {
15701579
drop(b1);
15711580
assert_eq!(drop_counter.load(Ordering::Acquire), 1);
15721581
}
1582+
1583+
#[test]
1584+
fn owned_safe_drop_on_as_ref_panic() {
1585+
let buf: [u8; 10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1586+
let drop_counter = Arc::new(AtomicUsize::new(0));
1587+
let mut owner = OwnedTester::new(buf, drop_counter.clone());
1588+
owner.panic_as_ref = true;
1589+
1590+
let result = panic::catch_unwind(AssertUnwindSafe(|| {
1591+
let _ = Bytes::from_owner(owner);
1592+
}));
1593+
1594+
assert!(result.is_err());
1595+
assert_eq!(drop_counter.load(Ordering::Acquire), 1);
1596+
}

0 commit comments

Comments
 (0)