mcslock 0.4.1

An implementation of Mellor-Crummey and Scott contention-free lock for mutual exclusion, referred to as MCS lock.
Documentation
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
use core::cell::RefCell;

use super::{Mutex, MutexNode};
use crate::cfg::thread::LocalKey;
use crate::inner::raw as inner;
use crate::relax::Relax;

#[cfg(test)]
use crate::test::{LockNew, LockThen, LockWithThen, TryLockThen, TryLockWithThen};

/// A short alias for a static shared reference over a local mutex node.
type Key = &'static LocalMutexNode;

/// Declares a new [`raw::LocalMutexNode`] key, which is a handle to the thread
/// local node of the currently running thread.
///
/// The macro wraps any number of static declarations and make them thread
/// local. Each provided name is associated with a single thread local key. The
/// keys are wrapped and managed by the [`LocalMutexNode`] type, which are the
/// actual handles meant to be used with the `lock_with_local_then` API family
/// from [`raw::Mutex`]. Handles are provided by reference to functions.
///
/// See: [`try_lock_with_local_then`], [`lock_with_local_then`],
/// [`try_lock_with_local_then_unchecked`] or [`lock_with_local_then_unchecked`].
///
/// The thread local node definition generated by this macro avoids lazy
/// initialization and does not need to be dropped, which enables a more
/// efficient underlying implementation. See [`std::thread_local!`] macro.
///
/// # Sintax
///
/// * Allows multiple static definitions, must be separated with semicolons.
/// * Visibility is optional (private by default).
/// * Requires `static` keyword and a **UPPER_SNAKE_CASE** name.
///
/// # Example
///
/// ```
/// use mcslock::raw::spins::Mutex;
///
/// // Multiple difenitions.
/// mcslock::thread_local_node! {
///     pub static NODE;
///     static OTHER_NODE1;
/// }
///
/// // Single definition.
/// mcslock::thread_local_node!(pub static OTHER_NODE2);
///
/// let mutex = Mutex::new(0);
/// // Keys are provided to APIs by reference.
/// mutex.lock_with_local_then(&NODE, |data| *data = 10);
/// assert_eq!(mutex.lock_with_local_then(&NODE, |data| *data), 10);
/// ```
/// [`raw::Mutex`]: Mutex
/// [`raw::LocalMutexNode`]: LocalMutexNode
/// [`std::thread_local!`]: https://doc.rust-lang.org/std/macro.thread_local.html
/// [`try_lock_with_local_then`]: Mutex::try_lock_with_local_then
/// [`lock_with_local_then`]: Mutex::lock_with_local_then
/// [`try_lock_with_local_then_unchecked`]: Mutex::try_lock_with_local_then_unchecked
/// [`lock_with_local_then_unchecked`]: Mutex::lock_with_local_then_unchecked
#[macro_export]
macro_rules! thread_local_node {
    // Empty (base for recursion).
    () => {};
    // Process multiply definitions (recursive).
    ($vis:vis static $node:ident; $($rest:tt)*) => {
        $crate::__thread_local_node_inner!($vis $node, raw);
        $crate::thread_local_node!($($rest)*);
    };
    // Process single declaration.
    ($vis:vis static $node:ident) => {
        $crate::__thread_local_node_inner!($vis $node, raw);
    };
}

