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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
use std::fmt::Debug;
use crate::lockable::{Lockable, OwnedLockable, RawLock, Sharable};
use crate::{Keyable, ThreadKey};
use super::utils::{
get_locks, ordered_contains_duplicates, scoped_read, scoped_try_read, scoped_try_write,
scoped_write,
};
use super::{utils, LockGuard, RefLockCollection};
impl<'a, L> IntoIterator for &'a RefLockCollection<'a, L>
where
&'a L: IntoIterator,
{
type Item = <&'a L as IntoIterator>::Item;
type IntoIter = <&'a L as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.child.into_iter()
}
}
unsafe impl<L: Lockable> RawLock for RefLockCollection<'_, L> {
#[mutants::skip] // this should never run
#[cfg(not(tarpaulin_include))]
fn poison(&self) {
for lock in &self.locks {
lock.poison();
}
}
unsafe fn raw_write(&self) {
utils::ordered_write(&self.locks)
}
unsafe fn raw_try_write(&self) -> bool {
utils::ordered_try_write(&self.locks)
}
unsafe fn raw_unlock_write(&self) {
for lock in &self.locks {
lock.raw_unlock_write();
}
}
unsafe fn raw_read(&self) {
utils::ordered_read(&self.locks)
}
unsafe fn raw_try_read(&self) -> bool {
utils::ordered_try_read(&self.locks)
}
unsafe fn raw_unlock_read(&self) {
for lock in &self.locks {
lock.raw_unlock_read();
}
}
}
unsafe impl<L: Lockable> Lockable for RefLockCollection<'_, L> {
type Guard<'g>
= L::Guard<'g>
where
Self: 'g;
type DataMut<'a>
= L::DataMut<'a>
where
Self: 'a;
fn get_ptrs<'a>(&'a self, ptrs: &mut Vec<&'a dyn RawLock>) {
// Just like with BoxedLockCollection, we need to return all the individual
// locks to avoid duplicates
ptrs.extend_from_slice(&self.locks);
}
unsafe fn guard(&self) -> Self::Guard<'_> {
self.child.guard()
}
unsafe fn data_mut(&self) -> Self::DataMut<'_> {
self.child.data_mut()
}
}
unsafe impl<L: Sharable> Sharable for RefLockCollection<'_, L> {
type ReadGuard<'g>
= L::ReadGuard<'g>
where
Self: 'g;
type DataRef<'a>
= L::DataRef<'a>
where
Self: 'a;
unsafe fn read_guard(&self) -> Self::ReadGuard<'_> {
self.child.read_guard()
}
unsafe fn data_ref(&self) -> Self::DataRef<'_> {
self.child.data_ref()
}
}
impl<T: ?Sized, L: AsRef<T>> AsRef<T> for RefLockCollection<'_, L> {
fn as_ref(&self) -> &T {
self.child.as_ref()
}
}
#[mutants::skip]
#[cfg(not(tarpaulin_include))]
impl<L: Debug> Debug for RefLockCollection<'_, L> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct(stringify!(RefLockCollection))
.field("data", self.child)
// there's not much reason to show the sorting order
.finish_non_exhaustive()
}
}
// safety: the RawLocks must be send because they come from the Send Lockable
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl<L: Send> Send for RefLockCollection<'_, L> {}
unsafe impl<L: Sync> Sync for RefLockCollection<'_, L> {}
impl<'a, L: OwnedLockable + Default> From<&'a L> for RefLockCollection<'a, L> {
fn from(value: &'a L) -> Self {
Self::new(value)
}
}
impl<'a, L: OwnedLockable> RefLockCollection<'a, L> {
/// Creates a new collection of owned locks.
///
/// Because the locks are owned, there's no need to do any checks for
/// duplicate values.
///
/// # Examples
///
/// ```
/// use happylock::Mutex;
/// use happylock::collection::RefLockCollection;
///
/// let data = (Mutex::new(0), Mutex::new(""));
/// let lock = RefLockCollection::new(&data);
/// ```
#[must_use]
pub fn new(data: &'a L) -> Self {
RefLockCollection {
locks: get_locks(data),
child: data,
}
}
}
impl<L> RefLockCollection<'_, L> {
/// Gets an immutable reference to the underlying data
///
/// # Examples
///
/// ```
/// use happylock::{Mutex, ThreadKey};
/// use happylock::collection::RefLockCollection;
///
/// let data1 = Mutex::new(42);
/// let data2 = Mutex::new("");
///
/// // data1 and data2 refer to distinct mutexes, so this won't panic
/// let data = (&data1, &data2);
/// let lock = RefLockCollection::try_new(&data).unwrap();
///
/// let key = ThreadKey::get().unwrap();
/// let guard = lock.child().0.lock(key);
/// assert_eq!(*guard, 42);
/// ```
#[must_use]
pub const fn child(&self) -> &L {
self.child
}
}
impl<'a, L: Lockable> RefLockCollection<'a, L> {
/// Creates a new collections of locks.
///
/// # Safety
///
/// This results in undefined behavior if any locks are presented twice
/// within this collection.
///
/// # Examples
///
/// ```
/// use happylock::Mutex;
/// use happylock::collection::RefLockCollection;
///
/// let data1 = Mutex::new(0);
/// let data2 = Mutex::new("");
///
/// // safety: data1 and data2 refer to distinct mutexes
/// let data = (&data1, &data2);
/// let lock = unsafe { RefLockCollection::new_unchecked(&data) };
/// ```
#[must_use]
pub unsafe fn new_unchecked(data: &'a L) -> Self {
Self {
child: data,
locks: get_locks(data),
}
}
/// Creates a new collection of locks.
///
/// This returns `None` if any locks are found twice in the given
/// collection.
///
/// # Examples
///
/// ```
/// use happylock::Mutex;
/// use happylock::collection::RefLockCollection;
///
/// let data1 = Mutex::new(0);
/// let data2 = Mutex::new("");
///
/// // data1 and data2 refer to distinct mutexes, so this won't panic
/// let data = (&data1, &data2);
/// let lock = RefLockCollection::try_new(&data).unwrap();
/// ```
#[must_use]
pub fn try_new(data: &'a L) -> Option<Self> {
let locks = get_locks(data);
if ordered_contains_duplicates(&locks) {
return None;
}
Some(Self { child: data, locks })
}
/// Acquires an exclusive lock, blocking until it is safe to do so, and then
/// unlocks after the provided function returns.
///
/// This function is useful to ensure that the data is never accidentally
/// locked forever by leaking the guard. Even if the function panics, this
/// function will gracefully notice the panic, and unlock. This function
/// provides no guarantees with respect to the ordering of whether contentious
/// readers or writers will acquire the lock first.
///
/// # Panics
///
/// This function will panic if the provided function also panics. However,
/// the collection will be safely unlocked in this case, allowing the
/// collection to be locked again later.
///
/// # Example
///
/// ```
/// use happylock::{ThreadKey, Mutex};
/// use happylock::collection::RefLockCollection;
///
/// let mut key = ThreadKey::get().unwrap();
/// let data = (Mutex::new(0), Mutex::new(""));
/// let lock = RefLockCollection::new(&data);
///
/// lock.scoped_lock(&mut key, |(number, string)| {
/// *number += 1;
/// *string = "1";
/// });
/// ```
pub fn scoped_lock<'s, R>(
&'s self,
key: impl Keyable,
f: impl FnOnce(L::DataMut<'s>) -> R,
) -> R {
scoped_write(self, key, f)
}
/// Attempts to acquire an exclusive lock to the underlying data without
/// blocking, and then unlocks once the provided function returns.
///
/// This function implements a non-blocking variant of [`scoped_lock`].
/// Unlike `scoped_lock`, if the lock collection is not already unlocked, then
/// the provided function will not run, and the given [`Keyable`] is returned.
/// This method does not provide any guarantees with respect to the ordering
/// of whether contentious readers or writers will acquire the lock first.
///
/// # Errors
///
/// If any of the locks in the collection are already locked, then the
/// provided function will not run. `Err` is returned with the given key.
///
/// # Panics
///
/// This function will panic if the provided function also panics. However,
/// the collection will be safely unlocked in this case, allowing the
/// collection to be locked again later.
///
/// # Example
///
/// ```
/// use happylock::{ThreadKey, Mutex};
/// use happylock::collection::RefLockCollection;
///
/// let mut key = ThreadKey::get().unwrap();
/// let data = (Mutex::new(0), Mutex::new(""));
/// let lock = RefLockCollection::new(&data);
///
/// lock.scoped_try_lock(&mut key, |(number, string)| {
/// *number += 1;
/// *string = "1";
/// }).expect("This lock has not yet been locked");
/// ```
///
/// [`scoped_lock`]: RefLockCollection::scoped_lock
pub fn scoped_try_lock<'s, Key: Keyable, R>(
&'s self,
key: Key,
f: impl FnOnce(L::DataMut<'s>) -> R,
) -> Result<R, Key> {
scoped_try_write(self, key, f)
}
/// Locks the collection
///
/// This function returns a guard that can be used to access the underlying
/// data. When the guard is dropped, the locks in the collection are also
/// dropped.
///
/// # Examples
///
/// ```
/// use happylock::{Mutex, ThreadKey};
/// use happylock::collection::RefLockCollection;
///
/// let key = ThreadKey::get().unwrap();
/// let data = (Mutex::new(0), Mutex::new(""));
/// let lock = RefLockCollection::new(&data);
///
/// let mut guard = lock.lock(key);
/// *guard.0 += 1;
/// *guard.1 = "1";
/// ```
#[must_use]
pub fn lock(&self, key: ThreadKey) -> LockGuard<L::Guard<'_>> {
let guard = unsafe {
// safety: we have the thread key
self.raw_write();
// safety: we've locked all of this already
self.child.guard()
};
LockGuard { guard, key }
}
/// Attempts to lock the without blocking.
///
/// If the access could not be granted at this time, then `Err` is
/// returned. Otherwise, an RAII guard is returned which will release the
/// locks when it is dropped.
///
/// # Errors
///
/// If any of the locks in the collection are already locked, then an error
/// is returned containing the given key.
///
/// # Examples
///
/// ```
/// use happylock::{Mutex, ThreadKey};
/// use happylock::collection::RefLockCollection;
///
/// let key = ThreadKey::get().unwrap();
/// let data = (Mutex::new(0), Mutex::new(""));
/// let lock = RefLockCollection::new(&data);
///
/// match lock.try_lock(key) {
/// Ok(mut guard) => {
/// *guard.0 += 1;
/// *guard.1 = "1";
/// },
/// Err(_) => unreachable!(),
/// };
///
/// ```
pub fn try_lock(&self, key: ThreadKey) -> Result<LockGuard<L::Guard<'_>>, ThreadKey> {
let guard = unsafe {
// safety: we have the thread key
if !self.raw_try_write() {
return Err(key);
}
// safety: we've acquired the locks
self.child.guard()
};
Ok(LockGuard { guard, key })
}
/// Unlocks the underlying lockable data type, returning the key that's
/// associated with it.
///
/// # Examples
///
/// ```
/// use happylock::{Mutex, ThreadKey};
/// use happylock::collection::RefLockCollection;
///
/// let key = ThreadKey::get().unwrap();
/// let data = (Mutex::new(0), Mutex::new(""));
/// let lock = RefLockCollection::new(&data);
///
/// let mut guard = lock.lock(key);
/// *guard.0 += 1;
/// *guard.1 = "1";
/// let key = RefLockCollection::<(Mutex<i32>, Mutex<&str>)>::unlock(guard);
/// ```
#[allow(clippy::missing_const_for_fn)]
pub fn unlock(guard: LockGuard<L::Guard<'_>>) -> ThreadKey {
drop(guard.guard);
guard.key
}
}
impl<L: Sharable> RefLockCollection<'_, L> {
/// Acquires a shared lock, blocking until it is safe to do so, and then
/// unlocks after the provided function returns.
///
/// This function is useful to ensure that the data is never accidentally
/// locked forever by leaking the guard. Even if the function panics, this
/// function will gracefully notice the panic, and unlock. This function
/// provides no guarantees with respect to the ordering of whether contentious
/// readers or writers will acquire the lock first.
///
/// # Panics
///
/// This function will panic if the provided function also panics. However,
/// the collection will be safely unlocked in this case, allowing the
/// collection to be locked again later.
///
/// # Example
///
/// ```
/// use happylock::{ThreadKey, RwLock};
/// use happylock::collection::RefLockCollection;
///
/// let mut key = ThreadKey::get().unwrap();
/// let data = (RwLock::new(0), RwLock::new(""));
/// let lock = RefLockCollection::new(&data);
///
/// lock.scoped_read(&mut key, |(number, string)| {
/// assert_eq!(*number, 0);
/// assert_eq!(*string, "");
/// });
/// ```
pub fn scoped_read<'a, R>(
&'a self,
key: impl Keyable,
f: impl FnOnce(L::DataRef<'a>) -> R,
) -> R {
scoped_read(self, key, f)
}
/// Attempts to acquire an exclusive lock to the underlying data without
/// blocking, and then unlocks once the provided function returns.
///
/// This function implements a non-blocking variant of [`scoped_read`].
/// Unlike `scoped_read`, if the lock collection is exclusively locked, then
/// the provided function will not run, and the given [`Keyable`] is returned.
/// This method does not provide any guarantees with respect to the ordering
/// of whether contentious readers or writers will acquire the lock first.
///
/// # Errors
///
/// If any of the locks in the collection are already exclusively locked, then
/// the provided function will not run. `Err` is returned with the given key.
///
/// # Panics
///
/// This function will panic if the provided function also panics. However,
/// the collection will be safely unlocked in this case, allowing the
/// collection to be locked again later.
///
/// # Example
///
/// ```
/// use happylock::{ThreadKey, RwLock};
/// use happylock::collection::RefLockCollection;
///
/// let mut key = ThreadKey::get().unwrap();
/// let data = (RwLock::new(0), RwLock::new(""));
/// let lock = RefLockCollection::new(&data);
///
/// lock.scoped_try_read(&mut key, |(number, string)| {
/// assert_eq!(*number, 0);
/// assert_eq!(*string, "");
/// }).expect("This lock has not yet been locked");
/// ```
///
/// [`scoped_read`]: RefLockCollection::scoped_read
pub fn scoped_try_read<'a, Key: Keyable, R>(
&'a self,
key: Key,
f: impl FnOnce(L::DataRef<'a>) -> R,
) -> Result<R, Key> {
scoped_try_read(self, key, f)
}
/// Locks the collection, so that other threads can still read from it
///
/// This function returns a guard that can be used to access the underlying
/// data immutably. When the guard is dropped, the locks in the collection
/// are also dropped.
///
/// # Examples
///
/// ```
/// use happylock::{RwLock, ThreadKey};
/// use happylock::collection::RefLockCollection;
///
/// let key = ThreadKey::get().unwrap();
/// let data = (RwLock::new(0), RwLock::new(""));
/// let lock = RefLockCollection::new(&data);
///
/// let mut guard = lock.read(key);
/// assert_eq!(*guard.0, 0);
/// assert_eq!(*guard.1, "");
/// ```
#[must_use]
pub fn read(&self, key: ThreadKey) -> LockGuard<L::ReadGuard<'_>> {
unsafe {
// safety: we have the thread key
self.raw_read();
LockGuard {
// safety: we've already acquired the lock
guard: self.child.read_guard(),
key,
}
}
}
/// Attempts to lock the without blocking, in such a way that other threads
/// can still read from the collection.
///
/// If the access could not be granted at this time, then `Err` is
/// returned. Otherwise, an RAII guard is returned which will release the
/// shared access when it is dropped.
///
/// # Errors
///
/// If any of the locks in the collection are already locked, then an error
/// is returned containing the given key.
///
/// # Examples
///
/// ```
/// use happylock::{RwLock, ThreadKey};
/// use happylock::collection::RefLockCollection;
///
/// let key = ThreadKey::get().unwrap();
/// let data = (RwLock::new(5), RwLock::new("6"));
/// let lock = RefLockCollection::new(&data);
///
/// match lock.try_read(key) {
/// Ok(mut guard) => {
/// assert_eq!(*guard.0, 5);
/// assert_eq!(*guard.1, "6");
/// },
/// Err(_) => unreachable!(),
/// };
///
/// ```
pub fn try_read(&self, key: ThreadKey) -> Result<LockGuard<L::ReadGuard<'_>>, ThreadKey> {
let guard = unsafe {
// safety: we have the thread key
if !self.raw_try_read() {
return Err(key);
}
// safety: we've acquired the locks
self.child.read_guard()
};
Ok(LockGuard { guard, key })
}
/// Unlocks the underlying lockable data type, returning the key that's
/// associated with it.
///
/// # Examples
///
/// ```
/// use happylock::{RwLock, ThreadKey};
/// use happylock::collection::RefLockCollection;
///
/// let key = ThreadKey::get().unwrap();
/// let data = (RwLock::new(0), RwLock::new(""));
/// let lock = RefLockCollection::new(&data);
///
/// let mut guard = lock.read(key);
/// let key = RefLockCollection::<(RwLock<i32>, RwLock<&str>)>::unlock_read(guard);
/// ```
#[allow(clippy::missing_const_for_fn)]
pub fn unlock_read(guard: LockGuard<L::ReadGuard<'_>>) -> ThreadKey {
drop(guard.guard);
guard.key
}
}
impl<'a, L: 'a> RefLockCollection<'a, L>
where
&'a L: IntoIterator,
{
/// Returns an iterator over references to each value in the collection.
///
/// # Examples
///
/// ```
/// use happylock::{Mutex, ThreadKey};
/// use happylock::collection::RefLockCollection;
///
/// let key = ThreadKey::get().unwrap();
/// let data = [Mutex::new(26), Mutex::new(1)];
/// let lock = RefLockCollection::new(&data);
///
/// let mut iter = lock.iter();
/// let mutex = iter.next().unwrap();
/// let guard = mutex.lock(key);
///
/// assert_eq!(*guard, 26);
/// ```
#[must_use]
pub fn iter(&'a self) -> <&'a L as IntoIterator>::IntoIter {
self.into_iter()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Mutex, RwLock, ThreadKey};
#[test]
fn non_duplicates_allowed() {
let mutex1 = Mutex::new(0);
let mutex2 = Mutex::new(1);
assert!(RefLockCollection::try_new(&[&mutex1, &mutex2]).is_some())
}
#[test]
fn duplicates_not_allowed() {
let mutex1 = Mutex::new(0);
assert!(RefLockCollection::try_new(&[&mutex1, &mutex1]).is_none())
}
#[test]
fn from() {
let key = ThreadKey::get().unwrap();
let mutexes = [Mutex::new("foo"), Mutex::new("bar"), Mutex::new("baz")];
let collection = RefLockCollection::from(&mutexes);
let guard = collection.lock(key);
assert_eq!(*guard[0], "foo");
assert_eq!(*guard[1], "bar");
assert_eq!(*guard[2], "baz");
}
#[test]
fn scoped_lock_changes_collection() {
let mut key = ThreadKey::get().unwrap();
let mutexes = [Mutex::new(24), Mutex::new(42)];
let collection = RefLockCollection::new(&mutexes);
let sum = collection.scoped_lock(&mut key, |guard| {
*guard[0] = 128;
*guard[0] + *guard[1]
});
assert_eq!(sum, 128 + 42);
let guard = collection.lock(key);
assert_eq!(*guard[0], 128);
assert_eq!(*guard[1], 42);
}
#[test]
fn scoped_read_sees_changes() {
let mut key = ThreadKey::get().unwrap();
let mutexes = [RwLock::new(24), RwLock::new(42)];
let collection = RefLockCollection::new(&mutexes);
collection.scoped_lock(&mut key, |guard| {
*guard[0] = 128;
});
let sum = collection.scoped_read(&mut key, |guard| {
assert_eq!(*guard[0], 128);
assert_eq!(*guard[1], 42);
*guard[0] + *guard[1]
});
assert_eq!(sum, 128 + 42);
}
#[test]
fn scoped_try_lock_can_fail() {
let key = ThreadKey::get().unwrap();
let locks = [Mutex::new(1), Mutex::new(2)];
let collection = RefLockCollection::new(&locks);
let guard = collection.lock(key);
std::thread::scope(|s| {
s.spawn(|| {
let key = ThreadKey::get().unwrap();
let r = collection.scoped_try_lock(key, |_| {});
assert!(r.is_err());
});
});
drop(guard);
}
#[test]
fn scoped_try_read_can_fail() {
let key = ThreadKey::get().unwrap();
let locks = [RwLock::new(1), RwLock::new(2)];
let collection = RefLockCollection::new(&locks);
let guard = collection.lock(key);
std::thread::scope(|s| {
s.spawn(|| {
let key = ThreadKey::get().unwrap();
let r = collection.scoped_try_read(key, |_| {});
assert!(r.is_err());
});
});
drop(guard);
}
#[test]
fn try_lock_succeeds_for_unlocked_collection() {
let key = ThreadKey::get().unwrap();
let mutexes = [Mutex::new(24), Mutex::new(42)];
let collection = RefLockCollection::new(&mutexes);
let guard = collection.try_lock(key).unwrap();
assert_eq!(*guard[0], 24);
assert_eq!(*guard[1], 42);
}
#[test]
fn try_lock_fails_for_locked_collection() {
let key = ThreadKey::get().unwrap();
let mutexes = [Mutex::new(24), Mutex::new(42)];
let collection = RefLockCollection::new(&mutexes);
std::thread::scope(|s| {
s.spawn(|| {
let key = ThreadKey::get().unwrap();
let guard = mutexes[1].lock(key);
assert_eq!(*guard, 42);
std::mem::forget(guard);
});
});
let guard = collection.try_lock(key);
assert!(guard.is_err());
}
#[test]
fn try_read_succeeds_for_unlocked_collection() {
let key = ThreadKey::get().unwrap();
let mutexes = [RwLock::new(24), RwLock::new(42)];
let collection = RefLockCollection::new(&mutexes);
let guard = collection.try_read(key).unwrap();
assert_eq!(*guard[0], 24);
assert_eq!(*guard[1], 42);
}
#[test]
fn try_read_fails_for_locked_collection() {
let key = ThreadKey::get().unwrap();
let mutexes = [RwLock::new(24), RwLock::new(42)];
let collection = RefLockCollection::new(&mutexes);
std::thread::scope(|s| {
s.spawn(|| {
let key = ThreadKey::get().unwrap();
let guard = mutexes[1].write(key);
assert_eq!(*guard, 42);
std::mem::forget(guard);
});
});
let guard = collection.try_read(key);
assert!(guard.is_err());
}
#[test]
fn can_read_twice_on_different_threads() {
let key = ThreadKey::get().unwrap();
let mutexes = [RwLock::new(24), RwLock::new(42)];
let collection = RefLockCollection::new(&mutexes);
std::thread::scope(|s| {
s.spawn(|| {
let key = ThreadKey::get().unwrap();
let guard = collection.read(key);
assert_eq!(*guard[0], 24);
assert_eq!(*guard[1], 42);
std::mem::forget(guard);
});
});
let guard = collection.try_read(key).unwrap();
assert_eq!(*guard[0], 24);
assert_eq!(*guard[1], 42);
}
#[test]
fn into_ref_iterator() {
let mut key = ThreadKey::get().unwrap();
let mutexes = [Mutex::new(0), Mutex::new(1), Mutex::new(2)];
let collection = RefLockCollection::new(&mutexes);
for (i, mutex) in (&collection).into_iter().enumerate() {
mutex.scoped_lock(&mut key, |val| assert_eq!(*val, i))
}
}
#[test]
fn ref_iterator() {
let mut key = ThreadKey::get().unwrap();
let mutexes = [Mutex::new(0), Mutex::new(1), Mutex::new(2)];
let collection = RefLockCollection::new(&mutexes);
for (i, mutex) in collection.iter().enumerate() {
mutex.scoped_lock(&mut key, |val| assert_eq!(*val, i))
}
}
#[test]
fn works_in_collection() {
let key = ThreadKey::get().unwrap();
let mutex1 = RwLock::new(0);
let mutex2 = RwLock::new(1);
let collection0 = [&mutex1, &mutex2];
let collection1 = RefLockCollection::try_new(&collection0).unwrap();
let collection = RefLockCollection::try_new(&collection1).unwrap();
let mut guard = collection.lock(key);
assert!(mutex1.is_locked());
assert!(mutex2.is_locked());
assert_eq!(*guard[0], 0);
assert_eq!(*guard[1], 1);
*guard[1] = 2;
drop(guard);
let key = ThreadKey::get().unwrap();
let guard = collection.read(key);
assert!(mutex1.is_locked());
assert!(mutex2.is_locked());
assert_eq!(*guard[0], 0);
assert_eq!(*guard[1], 2);
}
#[test]
fn unlock_collection_works() {
let key = ThreadKey::get().unwrap();
let mutexes = (Mutex::new("foo"), Mutex::new("bar"));
let collection = RefLockCollection::new(&mutexes);
let guard = collection.lock(key);
let key = RefLockCollection::<(Mutex<_>, Mutex<_>)>::unlock(guard);
assert!(collection.try_lock(key).is_ok())
}
#[test]
fn read_unlock_collection_works() {
let key = ThreadKey::get().unwrap();
let locks = (RwLock::new("foo"), RwLock::new("bar"));
let collection = RefLockCollection::new(&locks);
let guard = collection.read(key);
let key = RefLockCollection::<(&RwLock<_>, &RwLock<_>)>::unlock_read(guard);
assert!(collection.try_lock(key).is_ok())
}
#[test]
fn as_ref_works() {
let mutexes = [Mutex::new(0), Mutex::new(1)];
let collection = RefLockCollection::new(&mutexes);
assert!(std::ptr::addr_eq(&raw const mutexes, collection.as_ref()))
}
#[test]
fn child() {
let mutexes = [Mutex::new(0), Mutex::new(1)];
let collection = RefLockCollection::new(&mutexes);
assert!(std::ptr::addr_eq(&raw const mutexes, collection.child()))
}
}