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
//! Contains code relating to returned reference types and their internal state.
//!
//! Default implementation returns [`ContiguousMemoryRef`] when items are
//! stored which can be easily accessed through [`CMRef`] alias.
//!
//! Concurrent implementation returns [`SyncContiguousMemoryRef`] when items are
//! stored which can be easily accessed through [`SCMRef`] alias.

use core::{
    marker::PhantomData,
    ops::{Deref, DerefMut},
};

use crate::{
    details::{ImplConcurrent, ImplDefault, ImplDetails, StorageDetails},
    error::{LockSource, LockingError, RegionBorrowed},
    range::ByteRange,
    types::*,
};

/// Trait specifying interface of returned reference types.
pub trait ContiguousMemoryReference<T: ?Sized, Impl: ImplDetails> {
    /// Error type returned when the data represented by the reference can't be
    /// safely accessed/borrowed.
    type BorrowError;

    /// Returns a byte range within container memory this reference points to.
    fn range(&self) -> ByteRange;

    /// Returns a reference to data at its current location and panics if the
    /// reference has been mutably borrowed or blocks the thread for the
    /// concurrent implementation.
    fn get<'a>(&'a self) -> Impl::LockResult<MemoryReadGuard<'a, T, Impl>>
    where
        T: RefSizeReq;

    /// Returns a reference to data at its current location and returns the
    /// appropriate [error](Self::BorrowError) if that's not possible.
    fn try_get<'a>(&'a self) -> Result<MemoryReadGuard<'a, T, Impl>, Self::BorrowError>
    where
        T: RefSizeReq;

    /// Returns a mutable reference to data at its current location and panics
    /// if the reference has been mutably borrowed or blocks the thread for
    /// concurrent implementation.
    fn get_mut<'a>(&'a mut self) -> Impl::LockResult<MemoryWriteGuard<'a, T, Impl>>
    where
        T: RefSizeReq;

    /// Returns a mutable reference to data at its current location or an error
    /// [error](Self::BorrowError) if the represented memory region is already
    /// mutably borrowed.
    fn try_get_mut<'a>(&'a mut self) -> Result<MemoryWriteGuard<'a, T, Impl>, Self::BorrowError>
    where
        T: RefSizeReq;

    /// Casts this reference into a dynamic type `R`.
    #[cfg(feature = "ptr_metadata")]
    fn into_dyn<R: ?Sized>(self) -> Impl::ReferenceType<R>
    where
        T: Sized + Unsize<R>;
}

/// A synchronized (thread-safe) reference to `T` data stored in a
/// [`ContiguousMemoryStorage`](crate::ContiguousMemoryStorage) structure.
pub struct SyncContiguousMemoryRef<T: ?Sized> {
    pub(crate) inner: Arc<ReferenceState<T, ImplConcurrent>>,
    #[cfg(feature = "ptr_metadata")]
    pub(crate) metadata: <T as Pointee>::Metadata,
    #[cfg(not(feature = "ptr_metadata"))]
    pub(crate) _phantom: PhantomData<T>,
}

/// A shorter type name for [`SyncContiguousMemoryRef`].
pub type SCMRef<T> = SyncContiguousMemoryRef<T>;

impl<T: ?Sized> ContiguousMemoryReference<T, ImplConcurrent> for SyncContiguousMemoryRef<T> {
    type BorrowError = LockingError;

    fn range(&self) -> ByteRange {
        self.inner.range
    }