/// A handle to a [`MutexNode`] stored at the thread local storage.
///
/// Thread local nodes can be claimed for temporary, exclusive access during
/// runtime for locking purposes. Node handles refer to the node stored at
/// the current running thread.
///
/// Just like `MutexNode`, this is an opaque type that holds metadata for the
/// [`raw::Mutex`]'s waiting queue. You must declare a thread local node with
/// the [`thread_local_node!`] macro, and provide the generated handle to the
/// appropriate [`raw::Mutex`] locking APIs. Attempting to lock a mutex with a
/// thread local node that already is in use for the locking thread will cause
/// a panic. Handles are provided by reference to functions.
///
/// See: [`try_lock_with_local_then`], [`lock_with_local_then`],
/// [`try_lock_with_local_then_unchecked`] or [`lock_with_local_then_unchecked`].
///
/// [`MutexNode`]: MutexNode
/// [`raw::Mutex`]: Mutex
/// [`try_lock_with_local_then`]: Mutex::try_lock_with_local_then
/// [`lock_with_local_then`]: Mutex::lock_with_local_then
/// [`try_lock_with_local_then_unchecked`]: Mutex::try_lock_with_local_then_unchecked
/// [`lock_with_local_then_unchecked`]: Mutex::lock_with_local_then_unchecked
#[derive(Debug)]
#[repr(transparent)]
pub struct LocalMutexNode {
    pub(crate) inner: inner::LocalMutexNode<MutexNode>,
}

#[cfg(not(tarpaulin_include))]
impl LocalMutexNode {
    /// Creates a new `LocalMutexNode` key from the provided thread local node
    /// key.
    ///
    /// This function is **NOT** part of the public API and so must not be
    /// called directly by user's code. It is subjected to changes **WITHOUT**
    /// prior notice or accompanied with relevant SemVer changes.
    #[cfg(not(all(loom, test)))]
    #[doc(hidden)]
    #[must_use]
    #[inline(always)]
    pub const fn __new(key: LocalKey<RefCell<MutexNode>>) -> Self {
        Self { inner: inner::LocalMutexNode::new(key) }
    }

    /// Creates a new Loom based `LocalMutexNode` key from the provided thread
    /// local node key.
    #[cfg(all(loom, test))]
    #[must_use]
    pub(crate) const fn new(key: &'static LocalKey<RefCell<MutexNode>>) -> Self {
        Self { inner: inner::LocalMutexNode::new(key) }
    }
}

impl<T: ?Sized, R: Relax> Mutex<T, R> {
    /// Attempts to acquire this mutex and then runs a closure against the
    /// protected data.
    ///
    /// If the lock could not be acquired at this time, then a [`None`] value is
    /// given back as the closure argument. If the lock has been acquired, then
    /// a [`Some`] value with the mutex proteced data is given instead. The lock
    /// will be unlocked when the closure scope ends.
    ///
    /// To acquire a MCS lock through this function, it's also required a
    /// queue node, which is a record that keeps a link for forming the queue,
    /// to be stored in the current locking thread local storage. See
    /// [`LocalMutexNode`] and [`thread_local_node!`].
    ///
    /// This function does not block.
    ///
    /// # Panics
    ///
    /// Will panic if the thread local node is already mutably borrowed.
    ///
    /// Panics if the key currently has its destructor running, and it **may**
    /// panic if the destructor has previously been run for this thread.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    /// use std::thread;
    ///
    /// use mcslock::raw::spins::Mutex;
    ///
    /// mcslock::thread_local_node!(static NODE);
    ///
    /// let mutex = Arc::new(Mutex::new(0));
    /// let c_mutex = Arc::clone(&mutex);
    ///
    /// thread::spawn(move || {
    ///     c_mutex.try_lock_with_local_then(&NODE, |data| {
    ///         if let Some(data) = data {
    ///             *data = 10;
    ///         } else {
    ///             println!("try_lock_with_local_then failed");
    ///         }
    ///     });
    /// })
    /// .join().expect("thread::spawn failed");
    ///
    /// assert_eq!(mutex.lock_with_local_then(&NODE, |data| *data), 10);
    /// ```
    ///
    /// Compile fail: borrows of the data cannot escape the given closure:
    ///
    /// ```compile_fail,E0515
    /// use mcslock::raw::spins::Mutex;
    ///
    /// mcslock::thread_local_node!(static NODE);
    ///
    /// let mutex = Mutex::new(1);
    /// let borrow = mutex.try_lock_with_local_then(&NODE, |data| &*data.unwrap());
    /// ```
    ///
    /// Panic: thread local node cannot be borrowed more than once at the same
    /// time:
    ///
    #[doc = concat!("```should_panic(expected = ", already_borrowed_error!(), ")")]
    /// use mcslock::raw::spins::Mutex;
    ///
    /// mcslock::thread_local_node!(static NODE);
    ///
    /// let mutex = Mutex::new(0);
    ///
    /// mutex.lock_with_local_then(&NODE, |_data| {
    ///     // `NODE` is already mutably borrowed in this thread by the enclosing
    ///     // `lock_with_local_then`, the borrow is live for the full duration
    ///     // of this closure scope.
    ///     let mutex = Mutex::new(());
    ///     mutex.try_lock_with_local_then(&NODE, |_data| ());
    /// });
    /// ```
    #[inline]
    #[track_caller]
    pub fn try_lock_with_local_then<F, Ret>(&self, node: Key, f: F) -> Ret
    where
        F: FnOnce(Option<&mut T>) -> Ret,
    {
        self.inner.try_lock_with_local_then(&node.inner, f)
    }

