1 // We avoid relying on anything else in the crate, apart from the `Debug` trait.
3 use std
::cmp
::Ordering
;
4 use std
::sync
::atomic
::{AtomicUsize, Ordering::SeqCst}
;
6 /// A blueprint for crash test dummy instances that monitor particular events.
7 /// Some instances may be configured to panic at some point.
8 /// Events are `clone`, `drop` or some anonymous `query`.
10 /// Crash test dummies are identified and ordered by an id, so they can be used
11 /// as keys in a BTreeMap.
13 pub struct CrashTestDummy
{
21 /// Creates a crash test dummy design. The `id` determines order and equality of instances.
22 pub fn new(id
: usize) -> CrashTestDummy
{
25 cloned
: AtomicUsize
::new(0),
26 dropped
: AtomicUsize
::new(0),
27 queried
: AtomicUsize
::new(0),
31 /// Creates an instance of a crash test dummy that records what events it experiences
32 /// and optionally panics.
33 pub fn spawn(&self, panic
: Panic
) -> Instance
<'_
> {
34 Instance { origin: self, panic }
37 /// Returns how many times instances of the dummy have been cloned.
38 pub fn cloned(&self) -> usize {
39 self.cloned
.load(SeqCst
)
42 /// Returns how many times instances of the dummy have been dropped.
43 pub fn dropped(&self) -> usize {
44 self.dropped
.load(SeqCst
)
47 /// Returns how many times instances of the dummy have had their `query` member invoked.
48 pub fn queried(&self) -> usize {
49 self.queried
.load(SeqCst
)
54 pub struct Instance
<'a
> {
55 origin
: &'a CrashTestDummy
,
59 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
68 pub fn id(&self) -> usize {
72 /// Some anonymous query, the result of which is already given.
73 pub fn query
<R
>(&self, result
: R
) -> R
{
74 self.origin
.queried
.fetch_add(1, SeqCst
);
75 if self.panic
== Panic
::InQuery
{
76 panic
!("panic in `query`");
82 impl Clone
for Instance
<'_
> {
83 fn clone(&self) -> Self {
84 self.origin
.cloned
.fetch_add(1, SeqCst
);
85 if self.panic
== Panic
::InClone
{
86 panic
!("panic in `clone`");
88 Self { origin: self.origin, panic: Panic::Never }
92 impl Drop
for Instance
<'_
> {
94 self.origin
.dropped
.fetch_add(1, SeqCst
);
95 if self.panic
== Panic
::InDrop
{
96 panic
!("panic in `drop`");
101 impl PartialOrd
for Instance
<'_
> {
102 fn partial_cmp(&self, other
: &Self) -> Option
<Ordering
> {
103 self.id().partial_cmp(&other
.id())
107 impl Ord
for Instance
<'_
> {
108 fn cmp(&self, other
: &Self) -> Ordering
{
109 self.id().cmp(&other
.id())
113 impl PartialEq
for Instance
<'_
> {
114 fn eq(&self, other
: &Self) -> bool
{
115 self.id().eq(&other
.id())
119 impl Eq
for Instance
<'_
> {}