    /// Returns a reference to data at its current location or returns a
    /// [`LockingError::Poisoned`](crate::error::LockingError::Poisoned) error
    /// if the Mutex holding the `base` address pointer has been poisoned.
    ///
    /// If the data is mutably accessed, this method will block the current
    /// thread until it becomes available.
    fn get<'a>(&'a self) -> Result<MemoryReadGuard<'a, T, ImplConcurrent>, LockingError>
    where
        T: RefSizeReq,
    {
        let guard = self.inner.borrow_kind.read_named(LockSource::Reference)?;

        unsafe {
            let base = ImplConcurrent::get_base(&self.inner.state.base)?;
            let pos = base.add(self.inner.range.0);

            Ok(MemoryReadGuard {
                state: self.inner.clone(),
                guard,
                #[cfg(not(feature = "ptr_metadata"))]
                value: &*(pos as *mut T),
                #[cfg(feature = "ptr_metadata")]
                value: &*core::ptr::from_raw_parts(pos as *const (), self.metadata),
            })
        }
    }

    /// Returns a reference to data at its current location or returns a
    /// [`LockingError::Poisoned`](crate::error::LockingError::Poisoned) error
    /// if the Mutex holding the `base` address pointer has been poisoned.
    ///
    /// If the data is mutably accessed, this method return a
    /// [`LockingError::WouldBlock`](crate::error::LockingError::WouldBlock)
    /// error.
    fn try_get<'a>(&'a self) -> Result<MemoryReadGuard<'a, T, ImplConcurrent>, LockingError>
    where
        T: RefSizeReq,
    {
        let guard = self
            .inner
            .borrow_kind
            .try_read_named(LockSource::Reference)?;

        unsafe {
            let base = ImplConcurrent::get_base(&self.inner.state.base)?;
            let pos = base.add(self.inner.range.0);

            Ok(MemoryReadGuard {
                state: self.inner.clone(),
                guard,
                #[cfg(not(feature = "ptr_metadata"))]
                value: &*(pos as *mut T),
                #[cfg(feature = "ptr_metadata")]
                value: &*core::ptr::from_raw_parts(pos as *const (), self.metadata),
            })
        }
    }

    /// Returns or write guard to referenced data at its current location a
    /// [`LockingError::Poisoned`] error if the Mutex holding the base address
    /// pointer or the Mutex holding concurrent mutable access flag has been
    /// poisoned.
    fn get_mut<'a>(&'a mut self) -> Result<MemoryWriteGuard<'a, T, ImplConcurrent>, LockingError>
    where
        T: RefSizeReq,
    {
        let guard = self.inner.borrow_kind.write_named(LockSource::Reference)?;
        unsafe {
            let base = ImplConcurrent::get_base(&self.inner.state.base)?;
            let pos = base.add(self.inner.range.0);
            Ok(MemoryWriteGuard {
                state: self.inner.clone(),
                guard,
                #[cfg(not(feature = "ptr_metadata"))]
                value: &mut *(pos as *mut T),
                #[cfg(feature = "ptr_metadata")]
                value: &mut *core::ptr::from_raw_parts_mut::<T>(pos as *mut (), self.metadata),
            })
        }
    }

    /// Returns a write guard to referenced data at its current location or a
    /// `LockingError` if that isn't possible.
    ///
    /// This function can return the following errors:
    ///
    /// - [`LockingError::Poisoned`] error if the Mutex holding the base address
    ///   pointer or the Mutex holding mutable access exclusion flag has been
    ///   poisoned.
    ///
    /// - [`LockingError::WouldBlock`] error if accessing referenced data chunk
    ///   would be blocking.
    fn try_get_mut<'a>(
        &'a mut self,
    ) -> Result<MemoryWriteGuard<'a, T, ImplConcurrent>, LockingError>
    where
        T: RefSizeReq,
    {
        let guard = self
            .inner
            .borrow_kind
            .try_write_named(LockSource::Reference)?;
        unsafe {
            let base = ImplConcurrent::get_base(&self.inner.state.base)?;
            let pos = base.add(self.inner.range.0);
            Ok(MemoryWriteGuard {
                state: self.inner.clone(),
                guard,
                #[cfg(not(feature = "ptr_metadata"))]
                value: &mut *(pos as *mut T),
                #[cfg(feature = "ptr_metadata")]
                value: &mut *core::ptr::from_raw_parts_mut::<T>(pos as *mut (), self.metadata),
            })
        }
    }

    #[cfg(feature = "ptr_metadata")]
    fn into_dyn<R: ?Sized>(self) -> SyncContiguousMemoryRef<R>
    where
        T: Sized + Unsize<R>,
    {
        unsafe {
            SyncContiguousMemoryRef {
                inner: core::mem::transmute(self.inner),
                metadata: static_metadata::<T, R>(),
            }
        }
    }
}