    /// Attempts to acquire this mutex and then runs a closure against the
    /// protected data.
    ///
    /// If the lock could not be acquired at this time, then a [`None`] value is
    /// given back as the closure argument. If the lock has been acquired, then
    /// a [`Some`] value with the mutex protected data is given instead. The lock
    /// will be unlocked when the closure scope ends.
    ///
    /// To acquire a MCS lock through this function, it's also required a
    /// queue node, which is a record that keeps a link for forming the queue,
    /// to be stored in the current locking thread local storage. See
    /// [`LocalMutexNode`] and [`thread_local_node!`].
    ///
    /// This function does not block.
    ///
    /// # Safety
    ///
    /// Unlike [`try_lock_with_local_then`], this method is unsafe because it does
    /// not check if the current thread local node is already mutably borrowed.
    /// If the current thread local node is already borrowed, calling this
    /// function is undefined behavior.
    ///
    /// # Panics
    ///
    /// Panics if the key currently has its destructor running, and it **may**
    /// panic if the destructor has previously been run for this thread.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    /// use std::thread;
    ///
    /// use mcslock::raw::spins::Mutex;
    ///
    /// mcslock::thread_local_node!(static NODE);
    ///
    /// let mutex = Arc::new(Mutex::new(0));
    /// let c_mutex = Arc::clone(&mutex);
    ///
    /// thread::spawn(move || unsafe {
    ///     c_mutex.try_lock_with_local_then_unchecked(&NODE, |data| {
    ///         if let Some(data) = data {
    ///             *data = 10;
    ///         } else {
    ///             println!("try_lock_with_local_then_unchecked failed");
    ///         }
    ///     });
    /// })
    /// .join().expect("thread::spawn failed");
    ///
    /// assert_eq!(mutex.lock_with_local_then(&NODE, |d| *d), 10);
    /// ```
    ///
    /// Compile fail: borrows of the data cannot escape the given closure:
    ///
    /// ```compile_fail,E0515
    /// use mcslock::raw::spins::Mutex;
    ///
    /// mcslock::thread_local_node!(static NODE);
    ///
    /// let mutex = Mutex::new(1);
    /// let data = unsafe {
    ///     mutex.try_lock_with_local_then_unchecked(&NODE, |g| &*g.unwrap())
    /// };
    /// ```
    ///
    /// Undefined behavior: thread local node cannot be borrowed more than once
    /// at the same time:
    ///
    /// ```no_run
    /// use mcslock::raw::spins::Mutex;
    ///
    /// mcslock::thread_local_node!(static NODE);
    ///
    /// let mutex = Mutex::new(0);
    ///
    /// mutex.lock_with_local_then(&NODE, |_data| unsafe {
    ///     // UB: `NODE` is already mutably borrowed in this thread by the
    ///     // enclosing `lock_with_local_then`, the borrow is live for the full
    ///     // duration of this closure scope.
    ///     let mutex = Mutex::new(());
    ///     mutex.try_lock_with_local_then_unchecked(&NODE, |_data| ());
    /// });
    /// ```
    /// [`try_lock_with_local_then`]: Mutex::try_lock_with_local_then
    #[inline]
    pub unsafe fn try_lock_with_local_then_unchecked<F, Ret>(&self, node: Key, f: F) -> Ret
    where
        F: FnOnce(Option<&mut T>) -> Ret,
    {
        unsafe { self.inner.try_lock_with_local_then_unchecked(&node.inner, f) }
    }

