1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
//-
// Copyright 2017, 2018 The proptest developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Arbitrary implementations for `std::sync`.

use std::fmt;
use std::sync::*;
use std::sync::atomic::*;
use std::sync::mpsc::*;
use std::thread;
use std::time::Duration;

use strategy::*;
use strategy::statics::static_map;
use arbitrary::*;

// OnceState can not escape Once::call_once_force.
// PoisonError depends implicitly on the lifetime on MutexGuard, etc.
// This transitively applies to TryLockError.

wrap_from!(Arc);

// Not doing Weak because .upgrade() would always return None.

#[cfg(not(feature = "unstable"))]
wrap_ctor!(Mutex);
#[cfg(feature = "unstable")]
wrap_from!(Mutex);

#[cfg(not(feature = "unstable"))]
wrap_ctor!(RwLock);
#[cfg(feature = "unstable")]
wrap_from!(RwLock);

arbitrary!(Barrier, SMapped<u16, Self>;  // usize would be extreme!
    static_map(any::<u16>(), |n| Barrier::new(n as usize))
);

arbitrary!(BarrierWaitResult,
    TupleUnion<(W<LazyJustFn<Self>>, W<LazyJustFn<Self>>)>;
    prop_oneof![LazyJust::new(bwr_true), LazyJust::new(bwr_false)]
);

lazy_just!(
    Condvar, Default::default;
    Once, Once::new
);

arbitrary!(WaitTimeoutResult, TupleUnion<(W<Just<Self>>, W<Just<Self>>)>;
    prop_oneof![Just(wtr_true()), Just(wtr_false())]
);

fn bwr_true() -> BarrierWaitResult {
    Barrier::new(1).wait()
}

fn bwr_false() -> BarrierWaitResult {
    let barrier = Arc::new(Barrier::new(2));
    let b2 = barrier.clone();
    let jh = thread::spawn(move|| { b2.wait() });
    let bwr1 = barrier.wait();
    let bwr2 = jh.join().unwrap();
    if bwr1.is_leader() { bwr2 } else { bwr1 }
}

fn wtr_false() -> WaitTimeoutResult {
    let cvar = Arc::new(Condvar::new());
    let cvar2 = cvar.clone();
    thread::spawn(move|| { cvar2.notify_one(); });
    let lock = Mutex::new(());
    let wt = cvar.wait_timeout(lock.lock().unwrap(), Duration::from_millis(1));
    let (_, wtr) = wt.unwrap();
    wtr
}

fn wtr_true() -> WaitTimeoutResult {
    let cvar = Condvar::new();
    let lock = Mutex::new(());
    let wt = cvar.wait_timeout(lock.lock().unwrap(), Duration::from_millis(0));
    let (_, wtr) = wt.unwrap();
    wtr
}

macro_rules! atomic {
    ($($type: ident, $base: ty);+) => {
        $(arbitrary!($type, SMapped<$base, Self>;
            static_map(any::<$base>(), $type::new)
        );)+
    };
}

// impl_wrap_gen!(AtomicPtr); // We don't have impl Arbitrary for *mut T yet.
atomic!(AtomicBool, bool; AtomicIsize, isize; AtomicUsize, usize);

#[cfg(feature = "unstable")]
atomic!(AtomicI8, i8; AtomicI16, i16; AtomicI32, i32; AtomicI64, i64;
        AtomicU8, u8; AtomicU16, u16; AtomicU32, u32; AtomicU64, u64);

arbitrary!(Ordering,
    TupleUnion<(W<Just<Self>>, W<Just<Self>>, W<Just<Self>>,
                W<Just<Self>>, W<Just<Self>>)>;
    prop_oneof![
        Just(Ordering::Relaxed),
        Just(Ordering::Release),
        Just(Ordering::Acquire),
        Just(Ordering::AcqRel),
        Just(Ordering::SeqCst)
    ]
);

arbitrary!(RecvError; RecvError);

arbitrary!([T: Arbitrary] SendError<T>, SMapped<T, Self>, T::Parameters;
    args => static_map(any_with::<T>(args), SendError)
);

arbitrary!(RecvTimeoutError, TupleUnion<(W<Just<Self>>, W<Just<Self>>)>;
    prop_oneof![
        Just(RecvTimeoutError::Disconnected),
        Just(RecvTimeoutError::Timeout)
    ]
);

arbitrary!(TryRecvError, TupleUnion<(W<Just<Self>>, W<Just<Self>>)>;
    prop_oneof![
        Just(TryRecvError::Disconnected),
        Just(TryRecvError::Empty)
    ]
);

arbitrary!(
    [P: Clone + Default, T: Arbitrary<Parameters = P>] TrySendError<T>,
    TupleUnion<(W<SMapped<T, Self>>, W<SMapped<T, Self>>)>, P;
    args => prop_oneof![
        static_map(any_with::<T>(args.clone()), TrySendError::Disconnected),
        static_map(any_with::<T>(args), TrySendError::Full),
    ]
);

#[cfg(feature = "unstable")]
lazy_just!(Select, Select::new);

// If only half of a pair is generated then you will get a hang-up.
// Thus the only meaningful impls are in pairs.
arbitrary!([A] (Sender<A>, Receiver<A>), LazyJustFn<Self>;
    LazyJust::new(channel)
);

arbitrary!([A: fmt::Debug] (Sender<A>, IntoIter<A>), LazyJustFn<Self>;
    LazyJust::new(|| {
        let (rx, tx) = channel();
        (rx, tx.into_iter())
    })
);

arbitrary!([A] (SyncSender<A>, Receiver<A>), SMapped<u16, Self>;
    static_map(any::<u16>(), |size| sync_channel(size as usize))
);

arbitrary!([A: fmt::Debug] (SyncSender<A>, IntoIter<A>), SMapped<u16, Self>;
    static_map(any::<u16>(), |size| {
        let (rx, tx) = sync_channel(size as usize);
        (rx, tx.into_iter())
    })
);

#[cfg(test)]
mod test {
    no_panic_test!(
        arc => Arc<u8>,
        mutex => Mutex<u8>,
        rw_lock => RwLock<u8>,
        barrier => Barrier,
        barrier_wait_result => BarrierWaitResult,
        condvar => Condvar,
        once => Once,
        wait_timeout_result => WaitTimeoutResult,
        atomic_bool => AtomicBool,
        atomic_isize => AtomicIsize,
        atomic_usize => AtomicUsize,
        ordering => Ordering,
        recv_error => RecvError,
        send_error => SendError<u8>,
        recv_timeout_error => RecvTimeoutError,
        try_recv_error => TryRecvError,
        try_send_error => TrySendError<u8>,
        rx_tx => (Sender<u8>, Receiver<u8>),
        rx_txiter => (Sender<u8>, IntoIter<u8>),
        syncrx_tx => (SyncSender<u8>, Receiver<u8>),
        syncrx_txiter => (SyncSender<u8>, IntoIter<u8>)
    );

    #[cfg(feature = "unstable")]
    no_panic_test!(
        select => Select,
        atomic_i8  => AtomicI8,
        atomic_i16 => AtomicI16,
        atomic_i32 => AtomicI32,
        atomic_i64 => AtomicI64,
        atomic_u8  => AtomicU8,
        atomic_u16 => AtomicU16,
        atomic_u32 => AtomicU32,
        atomic_u64 => AtomicU64
    );
}