contiguous-mem 0.4.2

A contiguous memory storage
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
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
//! Implementation details for behavior specialization marker structs.
//!
//! End-users aren't meant to interact with traits defined in this module
//! directly and they exist solely to simplify implementation of
//! [`ContiguousMemoryStorage`](ContiguousMemoryStorage) by erasing
//! type details of different implementations.
//!
//! Any changes to these traits aren't considered a breaking change and won't
//! be reflected in version numbers.

use core::{
    alloc::{Layout, LayoutError},
    cell::{Cell, RefCell, RefMut},
    mem::size_of,
    ptr::null_mut,
};

use core::marker::PhantomData;

#[cfg(feature = "no_std")]
use portable_atomic::{AtomicUsize, Ordering};
#[cfg(not(feature = "no_std"))]
use std::sync::atomic::{AtomicUsize, Ordering};

use crate::{
    error::{ContiguousMemoryError, LockSource, LockingError},
    range::ByteRange,
    refs::{sealed::*, ContiguousEntryRef, SyncContiguousEntryRef},
    tracker::AllocationTracker,
    types::*,
    BaseLocation, ContiguousMemoryState,
};

/// Implementation details shared between [storage](StorageDetails) and
/// [`reference`](ReferenceDetails) implementations.
pub trait ImplBase: Sized {
    /// The type representing reference to internal state
    type StorageState: Clone;

    /// The type of reference returned by store operations.
    type ReferenceType<T: ?Sized>: Clone;

    /// The type representing result of accessing data that is locked in async
    /// context
    type LockResult<T>;

    /// The type representing the allocation tracker reference type.
    type ATGuard<'a>;

    /// Indicates whether locks are used for synchronization, allowing the
    /// compiler to easily optimize away branches involving them.
    const USES_LOCKS: bool = false;
}

/// Implementation that's not thread-safe but performs faster as it avoids
/// mutexes and locks.
///
/// For example usage of default implementation see: [`ContiguousMemory`](crate::ContiguousMemory)
#[cfg_attr(feature = "debug", derive(Debug))]
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct ImplDefault;
impl ImplBase for ImplDefault {
    type StorageState = Rc<ContiguousMemoryState<Self>>;
    type ReferenceType<T: ?Sized> = ContiguousEntryRef<T>;
    type LockResult<T> = T;
    type ATGuard<'a> = RefMut<'a, AllocationTracker>;
}

/// Thread-safe implementation utilizing mutexes and locks to prevent data
/// races.
///
/// For example usage of default implementation see:
/// [`SyncContiguousMemory`](crate::SyncContiguousMemory)
#[cfg_attr(feature = "debug", derive(Debug))]
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct ImplConcurrent;
impl ImplBase for ImplConcurrent {
    type StorageState = Arc<ContiguousMemoryState<Self>>;
    type ReferenceType<T: ?Sized> = SyncContiguousEntryRef<T>;
    type LockResult<T> = Result<T, LockingError>;
    type ATGuard<'a> = MutexGuard<'a, AllocationTracker>;

    const USES_LOCKS: bool = true;
}

/// Implementation which provides direct (unsafe) access to stored entries.
///
/// For example usage of default implementation see:
/// [`UnsafeContiguousMemory`](crate::UnsafeContiguousMemory)
#[cfg_attr(feature = "debug", derive(Debug))]
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct ImplUnsafe;
impl ImplBase for ImplUnsafe {
    type StorageState = ContiguousMemoryState<Self>;
    type ReferenceType<T: ?Sized> = *mut T;
    type LockResult<T> = T;
    type ATGuard<'a> = &'a mut AllocationTracker;
}

/// Implementation details of
/// [`ContiguousMemoryStorage`](ContiguousMemoryStorage).
pub trait StorageDetails: ImplBase {
    /// The type representing the base memory and allocation tracking.
    type Base;

    /// The type representing the allocation tracker discrete type.
    type AllocationTracker;

    /// The type representing [`Layout`] entries with inner mutability.
    type SizeType;

    /// The type representing result of storing data.
    type PushResult<T>;