    /// Acquires this mutex and then runs the closure against the protected data.
    ///
    /// This function will block the local thread until it is available to acquire
    /// the mutex. Upon acquiring the mutex, the user provided closure will be
    /// executed against the mutex protected data. Once the closure goes out of
    /// scope, it will unlock the mutex.
    ///
    /// To acquire a MCS lock through this function, it's also required a
    /// queue node, which is a record that keeps a link for forming the queue,
    /// to be stored in the current locking thread local storage. See
    /// [`LocalMutexNode`] and [`thread_local_node!`].
    ///
    /// This function will block if the lock is unavailable.
    ///
    /// # Panics
    ///
    /// Will panic if the thread local node is already mutably borrowed.
    ///
    /// Panics if the key currently has its destructor running, and it **may**
    /// panic if the destructor has previously been run for this thread.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    /// use std::thread;
    ///
    /// use mcslock::raw::spins::Mutex;
    ///
    /// mcslock::thread_local_node!(static NODE);
    ///
    /// let mutex = Arc::new(Mutex::new(0));
    /// let c_mutex = Arc::clone(&mutex);
    ///
    /// thread::spawn(move || {
    ///     c_mutex.lock_with_local_then(&NODE, |data| *data = 10);
    /// })
    /// .join().expect("thread::spawn failed");
    ///
    /// assert_eq!(mutex.lock_with_local_then(&NODE, |data| *data), 10);
    /// ```
    ///
    /// Compile fail: borrows of the data cannot escape the given closure:
    ///
    /// ```compile_fail,E0515
    /// use mcslock::raw::spins::Mutex;
    ///
    /// mcslock::thread_local_node!(static NODE);
    ///
    /// let mutex = Mutex::new(1);
    /// let borrow = mutex.lock_with_local_then(&NODE, |data| &*data);
    /// ```
    ///
    /// Panic: thread local node cannot be borrowed more than once at the same
    /// time:
    ///
    #[doc = concat!("```should_panic(expected = ", already_borrowed_error!(), ")")]
    /// use mcslock::raw::spins::Mutex;
    ///
    /// mcslock::thread_local_node!(static NODE);
    ///
    /// let mutex = Mutex::new(0);
    ///
    /// mutex.lock_with_local_then(&NODE, |_data| {
    ///     // `NODE` is already mutably borrowed in this thread by the
    ///     // enclosing `lock_with_local_then`, the borrow is live for the full
    ///     // duration of this closure scope.
    ///     let mutex = Mutex::new(());
    ///     mutex.lock_with_local_then(&NODE, |_data| ());
    /// });
    /// ```
    #[inline]
    #[track_caller]
    pub fn lock_with_local_then<F, Ret>(&self, node: Key, f: F) -> Ret
    where
        F: FnOnce(&mut T) -> Ret,
    {
        self.inner.lock_with_local_then(&node.inner, f)
    }

