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
#[cfg(not(feature = "std"))]
extern crate alloc;

#[cfg(feature = "std")]
extern crate core;

use core::{
    cell::Cell,
    fmt::Debug,
    marker::PhantomData,
    ops::{
        Deref,
        DerefMut,
    },
    ptr::NonNull,
};

/// The state of a borrowed element.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum BorrowState {
    /// The element is not borrowed.
    #[default]
    NotBorrowed,
    /// The element is borrowed with N readers.
    Reading(usize),
    /// The element is borrowed for writing.
    Writing,
}

impl BorrowState {
    #[inline]
    fn add_reader(self) -> Option<Self> {
        match self {
            Self::NotBorrowed => Some(Self::Reading(1)),
            Self::Reading(n) => Some(Self::Reading(n + 1)),
            Self::Writing => None,
        }
    }

    #[inline]
    fn add_reader_unchecked(self) -> Self {
        match self {
            Self::Reading(n) => Self::Reading(n + 1),
            _ => unreachable!(),
        }
    }

    #[inline]
    fn drop_reader(self) -> Self {
        match self {
            Self::Reading(n) if n > 1 => Self::Reading(n - 1),
            _ => Self::NotBorrowed,
        }
    }

    #[inline]
    fn add_writer(self) -> Option<Self> {
        match self {
            Self::NotBorrowed => Some(Self::Writing),
            _ => None,
        }
    }
}

/// A borrow reference, which is a shared reference to an element's borrow state.
#[derive(Debug)]
pub(crate) struct BorrowRef<'borrow> {
    state: &'borrow Cell<BorrowState>,
}

impl<'borrow> BorrowRef<'borrow> {
    pub fn new(state: &'borrow Cell<BorrowState>) -> Option<Self> {
        state.set(state.get().add_reader()?);
        Some(Self { state })
    }
}

impl Clone for BorrowRef<'_> {
    fn clone(&self) -> Self {
        self.state.set(self.state.get().add_reader_unchecked());
        Self { state: self.state }
    }
}

#[cfg(feature = "may-dangle")]
unsafe impl<#[may_dangle] 'borrow> Drop for BorrowRef<'borrow> {
    #[inline]
    fn drop(&mut self) {
        self.state.set(self.state.get().drop_reader());
    }
}

#[cfg(not(feature = "may-dangle"))]
impl Drop for BorrowRef<'_> {
    #[inline]
    fn drop(&mut self) {
        self.state.set(self.state.get().drop_reader());
    }
}

/// A mutable borrow reference, which is a reference to an element's borrow state.
#[derive(Debug)]
pub(crate) struct BorrowRefMut<'borrow> {
    state: &'borrow Cell<BorrowState>,
}

impl<'borrow> BorrowRefMut<'borrow> {
    pub fn new(state: &'borrow Cell<BorrowState>) -> Option<Self> {
        state.set(state.get().add_writer()?);
        Some(Self { state })
    }
}

#[cfg(feature = "may-dangle")]
unsafe impl<#[may_dangle] 'borrow> Drop for BorrowRefMut<'borrow> {
    #[inline]
    fn drop(&mut self) {
        self.state.set(BorrowState::NotBorrowed);
    }
}

#[cfg(not(feature = "may-dangle"))]
impl Drop for BorrowRefMut<'_> {
    #[inline]
    fn drop(&mut self) {
        self.state.set(BorrowState::NotBorrowed);
    }
}

/// An immutably borrowed element.
#[derive(Clone)]
pub struct ElementRef<'borrow, T> {
    value: NonNull<T>,
    #[allow(unused)]
    borrow_ref: BorrowRef<'borrow>,
}

impl<'borrow, T> ElementRef<'borrow, T>
where
    T: 'borrow,
{
    /// Creates a new immutable borrow.
    pub(crate) fn new(value: NonNull<T>, borrow_ref: BorrowRef<'borrow>) -> Self {
        Self { value, borrow_ref }
    }
}

impl<T> Deref for ElementRef<'_, T> {
    type Target = T;
    #[inline]
    fn deref(&self) -> &Self::Target {
        unsafe { self.value.as_ref() }
    }
}

impl<'borrow, T> AsRef<T> for ElementRef<'borrow, T> {
    #[inline]
    fn as_ref(&self) -> &T {
        self.deref()
    }
}

impl<T> Debug for ElementRef<'_, T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{:?}", self.deref())
    }
}

/// A mutably borrowed element.
pub struct ElementRefMut<'borrow, T> {
    value: NonNull<T>,
    #[allow(unused)]
    borrow_ref: BorrowRefMut<'borrow>,
    phantom: PhantomData<&'borrow mut T>,
}

impl<'borrow, T> ElementRefMut<'borrow, T>
where
    T: 'borrow,
{
    /// Creates a new mutable borrow.
    pub(crate) fn new(value: NonNull<T>, borrow_ref: BorrowRefMut<'borrow>) -> Self {
        Self {
            value,
            borrow_ref,
            phantom: PhantomData,
        }
    }
}

impl<'borrow, T> Deref for ElementRefMut<'borrow, T> {
    type Target = T;
    #[inline]
    fn deref(&self) -> &'borrow Self::Target {
        unsafe { self.value.as_ref() }
    }
}

impl<'borrow, T> DerefMut for ElementRefMut<'borrow, T> {
    #[inline]
    fn deref_mut(&mut self) -> &'borrow mut Self::Target {
        unsafe { self.value.as_mut() }
    }
}

impl<'borrow, T> AsRef<T> for ElementRefMut<'borrow, T> {
    #[inline]
    fn as_ref(&self) -> &T {
        self.deref()
    }
}

impl<'borrow, T> AsMut<T> for ElementRefMut<'borrow, T> {
    #[inline]
    fn as_mut(&mut self) -> &mut T {
        self.deref_mut()
    }
}

impl<T> Debug for ElementRefMut<'_, T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{:?}", self.deref())
    }
}