    /// Builds a new internal state from provided parameters
    fn build_state(
        base: *mut u8,
        capacity: usize,
        alignment: usize,
    ) -> Result<Self::StorageState, LayoutError>;

    /// Dereferences the inner state smart pointer and returns it by reference.
    fn deref_state(state: &Self::StorageState) -> &ContiguousMemoryState<Self>;

    /// Retrieves the base pointer from the base instance.
    fn get_base(base: &Self::Base) -> Self::LockResult<*mut u8>;

    /// Retrieves the base pointer from the base instance. Non blocking version.
    fn try_get_base(base: &Self::Base) -> Self::LockResult<*mut u8>;

    /// Retrieves the capacity from the state.
    fn get_capacity(capacity: &Self::SizeType) -> usize;

    /// Returns a writable reference to AllocationTracker.
    fn get_allocation_tracker<'a>(
        state: &'a mut Self::StorageState,
    ) -> Self::LockResult<Self::ATGuard<'a>>;

    /// Resizes and reallocates the base memory according to new capacity.
    fn resize_container(
        state: &mut Self::StorageState,
        new_capacity: usize,
    ) -> Result<Option<*mut u8>, ContiguousMemoryError>;

    /// Deallocates the base memory using layout information.
    fn deallocate(base: &mut Self::Base, layout: Layout);

    /// Resizes the allocation tracker to the new capacity.
    fn resize_tracker(
        state: &mut Self::StorageState,
        new_capacity: usize,
    ) -> Result<(), ContiguousMemoryError>;

    /// Shrinks tracked area of the allocation tracker to smallest that can fit
    /// currently stored data.
    fn shrink_tracker(state: &mut Self::StorageState) -> Self::LockResult<Option<usize>>;

    /// Finds the next free memory region for given layout in the tracker.
    fn track_next(
        state: &mut Self::StorageState,
        layout: Layout,
    ) -> Result<ByteRange, ContiguousMemoryError>;

    /// Returns whether a given layout can be stored or returns an error if
    /// [`AllocationTracker`] can't be stored.
    fn peek_next(state: &Self::StorageState, layout: Layout)
        -> Self::LockResult<Option<ByteRange>>;
}

impl StorageDetails for ImplConcurrent {
    type Base = RwLock<*mut u8>;
    type AllocationTracker = Mutex<AllocationTracker>;
    type SizeType = AtomicUsize;
    type PushResult<T> = Result<Self::ReferenceType<T>, LockingError>;

    fn build_state(
        base: *mut u8,
        capacity: usize,
        alignment: usize,
    ) -> Result<Self::StorageState, LayoutError> {
        let layout = Layout::from_size_align(capacity, alignment)?;

        Ok(Arc::new(ContiguousMemoryState {
            base: BaseLocation(RwLock::new(base)),
            capacity: AtomicUsize::new(layout.size()),
            alignment: layout.align(),
            tracker: Mutex::new(AllocationTracker::new(capacity)),
        }))
    }

    #[inline]
    fn deref_state(state: &Self::StorageState) -> &ContiguousMemoryState<Self> {
        state
    }

    #[inline]
    fn get_base(base: &Self::Base) -> Self::LockResult<*mut u8> {
        base.read_named(LockSource::BaseAddress)
            .map(|result| *result)
    }

    #[inline]
    fn try_get_base(base: &Self::Base) -> Self::LockResult<*mut u8> {
        base.try_read_named(LockSource::BaseAddress)
            .map(|result| *result)
    }

    #[inline]
    fn get_capacity(capacity: &Self::SizeType) -> usize {
        capacity.load(Ordering::Acquire)
    }