    /// Acquires this mutex and then runs the closure against the protected data.
    ///
    /// This function will block the local thread until it is available to acquire
    /// the mutex. Upon acquiring the mutex, the user provided closure will be
    /// executed against the mutex protected data. Once the closure goes out of
    /// scope, it will unlock the mutex.
    ///
    /// To acquire a MCS lock through this function, it's also required a
    /// queue node, which is a record that keeps a link for forming the queue,
    /// to be stored in the current locking thread local storage. See
    /// [`LocalMutexNode`] and [`thread_local_node!`].
    ///
    /// This function will block if the lock is unavailable.
    ///
    /// # Safety
    ///
    /// Unlike [`lock_with_local_then`], this method is unsafe because it does not
    /// check if the current thread local node is already mutably borrowed. If
    /// the current thread local node is already borrowed, calling this
    /// function is undefined behavior.
    ///
    /// # Panics
    ///
    /// Panics if the key currently has its destructor running, and it **may**
    /// panic if the destructor has previously been run for this thread.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    /// use std::thread;
    ///
    /// use mcslock::raw::spins::Mutex;
    ///
    /// mcslock::thread_local_node!(static NODE);
    ///
    /// let mutex = Arc::new(Mutex::new(0));
    /// let c_mutex = Arc::clone(&mutex);
    ///
    /// thread::spawn(move || unsafe {
    ///     c_mutex.lock_with_local_then_unchecked(&NODE, |data| *data = 10);
    /// })
    /// .join().expect("thread::spawn failed");
    ///
    /// assert_eq!(mutex.lock_with_local_then(&NODE, |data| *data), 10);
    /// ```
    ///
    /// Compile fail: borrows of the data cannot escape the given closure:
    ///
    /// ```compile_fail,E0515
    /// use mcslock::raw::spins::Mutex;
    ///
    /// mcslock::thread_local_node!(static NODE);
    ///
    /// let mutex = Mutex::new(1);
    /// let data = unsafe {
    ///     mutex.lock_with_local_then_unchecked(&NODE, |data| &*data)
    /// };
    /// ```
    ///
    /// Undefined behavior: thread local node cannot be borrowed more than once
    /// at the same time:
    ///
    /// ```no_run
    /// use mcslock::raw::spins::Mutex;
    ///
    /// mcslock::thread_local_node!(static NODE);
    ///
    /// let mutex = Mutex::new(0);
    ///
    /// mutex.lock_with_local_then(&NODE, |_data| unsafe {
    ///     // UB: `NODE` is already mutably borrowed in this thread by the
    ///     // enclosing `lock_with_local_then`, the borrow is live for the full
    ///     // duration of this closure scope.
    ///     let mutex = Mutex::new(());
    ///     mutex.lock_with_local_then_unchecked(&NODE, |_data| ());
    /// });
    /// ```
    /// [`lock_with_local_then`]: Mutex::lock_with_local_then
    #[inline]
    pub unsafe fn lock_with_local_then_unchecked<F, Ret>(&self, node: Key, f: F) -> Ret
    where
        F: FnOnce(&mut T) -> Ret,
    {
        unsafe { self.inner.lock_with_local_then_unchecked(&node.inner, f) }
    }

    /// Mutable borrows must not escape the closure.
    ///
    /// ```compile_fail
    /// use mcslock::raw::spins::Mutex;
    /// mcslock::thread_local_node!(static NODE);
    ///
    /// let mutex = Mutex::new(1);
    /// let borrow = mutex.lock_with_local_then(&NODE, |data| data);
    /// ```
    ///
    /// ```compile_fail,E0521
    /// use std::thread;
    /// use mcslock::raw::spins::Mutex;
    /// mcslock::thread_local_node!(static NODE);
    ///
    /// let mutex = Mutex::new(1);
    /// mutex.lock_with_local_then(&NODE, |data| {
    ///     thread::spawn(move || {
    ///         let data = data;
    ///     });
    /// });
    /// ```
    #[cfg(doctest)]
    #[cfg(not(tarpaulin_include))]
    const fn __borrows_must_not_escape_closure() {}
}

// A thread local node definition used for testing.
#[cfg(test)]
#[cfg(not(tarpaulin_include))]
thread_local_node!(static TEST_NODE);

