|
| 1 | +use std::cmp::Ordering; |
| 2 | +use std::fmt::Debug; |
| 3 | +use std::sync::atomic::AtomicUsize; |
| 4 | +use std::sync::atomic::Ordering::SeqCst; |
| 5 | + |
| 6 | +/// A blueprint for crash test dummy instances that monitor drops. |
| 7 | +/// Some instances may be configured to panic at some point. |
| 8 | +/// |
| 9 | +/// Crash test dummies are identified and ordered by an id, so they can be used |
| 10 | +/// as keys in a BTreeMap. |
| 11 | +#[derive(Debug)] |
| 12 | +pub struct CrashTestDummy { |
| 13 | + pub id: usize, |
| 14 | + dropped: AtomicUsize, |
| 15 | +} |
| 16 | + |
| 17 | +impl CrashTestDummy { |
| 18 | + /// Creates a crash test dummy design. The `id` determines order and equality of instances. |
| 19 | + pub fn new(id: usize) -> CrashTestDummy { |
| 20 | + CrashTestDummy { id, dropped: AtomicUsize::new(0) } |
| 21 | + } |
| 22 | + |
| 23 | + /// Creates an instance of a crash test dummy that records what events it experiences |
| 24 | + /// and optionally panics. |
| 25 | + pub fn spawn(&self, panic: Panic) -> Instance<'_> { |
| 26 | + Instance { origin: self, panic } |
| 27 | + } |
| 28 | + |
| 29 | + /// Returns how many times instances of the dummy have been dropped. |
| 30 | + pub fn dropped(&self) -> usize { |
| 31 | + self.dropped.load(SeqCst) |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +#[derive(Debug)] |
| 36 | +pub struct Instance<'a> { |
| 37 | + origin: &'a CrashTestDummy, |
| 38 | + panic: Panic, |
| 39 | +} |
| 40 | + |
| 41 | +#[derive(Copy, Clone, Debug, PartialEq, Eq)] |
| 42 | +pub enum Panic { |
| 43 | + Never, |
| 44 | + InDrop, |
| 45 | +} |
| 46 | + |
| 47 | +impl Instance<'_> { |
| 48 | + pub fn id(&self) -> usize { |
| 49 | + self.origin.id |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +impl Drop for Instance<'_> { |
| 54 | + fn drop(&mut self) { |
| 55 | + self.origin.dropped.fetch_add(1, SeqCst); |
| 56 | + if self.panic == Panic::InDrop { |
| 57 | + panic!("panic in `drop`"); |
| 58 | + } |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +impl PartialOrd for Instance<'_> { |
| 63 | + fn partial_cmp(&self, other: &Self) -> Option<Ordering> { |
| 64 | + self.id().partial_cmp(&other.id()) |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +impl Ord for Instance<'_> { |
| 69 | + fn cmp(&self, other: &Self) -> Ordering { |
| 70 | + self.id().cmp(&other.id()) |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +impl PartialEq for Instance<'_> { |
| 75 | + fn eq(&self, other: &Self) -> bool { |
| 76 | + self.id().eq(&other.id()) |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +impl Eq for Instance<'_> {} |
0 commit comments