    #[inline]
    fn get_allocation_tracker<'a>(
        state: &'a mut Self::StorageState,
    ) -> Self::LockResult<Self::ATGuard<'a>> {
        state.tracker.lock_named(LockSource::AllocationTracker)
    }

    fn resize_container(
        state: &mut Self::StorageState,
        new_capacity: usize,
    ) -> Result<Option<*mut u8>, ContiguousMemoryError> {
        let layout =
            Layout::from_size_align(state.capacity.load(Ordering::Acquire), state.alignment)?;
        let mut base_addr = state.base.write_named(LockSource::BaseAddress)?;
        let prev_addr = *base_addr;
        *base_addr = unsafe { allocator::realloc(*base_addr, layout, new_capacity) };
        state.capacity.store(new_capacity, Ordering::Release);
        Ok(if *base_addr != prev_addr {
            Some(*base_addr)
        } else {
            None
        })
    }

    #[inline]
    fn deallocate(base: &mut Self::Base, layout: Layout) {
        if let Ok(mut lock) = base.write_named(LockSource::BaseAddress) {
            unsafe { allocator::dealloc(*lock, layout) };
            *lock = null_mut();
        }
    }

    #[inline]
    fn resize_tracker(
        state: &mut Self::StorageState,
        new_capacity: usize,
    ) -> Result<(), ContiguousMemoryError> {
        let mut lock = state.tracker.lock_named(LockSource::AllocationTracker)?;
        lock.resize(new_capacity)?;
        Ok(())
    }

    #[inline]
    fn shrink_tracker(state: &mut Self::StorageState) -> Result<Option<usize>, LockingError> {
        let mut lock = state.tracker.lock_named(LockSource::AllocationTracker)?;
        Ok(lock.shrink_to_fit())
    }

    #[inline]
    fn track_next(
        state: &mut Self::StorageState,
        layout: Layout,
    ) -> Result<ByteRange, ContiguousMemoryError> {
        let base = Self::get_base(&state.base)? as usize;
        let mut lock = state.tracker.lock_named(LockSource::AllocationTracker)?;
        lock.take_next(base, layout)
    }

    #[inline]
    fn peek_next(
        state: &Self::StorageState,
        layout: Layout,
    ) -> Result<Option<ByteRange>, LockingError> {
        let lock = state.tracker.lock_named(LockSource::AllocationTracker)?;
        Ok(lock.peek_next(layout))
    }
}

impl StorageDetails for ImplDefault {
    type Base = Cell<*mut u8>;
    type AllocationTracker = RefCell<AllocationTracker>;
    type SizeType = Cell<usize>;
    type PushResult<T> = ContiguousEntryRef<T>;

    fn build_state(
        base: *mut u8,
        capacity: usize,
        alignment: usize,
    ) -> Result<Self::StorageState, LayoutError> {
        let layout: Layout = Layout::from_size_align(capacity, alignment)?;

        Ok(Rc::new(ContiguousMemoryState {
            base: BaseLocation(Cell::new(base)),
            capacity: Cell::new(layout.size()),
            alignment: layout.align(),
            tracker: RefCell::new(AllocationTracker::new(capacity)),
        }))
    }

    #[inline]
    fn deref_state(state: &Self::StorageState) -> &ContiguousMemoryState<Self> {
        state
    }

    #[inline]
    fn get_base(base: &Self::Base) -> Self::LockResult<*mut u8> {
        base.get()
    }

    #[inline]
    fn try_get_base(base: &Self::Base) -> Self::LockResult<*mut u8> {
        Self::get_base(base)
    }

    #[inline]
    fn get_capacity(capacity: &Self::SizeType) -> usize {
        capacity.get()
    }