/// A Mutex wrapper type that calls `lock_with_local_then` and
/// `try_lock_with_local_then` when implementing testing traits.
#[cfg(test)]
struct MutexPanic<T: ?Sized, R>(Mutex<T, R>);

#[cfg(test)]
impl<T: ?Sized, R> LockNew for MutexPanic<T, R> {
    type Target = T;

    fn new(value: Self::Target) -> Self
    where
        Self::Target: Sized,
    {
        Self(Mutex::new(value))
    }
}

#[cfg(test)]
impl<T: ?Sized, R: Relax> LockWithThen for MutexPanic<T, R> {
    // A thread local node is transparently accessed instead.
    type Node = ();

    type Guard<'a>
        = &'a mut Self::Target
    where
        Self: 'a,
        Self::Target: 'a;

    fn lock_with_then<F, Ret>(&self, (): &mut Self::Node, f: F) -> Ret
    where
        F: FnOnce(&mut Self::Target) -> Ret,
    {
        self.0.lock_with_local_then(&TEST_NODE, f)
    }
}

#[cfg(test)]
impl<T: ?Sized, R: Relax> TryLockWithThen for MutexPanic<T, R> {
    fn try_lock_with_then<F, Ret>(&self, (): &mut Self::Node, f: F) -> Ret
    where
        F: FnOnce(Option<&mut Self::Target>) -> Ret,
    {
        self.0.try_lock_with_local_then(&TEST_NODE, f)
    }

    fn is_locked(&self) -> bool {
        self.0.is_locked()
    }
}

#[cfg(test)]
impl<T: ?Sized, R: Relax> LockThen for MutexPanic<T, R> {}

#[cfg(test)]
impl<T: ?Sized, R: Relax> TryLockThen for MutexPanic<T, R> {}

/// A Mutex wrapper type that calls `lock_with_local_then_unchecked` and
/// `try_lock_with_local_then_unchecked` when implementing testing traits.
#[cfg(test)]
struct MutexUnchecked<T: ?Sized, R>(Mutex<T, R>);

#[cfg(test)]
impl<T: ?Sized, R> LockNew for MutexUnchecked<T, R> {
    type Target = T;

    fn new(value: Self::Target) -> Self
    where
        Self::Target: Sized,
    {
        Self(Mutex::new(value))
    }
}

#[cfg(test)]
impl<T: ?Sized, R: Relax> LockWithThen for MutexUnchecked<T, R> {
    // A thread local node is transparently accessed instead.
    type Node = ();

    type Guard<'a>
        = &'a mut Self::Target
    where
        Self: 'a,
        Self::Target: 'a;

    fn lock_with_then<F, Ret>(&self, (): &mut Self::Node, f: F) -> Ret
    where
        F: FnOnce(&mut Self::Target) -> Ret,
    {
        // SAFETY: caller must guarantee that this thread local node is not
        // already mutably borrowed for some other lock acquisition.
        unsafe { self.0.lock_with_local_then_unchecked(&TEST_NODE, f) }
    }
}

#[cfg(test)]
impl<T: ?Sized, R: Relax> TryLockWithThen for MutexUnchecked<T, R> {
    fn try_lock_with_then<F, Ret>(&self, (): &mut Self::Node, f: F) -> Ret
    where
        F: FnOnce(Option<&mut Self::Target>) -> Ret,
    {
        // SAFETY: caller must guarantee that this thread local node is not
        // already mutably borrowed for some other lock acquisition.
        unsafe { self.0.try_lock_with_local_then_unchecked(&TEST_NODE, f) }
    }

    fn is_locked(&self) -> bool {
        self.0.is_locked()
    }
}

#[cfg(test)]
impl<T: ?Sized, R: Relax> LockThen for MutexUnchecked<T, R> {}

#[cfg(test)]
impl<T: ?Sized, R: Relax> TryLockThen for MutexUnchecked<T, R> {}

