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
use std::panic::{RefUnwindSafe, UnwindSafe};
use crate::handle_unwind::handle_unwind;
use crate::lockable::{
Lockable, LockableGetMut, LockableIntoInner, OwnedLockable, RawLock, Sharable,
};
use crate::{Keyable, ThreadKey};
use super::{
PoisonError, PoisonFlag, PoisonGuard, PoisonRef, PoisonResult, Poisonable,
TryLockPoisonableError, TryLockPoisonableResult,
};
unsafe impl<L: Lockable + RawLock> RawLock for Poisonable<L> {
#[mutants::skip] // this should never run
#[cfg(not(tarpaulin_include))]
fn poison(&self) {
self.inner.poison()
}
unsafe fn raw_write(&self) {
self.inner.raw_write()
}
unsafe fn raw_try_write(&self) -> bool {
self.inner.raw_try_write()
}
unsafe fn raw_unlock_write(&self) {
self.inner.raw_unlock_write()
}
unsafe fn raw_read(&self) {
self.inner.raw_read()
}
unsafe fn raw_try_read(&self) -> bool {
self.inner.raw_try_read()
}
unsafe fn raw_unlock_read(&self) {
self.inner.raw_unlock_read()
}
}
unsafe impl<L: Lockable> Lockable for Poisonable<L> {
type Guard<'g>
= PoisonResult<PoisonRef<'g, L::Guard<'g>>>
where
Self: 'g;
type DataMut<'a>
= PoisonResult<L::DataMut<'a>>
where
Self: 'a;
fn get_ptrs<'a>(&'a self, ptrs: &mut Vec<&'a dyn RawLock>) {
self.inner.get_ptrs(ptrs)
}
unsafe fn guard(&self) -> Self::Guard<'_> {
let ref_guard = PoisonRef::new(&self.poisoned, self.inner.guard());
if self.is_poisoned() {
Err(PoisonError::new(ref_guard))
} else {
Ok(ref_guard)
}
}
unsafe fn data_mut(&self) -> Self::DataMut<'_> {
if self.is_poisoned() {
Err(PoisonError::new(self.inner.data_mut()))
} else {
Ok(self.inner.data_mut())
}
}
}
unsafe impl<L: Sharable> Sharable for Poisonable<L> {
type ReadGuard<'g>
= PoisonResult<PoisonRef<'g, L::ReadGuard<'g>>>
where
Self: 'g;
type DataRef<'a>
= PoisonResult<L::DataRef<'a>>
where
Self: 'a;
unsafe fn read_guard(&self) -> Self::ReadGuard<'_> {
let ref_guard = PoisonRef::new(&self.poisoned, self.inner.read_guard());
if self.is_poisoned() {
Err(PoisonError::new(ref_guard))
} else {
Ok(ref_guard)
}
}
unsafe fn data_ref(&self) -> Self::DataRef<'_> {
if self.is_poisoned() {
Err(PoisonError::new(self.inner.data_ref()))
} else {
Ok(self.inner.data_ref())
}
}
}
unsafe impl<L: OwnedLockable> OwnedLockable for Poisonable<L> {}
// AsMut won't work here because we don't strictly return a &mut T
// LockableGetMut is the next best thing
impl<L: LockableGetMut> LockableGetMut for Poisonable<L> {
type Inner<'a>
= PoisonResult<L::Inner<'a>>
where
Self: 'a;
fn get_mut(&mut self) -> Self::Inner<'_> {
if self.is_poisoned() {
Err(PoisonError::new(self.inner.get_mut()))
} else {
Ok(self.inner.get_mut())
}
}
}
impl<L: LockableIntoInner> LockableIntoInner for Poisonable<L> {
type Inner = PoisonResult<L::Inner>;
fn into_inner(self) -> Self::Inner {
if self.is_poisoned() {
Err(PoisonError::new(self.inner.into_inner()))
} else {
Ok(self.inner.into_inner())
}
}
}
impl<L> From<L> for Poisonable<L> {
fn from(value: L) -> Self {
Self::new(value)
}
}
impl<L> Poisonable<L> {
/// Creates a new `Poisonable`
///
/// # Examples
///
/// ```
/// use happylock::{Mutex, Poisonable};
///
/// let mutex = Poisonable::new(Mutex::new(0));
/// ```
pub const fn new(value: L) -> Self {
Self {
inner: value,
poisoned: PoisonFlag::new(),
}
}
/// Determines whether the `Poisonable` is poisoned.
///
/// If another thread is active, the `Poisonable` can still become poisoned at
/// any time. You should not trust a `false` value for program correctness
/// without additional synchronization.
///
/// # Examples
///
/// ```
/// use std::thread;
///
/// use happylock::{Mutex, Poisonable, ThreadKey};
///
/// let mutex = Poisonable::new(Mutex::new(0));
///
/// thread::scope(|s| {
/// let r = s.spawn(|| {
/// let key = ThreadKey::get().unwrap();
/// let _lock = mutex.lock(key).unwrap();
/// panic!(); // the mutex gets poisoned
/// }).join();
/// });
///
/// assert_eq!(mutex.is_poisoned(), true);
/// ```
pub fn is_poisoned(&self) -> bool {
self.poisoned.is_poisoned()
}
/// Clear the poisoned state from a lock.
///
/// If the lock is poisoned, it will remain poisoned until this function
/// is called. This allows recovering from a poisoned state and marking
/// that it has recovered. For example, if the value is overwritten by a
/// known-good value, then the lock can be marked as un-poisoned. Or
/// possibly, the value could by inspected to determine if it is in a
/// consistent state, and if so the poison is removed.
///
/// # Examples
///
/// ```
/// use std::thread;
///
/// use happylock::{Mutex, Poisonable, ThreadKey};
///
/// let mutex = Poisonable::new(Mutex::new(0));
///
/// thread::scope(|s| {
/// let r = s.spawn(|| {
/// let key = ThreadKey::get().unwrap();
/// let _lock = mutex.lock(key).unwrap();
/// panic!(); // the mutex gets poisoned
/// }).join();
/// });
///
/// assert_eq!(mutex.is_poisoned(), true);
///
/// let key = ThreadKey::get().unwrap();
/// let x = mutex.lock(key).unwrap_or_else(|mut e| {
/// **e.get_mut() = 1;
/// mutex.clear_poison();
/// e.into_inner()
/// });
///
/// assert_eq!(mutex.is_poisoned(), false);
/// assert_eq!(*x, 1);
/// ```
pub fn clear_poison(&self) {
self.poisoned.clear_poison()
}
/// Consumes this `Poisonable`, returning the underlying lock.
///
/// # Errors
///
/// If another user of this lock panicked while holding the lock, then this
/// call will return an error instead.
///
/// # Examples
///
/// ```
/// use happylock::{Mutex, Poisonable};
///
/// let mutex = Poisonable::new(Mutex::new(0));
/// assert_eq!(mutex.into_child().unwrap().into_inner(), 0);
/// ```
pub fn into_child(self) -> PoisonResult<L> {
if self.is_poisoned() {
Err(PoisonError::new(self.inner))
} else {
Ok(self.inner)
}
}
/// Returns a mutable reference to the underlying lock.
///
/// # Errors
///
/// If another user of this lock panicked while holding the lock, then
/// this call will return an error instead.
///
/// # Examples
///
/// ```
/// use happylock::{Mutex, Poisonable, ThreadKey};
///
/// let key = ThreadKey::get().unwrap();
/// let mut mutex = Poisonable::new(Mutex::new(0));
/// *mutex.child_mut().unwrap().as_mut() = 10;
/// assert_eq!(*mutex.lock(key).unwrap(), 10);
/// ```
pub fn child_mut(&mut self) -> PoisonResult<&mut L> {
if self.is_poisoned() {
Err(PoisonError::new(&mut self.inner))
} else {
Ok(&mut self.inner)
}
}
// NOTE: `child_ref` isn't implemented because it would make this not `RefUnwindSafe`
}
impl<L: Lockable> Poisonable<L> {
/// Creates a guard for the poisonable, without locking it
unsafe fn guard(&self, key: ThreadKey) -> PoisonResult<PoisonGuard<'_, L::Guard<'_>>> {
let guard = PoisonGuard {
guard: PoisonRef::new(&self.poisoned, self.inner.guard()),
key,
};
if self.is_poisoned() {
return Err(PoisonError::new(guard));
}
Ok(guard)
}
}
impl<L: Lockable + RawLock> Poisonable<L> {
/// 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 a `Poisonable` is never
/// accidentally locked forever by leaking the guard. Even if the function
/// panics, this function will gracefully notice the panic, poison the lock,
/// and unlock.
///
/// If the lock is poisoned, then an error will be passed into the provided
/// function.
///
/// # Panics
///
/// This function will panic if the provided function also panics. However,
/// `Poisonable` will be safely poisoned and any subsequent calls will pass
/// `Err` into the given function.
///
/// # Example
///
/// ```
/// use happylock::{Poisonable, ThreadKey, RwLock};
///
/// let mut key = ThreadKey::get().unwrap();
/// let lock = Poisonable::new(RwLock::new(42));
///
/// let x = lock.scoped_lock(&mut key, |number| {
/// *number.unwrap()
/// });
/// assert_eq!(x, 42);
/// ```
pub fn scoped_lock<'a, R>(
&'a self,
key: impl Keyable,
f: impl FnOnce(<Self as Lockable>::DataMut<'a>) -> R,
) -> R {
unsafe {
// safety: we have the thread key
self.raw_write();
// safety: the data was just locked
let r = handle_unwind(
|| f(self.data_mut()),
|| {
self.poisoned.poison();
self.raw_unlock_write();
},
);
// safety: the collection is still locked
self.raw_unlock_write();
drop(key); // ensure the key stays alive long enough
r
}
}
/// Attempts to acquire an exclusive lock to the `Poisonable` without
/// blocking, and then unlocks it once the provided function returns.
///
/// This function implements a non-blocking variant of [`scoped_lock`].
/// Unlike `scoped_lock`, if the `Poisonable` 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.
///
/// If the lock is poisoned, then an error will be passed into the provided
/// function.
///
/// # Errors
///
/// If the `Poisonable` is already locked, then the provided function will not
/// run. `Err` is returned with the given key.
///
/// # Panics
///
/// If the provided function panics, then the panic will be bubbled up and
/// rethrown. The `Poisonable` will also be gracefully unlocked, allowing the
/// `Poisonable` to be locked again.
///
/// # Examples
///
/// ```
/// use happylock::{Poisonable, RwLock, ThreadKey};
///
/// let mut key = ThreadKey::get().unwrap();
/// let lock = Poisonable::new(RwLock::new(42));
///
/// let result = lock.scoped_try_lock(&mut key, |num| {
/// *num.unwrap()
/// });
///
/// match result {
/// Ok(val) => println!("The number is {val}"),
/// Err(_) => unreachable!(),
/// }
/// ```
///
/// [`scoped_lock`]: [`crate::Poisonable::scoped_lock`]
pub fn scoped_try_lock<'a, Key: Keyable, R>(
&'a self,
key: Key,
f: impl FnOnce(<Self as Lockable>::DataMut<'a>) -> R,
) -> Result<R, Key> {
unsafe {
// safety: we have the thread key
if !self.raw_try_write() {
return Err(key);
}
// safety: we just locked the collection
let r = handle_unwind(
|| f(self.data_mut()),
|| {
self.poisoned.poison();
self.raw_unlock_write();
},
);
// safety: the collection is still locked
self.raw_unlock_write();
drop(key); // ensures the key stays valid long enough
Ok(r)
}
}
/// Acquires the lock, blocking the current thread until it is ok to do so.
///
/// This function will block the current thread until it is available to
/// acquire the lock. Upon returning, the thread is the only thread with
/// the lock held. An RAII guard is returned to allow scoped unlock of the
/// lock. When the guard goes out of scope, the mutex will be unlocked.
///
/// # Errors
///
/// If another use of this lock panicked while holding the mutex, then
/// this call will return an error once the mutex is acquired.
///
/// # Examples
///
/// ```
/// use std::thread;
///
/// use happylock::{Mutex, Poisonable, ThreadKey};
///
/// let mutex = Poisonable::new(Mutex::new(0));
///
/// thread::scope(|s| {
/// let r = s.spawn(|| {
/// let key = ThreadKey::get().unwrap();
/// *mutex.lock(key).unwrap() = 10;
/// }).join();
/// });
///
/// let key = ThreadKey::get().unwrap();
/// assert_eq!(*mutex.lock(key).unwrap(), 10);
/// ```
pub fn lock(&self, key: ThreadKey) -> PoisonResult<PoisonGuard<'_, L::Guard<'_>>> {
unsafe {
self.inner.raw_write();
self.guard(key)
}
}
/// Attempts to acquire this lock.
///
/// If the lock could not be acquired at this time, then [`Err`] is
/// returned. Otherwise, an RAII guard is returned. The lock will be
/// unlocked when the guard is dropped.
///
/// This function does not block.
///
/// # Errors
///
/// If another user of this lock panicked while holding the lock, then this
/// call will return the [`Poisoned`] error if the lock would otherwise be
/// acquired.
///
/// If the lock could not be acquired because it is already locked, then
/// this call will return the [`WouldBlock`] error.
///
/// # Examples
///
/// ```
/// use std::thread;
///
/// use happylock::{Mutex, Poisonable, ThreadKey};
///
/// let mutex = Poisonable::new(Mutex::new(0));
///
/// thread::scope(|s| {
/// s.spawn(|| {
/// let key = ThreadKey::get().unwrap();
/// let mut lock = mutex.try_lock(key);
/// if let Ok(mut mutex) = lock {
/// *mutex = 10;
/// } else {
/// println!("try_lock failed");
/// }
/// });
/// });
///
/// let key = ThreadKey::get().unwrap();
/// assert_eq!(*mutex.lock(key).unwrap(), 10);
/// ```
///
/// [`Poisoned`]: `TryLockPoisonableError::Poisoned`
/// [`WouldBlock`]: `TryLockPoisonableError::WouldBlock`
pub fn try_lock(&self, key: ThreadKey) -> TryLockPoisonableResult<'_, L::Guard<'_>> {
unsafe {
if self.inner.raw_try_write() {
Ok(self.guard(key)?)
} else {
Err(TryLockPoisonableError::WouldBlock(key))
}
}
}
/// Consumes the [`PoisonGuard`], and consequently unlocks its `Poisonable`.
///
/// This function is equivalent to calling [`drop`] on the guard, except that
/// it returns the key that was used to create it. Alternatively, the guard
/// will be automatically dropped when it goes out of scope.
///
/// # Examples
///
/// ```
/// use happylock::{ThreadKey, Mutex, Poisonable};
///
/// let key = ThreadKey::get().unwrap();
/// let mutex = Poisonable::new(Mutex::new(0));
///
/// let mut guard = mutex.lock(key).unwrap();
/// *guard += 20;
///
/// let key = Poisonable::<Mutex<_>>::unlock(guard);
/// ```
pub fn unlock<'flag>(guard: PoisonGuard<'flag, L::Guard<'flag>>) -> ThreadKey {
drop(guard.guard);
guard.key
}
}
impl<L: Sharable + RawLock> Poisonable<L> {
unsafe fn read_guard(&self, key: ThreadKey) -> PoisonResult<PoisonGuard<'_, L::ReadGuard<'_>>> {
let guard = PoisonGuard {
guard: PoisonRef::new(&self.poisoned, self.inner.read_guard()),
key,
};
if self.is_poisoned() {
return Err(PoisonError::new(guard));
}
Ok(guard)
}
/// 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 a `Poisonable` is never
/// accidentally locked forever by leaking the `ReadGuard`. 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.
///
/// If the lock is poisoned, then an error will be passed into the provided
/// into the provided function.
///
/// # Panics
///
/// This function will panic if the provided function also panics. However,
/// `Poisonable` will be safely unlocked in this case, allowing the
/// `Poisonable` to be locked again later.
///
/// # Example
///
/// ```
/// use happylock::{Poisonable, ThreadKey, RwLock};
///
/// let mut key = ThreadKey::get().unwrap();
/// let lock = Poisonable::new(RwLock::new(42));
///
/// let x = lock.scoped_read(&mut key, |number| {
/// *number.unwrap()
/// });
/// assert_eq!(x, 42);
/// ```
pub fn scoped_read<'a, R>(
&'a self,
key: impl Keyable,
f: impl FnOnce(<Self as Sharable>::DataRef<'a>) -> R,
) -> R {
unsafe {
// safety: we have the thread key
self.raw_read();
// safety: the data was just locked
let r = handle_unwind(
|| f(self.data_ref()),
|| {
self.poisoned.poison();
self.raw_unlock_read();
},
);
// safety: the collection is still locked
self.raw_unlock_read();
drop(key); // ensure the key stays alive long enough
r
}
}
/// Attempts to acquire a shared lock to the `Poisonable` without blocking,
/// and then unlocks it once the provided function returns.
///
/// This function implements a non-blocking variant of [`scoped_read`].
/// Unlike `scoped_read`, if the `Poisonable` is exclusively locked, then the
/// provided function will not run, and the given [`Keyable`] is returned.
/// This method provides no guarantees with respect to the ordering of whether
/// contentious readers of writers will acquire the lock first.
///
/// If the lock is poisoned, then an error will be passed into the provided
/// function.
///
/// # Errors
///
/// If the `Poisonable` is already exclusively locked, then the provided
/// function will not run. `Err` is returned with the given key.
///
/// # Panics
///
/// If the provided function panics, then the panic will be bubbled up and
/// rethrown. The `Poisonable` will also be gracefully unlocked, allowing the
/// `Poisonable` to be locked again.
///
/// # Examples
///
/// ```
/// use happylock::{Poisonable, RwLock, ThreadKey};
///
/// let mut key = ThreadKey::get().unwrap();
/// let lock = Poisonable::new(RwLock::new(42));
///
/// let result = lock.scoped_try_read(&mut key, |num| {
/// *num.unwrap()
/// });
///
/// match result {
/// Ok(val) => println!("The number is {val}"),
/// Err(_) => unreachable!(),
/// }
/// ```
///
/// [`scoped_read`]: crate::Poisonable::scoped_read
pub fn scoped_try_read<'a, Key: Keyable, R>(
&'a self,
key: Key,
f: impl FnOnce(<Self as Sharable>::DataRef<'a>) -> R,
) -> Result<R, Key> {
unsafe {
// safety: we have the thread key
if !self.raw_try_read() {
return Err(key);
}
// safety: we just locked the collection
let r = handle_unwind(
|| f(self.data_ref()),
|| {
self.poisoned.poison();
self.raw_unlock_read();
},
);
// safety: the collection is still locked
self.raw_unlock_read();
drop(key); // ensures the key stays valid long enough
Ok(r)
}
}
/// Locks with shared read access, blocking the current thread until it can
/// be acquired.
///
/// This function will block the current thread until there are no writers
/// which hold the lock. This method does not provide any guarantee with
/// respect to the ordering of contentious readers or writers will acquire
/// the lock.
///
/// # Errors
///
/// This function will return an error if the `Poisonable` is poisoned. A
/// `Poisonable` is poisoned whenever a thread panics while holding a lock.
/// The failure will occur immediately after the lock has been acquired. The
/// acquired lock guard will be contained in the returned error.
///
/// # Examples
///
/// ```
/// use std::thread;
///
/// use happylock::{RwLock, Poisonable, ThreadKey};
///
/// let key = ThreadKey::get().unwrap();
/// let lock = Poisonable::new(RwLock::new(0));
///
/// let n = lock.read(key).unwrap();
/// assert_eq!(*n, 0);
///
/// thread::scope(|s| {
/// s.spawn(|| {
/// let key = ThreadKey::get().unwrap();
/// let r = lock.read(key);
/// assert!(r.is_ok());
/// });
/// });
/// ```
pub fn read(&self, key: ThreadKey) -> PoisonResult<PoisonGuard<'_, L::ReadGuard<'_>>> {
unsafe {
self.inner.raw_read();
self.read_guard(key)
}
}
/// Attempts to acquire the lock with shared read access, without blocking the
/// thread.
///
/// 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.
///
/// This function does not provide any guarantees with respect to the ordering
/// of whether contentious readers or writers will acquire the lock first.
///
/// # Errors
///
/// This function will return the [`Poisoned`] error if the lock is
/// poisoned. A [`Poisonable`] is poisoned whenever a thread panics while
/// holding a lock. `Poisoned` will only be returned if the lock would have
/// otherwise been acquired.
///
/// This function will return the [`WouldBlock`] error if the lock could
/// not be acquired because it was already locked exclusively.
///
/// # Examples
///
/// ```
/// use happylock::{Poisonable, RwLock, ThreadKey};
///
/// let key = ThreadKey::get().unwrap();
/// let lock = Poisonable::new(RwLock::new(1));
///
/// match lock.try_read(key) {
/// Ok(n) => assert_eq!(*n, 1),
/// Err(_) => unreachable!(),
/// };
/// ```
///
/// [`Poisoned`]: `TryLockPoisonableError::Poisoned`
/// [`WouldBlock`]: `TryLockPoisonableError::WouldBlock`
// TODO don't poison when holding shared lock
pub fn try_read(&self, key: ThreadKey) -> TryLockPoisonableResult<'_, L::ReadGuard<'_>> {
unsafe {
if self.inner.raw_try_read() {
Ok(self.read_guard(key)?)
} else {
Err(TryLockPoisonableError::WouldBlock(key))
}
}
}
/// Consumes the [`PoisonGuard`], and consequently unlocks its `Poisonable`.
///
/// This function is equivalent to calling [`drop`] on the guard, except that
/// it returns the key that was used to create it. Alternatively, the guard
/// will be automatically dropped when it goes out of scope.
///
/// # Examples
///
/// ```
/// use happylock::{ThreadKey, RwLock, Poisonable};
///
/// let key = ThreadKey::get().unwrap();
/// let lock = Poisonable::new(RwLock::new(20));
///
/// let mut guard = lock.read(key).unwrap();
/// assert_eq!(*guard, 20);
///
/// let key = Poisonable::<RwLock<_>>::unlock_read(guard);
/// ```
pub fn unlock_read<'flag>(guard: PoisonGuard<'flag, L::ReadGuard<'flag>>) -> ThreadKey {
drop(guard.guard);
guard.key
}
}
impl<L: LockableIntoInner> Poisonable<L> {
/// Consumes this `Poisonable`, returning the underlying data.
///
/// # Errors
///
/// If another user of this lock panicked while holding the lock, then this
/// call will return an error instead. A `Poisonable` is poisoned whenever a
/// thread panics while holding a lock.
///
/// # Examples
///
/// ```
/// use happylock::{Mutex, Poisonable};
///
/// let mutex = Poisonable::new(Mutex::new(0));
/// assert_eq!(mutex.into_inner().unwrap(), 0);
/// ```
pub fn into_inner(self) -> PoisonResult<L::Inner> {
LockableIntoInner::into_inner(self)
}
}
impl<L: LockableGetMut + RawLock> Poisonable<L> {
/// Returns a mutable reference to the underlying data.
///
/// Since this call borrows the `Poisonable` mutably, no actual locking
/// needs to take place - the mutable borrow statically guarantees no locks
/// exist.
///
/// # Errors
///
/// If another user of this lock panicked while holding the lock, then
/// this call will return an error instead. A `Poisonable` is poisoned
/// whenever a thread panics while holding a lock.
///
/// # Examples
///
/// ```
/// use happylock::{Mutex, Poisonable, ThreadKey};
///
/// let key = ThreadKey::get().unwrap();
/// let mut mutex = Poisonable::new(Mutex::new(0));
/// *mutex.get_mut().unwrap() = 10;
/// assert_eq!(*mutex.lock(key).unwrap(), 10);
/// ```
pub fn get_mut(&mut self) -> PoisonResult<L::Inner<'_>> {
LockableGetMut::get_mut(self)
}
}
impl<L: UnwindSafe> RefUnwindSafe for Poisonable<L> {}
impl<L: UnwindSafe> UnwindSafe for Poisonable<L> {}