Skip to content

Commit f8c92f5

Browse files
committed
Add failing leak detection test
1 parent 5142ad5 commit f8c92f5

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

crates/slice-dst/tests/leak.rs

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
use {
2+
slice_dst::*,
3+
std::sync::atomic::{AtomicUsize, Ordering::SeqCst},
4+
};
5+
6+
struct DropTracking<'a> {
7+
place: &'a AtomicUsize,
8+
}
9+
10+
impl<'a> DropTracking<'a> {
11+
fn new(place: &'a AtomicUsize) -> Self {
12+
place.fetch_add(1, SeqCst);
13+
DropTracking { place }
14+
}
15+
}
16+
17+
impl Drop for DropTracking<'_> {
18+
fn drop(&mut self) {
19+
self.place.fetch_sub(1, SeqCst);
20+
}
21+
}
22+
23+
#[test]
24+
fn bad_exactsizeiterator() {
25+
struct Iter<'a> {
26+
counter: &'a AtomicUsize,
27+
len: usize,
28+
}
29+
30+
impl ExactSizeIterator for Iter<'_> {
31+
fn len(&self) -> usize {
32+
self.len
33+
}
34+
}
35+
36+
impl<'a> Iterator for Iter<'a> {
37+
type Item = DropTracking<'a>;
38+
39+
fn next(&mut self) -> Option<Self::Item> {
40+
match self.len {
41+
0 | 1 => None,
42+
_ => {
43+
self.len -= 1;
44+
Some(DropTracking::new(self.counter))
45+
}
46+
}
47+
}
48+
}
49+
50+
let mut counter = AtomicUsize::new(0);
51+
let _ = std::panic::catch_unwind(|| {
52+
let _: Box<_> = SliceWithHeader::new::<Box<_>, _>(
53+
(),
54+
Iter {
55+
counter: &counter,
56+
len: 5,
57+
},
58+
);
59+
});
60+
assert_eq!(*counter.get_mut(), 0);
61+
}

0 commit comments

Comments
 (0)