    #[inline]
    fn get_allocation_tracker<'a>(
        state: &'a mut Self::StorageState,
    ) -> Self::LockResult<Self::ATGuard<'a>> {
        state.tracker.borrow_mut()
    }

    fn resize_container(
        state: &mut Self::StorageState,
        new_capacity: usize,
    ) -> Result<Option<*mut u8>, ContiguousMemoryError> {
        let layout = Layout::from_size_align(state.capacity.get(), state.alignment)?;
        let prev_base = state.base.get();
        let new_base = unsafe { allocator::realloc(prev_base, layout, new_capacity) };
        state.base.set(new_base);
        state.capacity.set(new_capacity);
        Ok(if new_base != prev_base {
            Some(new_base)
        } else {
            None
        })
    }

    #[inline]
    fn deallocate(base: &mut Self::Base, layout: Layout) {
        unsafe { allocator::dealloc(base.get(), layout) };
        base.set(null_mut())
    }

    #[inline]
    fn resize_tracker(
        state: &mut Self::StorageState,
        new_capacity: usize,
    ) -> Result<(), ContiguousMemoryError> {
        state.tracker.borrow_mut().resize(new_capacity)
    }

    #[inline]
    fn shrink_tracker(state: &mut Self::StorageState) -> Option<usize> {
        state.tracker.borrow_mut().shrink_to_fit()
    }

    #[inline]
    fn track_next(
        state: &mut Self::StorageState,
        layout: Layout,
    ) -> Result<ByteRange, ContiguousMemoryError> {
        let base = state.base.get() as usize;
        let mut tracker = state.tracker.borrow_mut();
        tracker.take_next(base, layout)
    }

    #[inline]
    fn peek_next(state: &Self::StorageState, layout: Layout) -> Option<ByteRange> {
        let tracker = state.tracker.borrow();
        tracker.peek_next(layout)
    }
}

impl StorageDetails for ImplUnsafe {
    type Base = *mut u8;
    type AllocationTracker = AllocationTracker;
    type SizeType = usize;
    type PushResult<T> = Result<*mut T, ContiguousMemoryError>;

    fn build_state(
        base: *mut u8,
        capacity: usize,
        alignment: usize,
    ) -> Result<Self::StorageState, LayoutError> {
        let layout = Layout::from_size_align(capacity, alignment)?;
        Ok(ContiguousMemoryState {
            base: BaseLocation(base),
            capacity: layout.size(),
            alignment: layout.align(),
            tracker: AllocationTracker::new(capacity),
        })
    }

    #[inline]
    fn deref_state(state: &Self::StorageState) -> &ContiguousMemoryState<Self> {
        state
    }

    #[inline]
    fn get_base(base: &Self::Base) -> Self::LockResult<*mut u8> {
        *base
    }

    #[inline]
    fn try_get_base(base: &Self::Base) -> Self::LockResult<*mut u8> {
        Self::get_base(base)
    }

    #[inline]
    fn get_capacity(capacity: &Self::SizeType) -> usize {
        *capacity
    }

    #[inline]
    fn get_allocation_tracker<'a>(
        state: &'a mut Self::StorageState,
    ) -> Self::LockResult<Self::ATGuard<'a>> {
        &mut state.tracker
    }

    fn resize_container(
        state: &mut Self::StorageState,
        new_capacity: usize,
    ) -> Result<Option<*mut u8>, ContiguousMemoryError> {
        let layout = Layout::from_size_align(state.capacity, state.alignment)?;
        let prev_base = *state.base;
        state.base = BaseLocation(unsafe { allocator::realloc(prev_base, layout, new_capacity) });
        state.capacity = new_capacity;
        Ok(if *state.base != prev_base {
            Some(*state.base)
        } else {
            None
        })
    }

    #[inline]
    fn deallocate(base: &mut Self::Base, layout: Layout) {
        unsafe {
            allocator::dealloc(*base, layout);
        }
        *base = null_mut();
    }

    #[inline]
    fn resize_tracker(
        state: &mut Self::StorageState,
        new_capacity: usize,
    ) -> Result<(), ContiguousMemoryError> {
        state.tracker.resize(new_capacity)
    }

    #[inline]
    fn shrink_tracker(state: &mut Self::StorageState) -> Option<usize> {
        state.tracker.shrink_to_fit()
    }

    #[inline]
    fn track_next(
        state: &mut Self::StorageState,
        layout: Layout,
    ) -> Result<ByteRange, ContiguousMemoryError> {
        let base = *state.base as usize;
        state.tracker.take_next(base, layout)
    }

    #[inline]
    fn peek_next(state: &Self::StorageState, layout: Layout) -> Option<ByteRange> {
        state.tracker.peek_next(layout)
    }
}