impl<T: ?Sized> Clone for SyncContiguousMemoryRef<T> {
    fn clone(&self) -> Self {
        SyncContiguousMemoryRef {
            inner: self.inner.clone(),
            #[cfg(feature = "ptr_metadata")]
            metadata: self.metadata.clone(),
            #[cfg(not(feature = "ptr_metadata"))]
            _phantom: PhantomData,
        }
    }
}

#[cfg(feature = "debug")]
impl<T: ?Sized> core::fmt::Debug for SyncContiguousMemoryRef<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("SyncContiguousMemoryRef")
            .field("inner", &self.inner)
            .finish()
    }
}

/// A thread-unsafe reference to `T` data stored in
/// [`ContiguousMemoryStorage`](crate::ContiguousMemoryStorage) structure.
pub struct ContiguousMemoryRef<T: ?Sized> {
    pub(crate) inner: Rc<ReferenceState<T, ImplDefault>>,
    #[cfg(feature = "ptr_metadata")]
    pub(crate) metadata: <T as Pointee>::Metadata,
    #[cfg(not(feature = "ptr_metadata"))]
    pub(crate) _phantom: PhantomData<T>,
}
/// A shorter type name for [`ContiguousMemoryRef`].
pub type CMRef<T> = ContiguousMemoryRef<T>;

impl<T: ?Sized> ContiguousMemoryReference<T, ImplDefault> for ContiguousMemoryRef<T> {
    type BorrowError = RegionBorrowed;

    fn range(&self) -> ByteRange {
        self.inner.range
    }

    fn get<'a>(&'a self) -> MemoryReadGuard<'a, T, ImplDefault>
    where
        T: RefSizeReq,
    {
        ContiguousMemoryRef::<T>::try_get(self).expect("mutably borrowed")
    }

    fn try_get<'a>(&'a self) -> Result<MemoryReadGuard<'a, T, ImplDefault>, RegionBorrowed>
    where
        T: RefSizeReq,
    {
        let state = self.inner.borrow_kind.get();
        if let BorrowState::Read(count) = state {
            self.inner.borrow_kind.set(BorrowState::Read(count + 1));
        } else {
            return Err(RegionBorrowed {
                range: self.inner.range,
            });
        }

        unsafe {
            let base = ImplDefault::get_base(&self.inner.state.base);
            let pos = base.add(self.inner.range.0);

            Ok(MemoryReadGuard {
                state: self.inner.clone(),
                guard: (),
                #[cfg(not(feature = "ptr_metadata"))]
                value: &*(pos as *mut T),
                #[cfg(feature = "ptr_metadata")]
                value: &*core::ptr::from_raw_parts_mut::<T>(pos as *mut (), self.metadata),
            })
        }
    }

    fn get_mut<'a>(&'a mut self) -> MemoryWriteGuard<'a, T, ImplDefault>
    where
        T: RefSizeReq,
    {
        ContiguousMemoryRef::<T>::try_get_mut(self).expect("mutably borrowed")
    }

    /// This implementation returns a [`RegionBorrowed`] error if the
    /// represented memory region is already borrowed.
    fn try_get_mut<'a>(&'a mut self) -> Result<MemoryWriteGuard<'a, T, ImplDefault>, RegionBorrowed>
    where
        T: RefSizeReq,
    {
        if self.inner.borrow_kind.get() != BorrowState::Read(0) {
            return Err(RegionBorrowed {
                range: self.inner.range,
            });
        } else {
            self.inner.borrow_kind.set(BorrowState::Write);
        }

        unsafe {
            let base = ImplDefault::get_base(&self.inner.state.base);
            let pos = base.add(self.inner.range.0);

            Ok(MemoryWriteGuard {
                state: self.inner.clone(),
                guard: (),
                #[cfg(not(feature = "ptr_metadata"))]
                value: &mut *(pos as *mut T),
                #[cfg(feature = "ptr_metadata")]
                value: &mut *core::ptr::from_raw_parts_mut::<T>(pos as *mut (), self.metadata),
            })
        }
    }

    #[cfg(feature = "ptr_metadata")]
    fn into_dyn<R: ?Sized>(self) -> ContiguousMemoryRef<R>
    where
        T: Sized + Unsize<R>,
    {
        unsafe {
            ContiguousMemoryRef {
                inner: core::mem::transmute(self.inner),
                metadata: static_metadata::<T, R>(),
            }
        }
    }
}