#[cfg(all(not(loom), test))]
mod test {
    use crate::raw::MutexNode;
    use crate::relax::Yield;
    use crate::test::tests;

    type MutexPanic<T> = super::MutexPanic<T, Yield>;
    type MutexUnchecked<T> = super::MutexUnchecked<T, Yield>;

    #[test]
    fn ref_cell_node_drop_does_not_matter() {
        use core::{cell::RefCell, mem};
        assert!(!mem::needs_drop::<RefCell<MutexNode>>());
    }

    #[test]
    fn lots_and_lots_lock() {
        tests::lots_and_lots_lock::<MutexPanic<_>>();
    }

    #[test]
    fn lots_and_lots_lock_unchecked() {
        tests::lots_and_lots_lock::<MutexUnchecked<_>>();
    }

    #[test]
    fn lots_and_lots_try_lock() {
        tests::lots_and_lots_try_lock::<MutexPanic<_>>();
    }

    #[test]
    fn lots_and_lots_try_lock_unchecked() {
        tests::lots_and_lots_try_lock::<MutexUnchecked<_>>();
    }

    #[test]
    fn lots_and_lots_mixed_lock() {
        tests::lots_and_lots_mixed_lock::<MutexPanic<_>>();
    }

    #[test]
    fn lots_and_lots_mixed_lock_unchecked() {
        tests::lots_and_lots_mixed_lock::<MutexUnchecked<_>>();
    }

    #[test]
    fn smoke() {
        tests::smoke::<MutexPanic<_>>();
    }

    #[test]
    fn smoke_unchecked() {
        tests::smoke::<MutexUnchecked<_>>();
    }

    #[test]
    fn test_try_lock() {
        tests::test_try_lock::<MutexPanic<_>>();
    }

    #[test]
    fn test_try_lock_unchecked() {
        tests::test_try_lock::<MutexUnchecked<_>>();
    }

    #[test]
    #[should_panic = already_borrowed_error!()]
    fn test_lock_arc_nested() {
        tests::test_lock_arc_nested::<MutexPanic<_>, MutexPanic<_>>();
    }

    #[test]
    #[should_panic = already_borrowed_error!()]
    fn test_acquire_more_than_one_lock() {
        tests::test_acquire_more_than_one_lock::<MutexPanic<_>>();
    }

    #[test]
    fn test_lock_arc_access_in_unwind() {
        tests::test_lock_arc_access_in_unwind::<MutexPanic<_>>();
    }

    #[test]
    fn test_lock_arc_access_in_unwind_unchecked() {
        tests::test_lock_arc_access_in_unwind::<MutexUnchecked<_>>();
    }

    #[test]
    fn test_lock_unsized() {
        tests::test_lock_unsized::<MutexPanic<_>>();
    }

    #[test]
    fn test_lock_unsized_unchecked() {
        tests::test_lock_unsized::<MutexUnchecked<_>>();
    }
}

#[cfg(all(loom, test))]
mod model {
    use crate::loom::models;
    use crate::relax::Yield;

    type MutexPanic<T> = super::MutexPanic<T, Yield>;
    type MutexUnchecked<T> = super::MutexUnchecked<T, Yield>;

    #[test]
    fn try_lock_join() {
        models::try_lock_join::<MutexPanic<_>>();
    }

    #[test]
    fn try_lock_join_unchecked() {
        models::try_lock_join::<MutexUnchecked<_>>();
    }

    #[test]
    fn lock_join() {
        models::lock_join::<MutexPanic<_>>();
    }

    #[test]
    fn lock_join_unchecked() {
        models::lock_join::<MutexUnchecked<_>>();
    }

    #[test]
    fn mixed_lock_join() {
        models::mixed_lock_join::<MutexPanic<_>>();
    }

    #[test]
    fn mixed_lock_join_unchecked() {
        models::mixed_lock_join::<MutexUnchecked<_>>();
    }
}