/// Implementation details of returned [reference types](crate::refs).
pub trait ReferenceDetails: ImplBase {
    /// The type representing internal state of the reference.
    type RefState<T: ?Sized>: Clone;

    /// The type handling concurrent mutable access exclusion.
    type BorrowLock;

    /// Type of the concurrent mutable access exclusion read guard.
    type ReadGuard<'a>: DebugReq;
    /// Type of the concurrent mutable access exclusion write guard.
    type WriteGuard<'a>: DebugReq;

    /// Releases the specified memory region back to the allocation tracker.
    fn free_region(
        tracker: Self::LockResult<Self::ATGuard<'_>>,
        base: Self::LockResult<*mut u8>,
        range: ByteRange,
    ) -> Option<*mut ()>;

    /// Builds a reference for the stored data.
    fn build_ref<T: StoreRequirements>(
        state: &Self::StorageState,
        addr: *mut T,
        range: ByteRange,
    ) -> Self::ReferenceType<T>;

    /// Marks reference state as no longer being borrowed.
    fn unborrow_ref<T: ?Sized>(_state: &Self::RefState<T>, _kind: BorrowKind) {}
}

impl ReferenceDetails for ImplConcurrent {
    type RefState<T: ?Sized> = Arc<ReferenceState<T, Self>>;
    type BorrowLock = RwLock<()>;
    type ReadGuard<'a> = RwLockReadGuard<'a, ()>;
    type WriteGuard<'a> = RwLockWriteGuard<'a, ()>;

    fn free_region(
        tracker: Self::LockResult<Self::ATGuard<'_>>,
        base: Self::LockResult<*mut u8>,
        range: ByteRange,
    ) -> Option<*mut ()> {
        if let Ok(mut lock) = tracker {
            let _ = lock.release(range);

            if let Ok(base) = base {
                unsafe { Some(base.add(range.0) as *mut ()) }
            } else {
                None
            }
        } else {
            None
        }
    }

    fn build_ref<T: StoreRequirements>(
        state: &Self::StorageState,
        _addr: *mut T,
        range: ByteRange,
    ) -> Self::ReferenceType<T> {
        SyncContiguousEntryRef {
            inner: Arc::new(ReferenceState {
                state: state.clone(),
                range,
                borrow_kind: RwLock::new(()),
                drop_fn: drop_fn::<T>(),
                _phantom: PhantomData,
            }),
            #[cfg(feature = "ptr_metadata")]
            metadata: (),
            #[cfg(not(feature = "ptr_metadata"))]
            _phantom: PhantomData,
        }
    }
}

impl ReferenceDetails for ImplDefault {
    type RefState<T: ?Sized> = Rc<ReferenceState<T, Self>>;
    type BorrowLock = Cell<BorrowState>;
    type ReadGuard<'a> = ();
    type WriteGuard<'a> = ();

    fn free_region(
        mut tracker: Self::LockResult<Self::ATGuard<'_>>,
        base: Self::LockResult<*mut u8>,
        range: ByteRange,
    ) -> Option<*mut ()> {
        let _ = tracker.release(range);
        unsafe { Some(base.add(range.0) as *mut ()) }
    }

    fn build_ref<T: StoreRequirements>(
        state: &Self::StorageState,
        _addr: *mut T,
        range: ByteRange,
    ) -> Self::ReferenceType<T> {
        ContiguousEntryRef {
            inner: Rc::new(ReferenceState {
                state: state.clone(),
                range,
                borrow_kind: Cell::new(BorrowState::Read(0)),
                drop_fn: drop_fn::<T>(),
                _phantom: PhantomData,
            }),
            #[cfg(feature = "ptr_metadata")]
            metadata: (),
            #[cfg(not(feature = "ptr_metadata"))]
            _phantom: PhantomData,
        }
    }

    fn unborrow_ref<T: ?Sized>(state: &Self::RefState<T>, _kind: BorrowKind) {
        let next = match state.borrow_kind.get() {
            BorrowState::Read(count) => BorrowState::Read(count - 1),
            BorrowState::Write => BorrowState::Read(0),
        };
        state.borrow_kind.set(next)
    }
}