impl<T: ?Sized> Clone for ContiguousMemoryRef<T> {
    fn clone(&self) -> Self {
        ContiguousMemoryRef {
            inner: self.inner.clone(),
            #[cfg(feature = "ptr_metadata")]
            metadata: self.metadata.clone(),
            #[cfg(not(feature = "ptr_metadata"))]
            _phantom: PhantomData,
        }
    }
}

#[cfg(feature = "debug")]
impl<T: ?Sized> core::fmt::Debug for ContiguousMemoryRef<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("ContiguousMemoryRef")
            .field("inner", &self.inner)
            .finish()
    }
}

pub(crate) mod sealed {
    use super::*;

    /// Internal state of [`ContiguousMemoryRef`] and [`SyncContiguousMemoryRef`].
    pub struct ReferenceState<T: ?Sized, Impl: ImplDetails> {
        pub state: Impl::StorageState,
        pub range: ByteRange,
        pub borrow_kind: Impl::BorrowLock,
        #[cfg(feature = "ptr_metadata")]
        pub drop_metadata: DynMetadata<dyn HandleDrop>,
        pub _phantom: PhantomData<T>,
    }

    #[cfg(feature = "debug")]
    impl<T: ?Sized, Impl: ImplDetails> core::fmt::Debug for ReferenceState<T, Impl>
    where
        Impl::StorageState: core::fmt::Debug,
        Impl::BorrowLock: core::fmt::Debug,
    {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            f.debug_struct("ReferenceState")
                .field("state", &self.state)
                .field("range", &self.range)
                .field("borrow_kind", &self.borrow_kind)
                .finish()
        }
    }

    impl<T: ?Sized, Impl: ImplDetails> Drop for ReferenceState<T, Impl> {
        fn drop(&mut self) {
            #[allow(unused_variables)]
            if let Some(it) = Impl::free_region(&mut self.state, self.range) {
                #[cfg(feature = "ptr_metadata")]
                unsafe {
                    let drop: *mut dyn HandleDrop =
                        core::ptr::from_raw_parts_mut::<dyn HandleDrop>(it, self.drop_metadata);
                    (&*drop).do_drop();
                }
            };
        }
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum BorrowKind {
        Read,
        Write,
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum BorrowState {
        Read(usize),
        Write,
    }
}
use sealed::*;

/// A smart reference wrapper responsible for tracking and managing a flag
/// that indicates whether the memory segment is actively being written to.
#[cfg_attr(feature = "debug", derive(Debug))]
pub struct MemoryWriteGuard<'a, T: ?Sized, Impl: ImplDetails> {
    state: Impl::RefState<T>,
    #[allow(unused)]
    guard: Impl::WriteGuard<'a>,
    value: &'a mut T,
}

impl<'a, T: ?Sized, Impl: ImplDetails> Deref for MemoryWriteGuard<'a, T, Impl> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.value
    }
}

impl<'a, T: ?Sized, Impl: ImplDetails> DerefMut for MemoryWriteGuard<'a, T, Impl> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.value
    }
}

impl<'a, T: ?Sized, Impl: ImplDetails> Drop for MemoryWriteGuard<'a, T, Impl> {
    fn drop(&mut self) {
        Impl::unborrow_ref::<T>(&self.state, BorrowKind::Write);
    }
}

/// A smart reference wrapper responsible for tracking and managing a flag
/// that indicates whether the memory segment is actively being read from.
#[cfg_attr(feature = "debug", derive(Debug))]
pub struct MemoryReadGuard<'a, T: ?Sized, Impl: ImplDetails> {
    state: Impl::RefState<T>,
    #[allow(unused)]
    guard: Impl::ReadGuard<'a>,
    value: &'a T,
}

impl<'a, T: ?Sized, Impl: ImplDetails> Deref for MemoryReadGuard<'a, T, Impl> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.value
    }
}

impl<'a, T: ?Sized, Impl: ImplDetails> Drop for MemoryReadGuard<'a, T, Impl> {
    fn drop(&mut self) {
        Impl::unborrow_ref::<T>(&self.state, BorrowKind::Read);
    }
}