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
use core::{cell::Cell, debug_assert_eq, fmt};

use super::{Lock, NoSendMarker};

/// A single-thread implementation of [`Lock`]. Panics on borrow failure.
pub struct LocalLock {
    count: Cell<usize>,
}

const EXCLUSIVE: usize = usize::max_value();

impl fmt::Debug for LocalLock {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.count.get() == EXCLUSIVE {
            write!(f, "LocalLock {{ <locked exclusively> }}")
        } else {
            write!(f, "LocalLock {{ num_shared_locks: {} }}", self.count.get())
        }
    }
}

unsafe impl Lock for LocalLock {
    #[inline]
    fn new() -> Self {
        Self {
            count: Cell::new(0),
        }
    }

    type LockMarker = NoSendMarker;
    type UnlockMarker = NoSendMarker;

    #[inline]
    unsafe fn lock_shared(&self) {
        let count = &self.count;
        if count.get() >= EXCLUSIVE - 1 {
            // Exclusively borrowed or counter overflow. Ignore the latter case
            // because it's a quite degenerate behavior.
            borrow_fail();
        } else {
            count.set(count.get() + 1);
        }
    }

    #[inline]
    unsafe fn try_lock_shared(&self) -> bool {
        let count = &self.count;
        if count.get() >= EXCLUSIVE - 1 {
            false
        } else {
            count.set(count.get() + 1);
            true
        }
    }

    #[inline]
    unsafe fn unlock_shared(&self) {
        debug_assert_ne!(self.count.get(), 0);
        debug_assert_ne!(self.count.get(), EXCLUSIVE);
        self.count.set(self.count.get() - 1);
    }

    #[inline]
    unsafe fn lock_exclusive(&self) {
        let count = &self.count;
        if count.get() != 0 {
            borrow_fail();
        } else {
            count.set(EXCLUSIVE);
        }
    }

    #[inline]
    unsafe fn try_lock_exclusive(&self) -> bool {
        let count = &self.count;
        if count.get() != 0 {
            false
        } else {
            count.set(EXCLUSIVE);
            true
        }
    }

    #[inline]
    unsafe fn unlock_exclusive(&self) {
        debug_assert_eq!(self.count.get(), EXCLUSIVE);
        self.count.set(0);
    }
}

#[cold]
fn borrow_fail() -> ! {
    panic!("deadlock")
}