impl ReferenceDetails for ImplUnsafe {
    type RefState<T: ?Sized> = ();
    type BorrowLock = ();
    type ReadGuard<'a> = ();
    type WriteGuard<'a> = ();

    fn free_region(
        tracker: Self::LockResult<Self::ATGuard<'_>>,
        base: Self::LockResult<*mut u8>,
        range: ByteRange,
    ) -> Option<*mut ()> {
        let _ = tracker.release(range);

        unsafe { Some(base.add(range.0) as *mut ()) }
    }

    fn build_ref<T>(
        _base: &Self::StorageState,
        addr: *mut T,
        _range: ByteRange,
    ) -> Self::ReferenceType<T> {
        addr
    }
}

pub trait StoreDataDetails: StorageDetails {
    unsafe fn push_raw<T: StoreRequirements>(
        state: &mut Self::StorageState,
        data: *const T,
        layout: Layout,
    ) -> Self::PushResult<T>;

    unsafe fn push_raw_persisted<T: StoreRequirements>(
        state: &mut Self::StorageState,
        data: *const T,
        layout: Layout,
    ) -> Self::PushResult<T>;

    fn assume_stored<T: StoreRequirements>(
        state: &Self::StorageState,
        position: usize,
    ) -> Self::LockResult<Self::ReferenceType<T>>;
}

impl StoreDataDetails for ImplConcurrent {
    unsafe fn push_raw<T: StoreRequirements>(
        state: &mut Self::StorageState,
        data: *const T,
        layout: Layout,
    ) -> Result<SyncContiguousEntryRef<T>, LockingError> {
        let (addr, range) = loop {
            match ImplConcurrent::track_next(state, layout) {
                Ok(taken) => {
                    let found = (taken.0
                        + *state.base.read_named(LockSource::BaseAddress)? as usize)
                        as *mut u8;
                    unsafe { core::ptr::copy_nonoverlapping(data as *mut u8, found, layout.size()) }
                    break (found, taken);
                }
                Err(ContiguousMemoryError::NoStorageLeft) => {
                    let curr_capacity = state.capacity.load(Ordering::Acquire);
                    let new_capacity = curr_capacity
                        .saturating_mul(2)
                        .max(curr_capacity + layout.size());
                    match ImplConcurrent::resize_container(state, new_capacity) {
                        Ok(_) => {
                            match ImplConcurrent::resize_tracker(state, new_capacity) {
                                Ok(_) => {},
                                Err(ContiguousMemoryError::Lock(locking_err)) => return Err(locking_err),
                                Err(_) => unreachable!("unable to grow AllocationTracker"),
                            };
                        }
                        Err(ContiguousMemoryError::Lock(locking_err)) => return Err(locking_err),
                        Err(other) => unreachable!(
                            "reached unexpected error while growing the container to store data: {:?}",
                            other
                        ),
                    };
                }
                Err(ContiguousMemoryError::Lock(locking_err)) => return Err(locking_err),
                Err(other) => unreachable!(
                    "reached unexpected error while looking for next region to store data: {:?}",
                    other
                ),
            }
        };

        Ok(ImplConcurrent::build_ref(state, addr as *mut T, range))
    }

    #[inline(always)]
    unsafe fn push_raw_persisted<T: StoreRequirements>(
        state: &mut Self::StorageState,
        data: *const T,
        layout: Layout,
    ) -> Self::PushResult<T> {
        match Self::push_raw(state, data, layout) {
            Ok(it) => {
                let result = it.clone();
                core::mem::forget(it.inner);
                Ok(result)
            }
            err => err,
        }
    }

    #[inline(always)]
    fn assume_stored<T: StoreRequirements>(
        state: &Self::StorageState,
        position: usize,
    ) -> Result<SyncContiguousEntryRef<T>, LockingError> {
        let addr = unsafe {
            state
                .base
                .read_named(LockSource::BaseAddress)?
                .add(position)
        };
        Ok(ImplConcurrent::build_ref(
            state,
            addr as *mut T,
            ByteRange(position, size_of::<T>()),
        ))
    }
}

impl StoreDataDetails for ImplDefault {
    unsafe fn push_raw<T: StoreRequirements>(
        state: &mut Self::StorageState,
        data: *const T,
        layout: Layout,
    ) -> ContiguousEntryRef<T> {
        let (addr, range) = loop {
            match ImplDefault::track_next(state, layout) {
                Ok(taken) => {
                    let found = (taken.0 + state.base.get() as usize) as *mut u8;
                    unsafe {
                        core::ptr::copy_nonoverlapping(data as *mut u8, found, layout.size());
                    }
                    break (found, taken);
                }
                Err(ContiguousMemoryError::NoStorageLeft) => {
                    let curr_capacity = state.capacity.get();
                    let new_capacity = curr_capacity
                        .saturating_mul(2)
                        .max(curr_capacity + layout.size());
                    match ImplDefault::resize_container(state, new_capacity) {
                        Ok(_) => {
                            ImplDefault::resize_tracker(state, new_capacity).expect("unable to grow AllocationTracker");
                        },
                        Err(err) => unreachable!(
                            "reached unexpected error while growing the container to store data: {:?}",
                            err
                        ),
                    }
                }
                Err(other) => unreachable!(
                    "reached unexpected error while looking for next region to store data: {:?}",
                    other
                ),
            }
        };

        ImplDefault::build_ref(state, addr as *mut T, range)
    }

    #[inline(always)]
    unsafe fn push_raw_persisted<T: StoreRequirements>(
        state: &mut Self::StorageState,
        data: *const T,
        layout: Layout,
    ) -> Self::PushResult<T> {
        let value = Self::push_raw(state, data, layout);
        let result = value.clone();
        core::mem::forget(value.inner);
        result
    }

    #[inline(always)]
    fn assume_stored<T: StoreRequirements>(
        state: &Self::StorageState,
        position: usize,
    ) -> ContiguousEntryRef<T> {
        let addr = unsafe { state.base.get().add(position) };
        ImplDefault::build_ref(state, addr as *mut T, ByteRange(position, size_of::<T>()))
    }
}

impl StoreDataDetails for ImplUnsafe {
    /// Returns a raw pointer (`*mut T`) to the stored value or an error if no
    /// free regions remain
    unsafe fn push_raw<T: StoreRequirements>(
        state: &mut Self::StorageState,
        data: *const T,
        layout: Layout,
    ) -> Result<*mut T, ContiguousMemoryError> {
        let (addr, range) = match ImplUnsafe::track_next(state, layout) {
            Ok(taken) => {
                let found = (taken.0 + *state.base as usize) as *mut u8;
                unsafe {
                    core::ptr::copy_nonoverlapping(data as *mut u8, found, layout.size());
                }

                (found, taken)
            }
            Err(other) => return Err(other),
        };

        Ok(ImplUnsafe::build_ref(state, addr as *mut T, range))
    }

    unsafe fn push_raw_persisted<T: StoreRequirements>(
        _state: &mut Self::StorageState,
        _data: *const T,
        _layout: Layout,
    ) -> Self::PushResult<T> {
        unimplemented!()
    }

    #[inline(always)]
    fn assume_stored<T: StoreRequirements>(state: &Self::StorageState, position: usize) -> *mut T {
        let addr = unsafe { state.base.add(position) };
        ImplUnsafe::build_ref(
            state,
            addr as *mut T,
            ByteRange(position, position + size_of::<T>()),
        )
    }
}

/// Trait representing requirements for implementation details of the
/// [`ContiguousMemoryStorage`](crate::ContiguousMemoryStorage).
///
/// This trait is implemented by:
/// - [`ImplDefault`]
/// - [`ImplConcurrent`]
/// - [`ImplUnsafe`]
pub trait ImplDetails: ImplBase + StorageDetails + ReferenceDetails + StoreDataDetails {}
impl<Impl: ImplBase + StorageDetails + ReferenceDetails + StoreDataDetails> ImplDetails for Impl {}