reslab/
ref.rs

1use std::ops::Deref;
2
3use sharded_slab::{Entry, OwnedEntry};
4
5/// A type that represents a borrowed reference to a value in a
6/// [`super::ReSlab`].
7pub type Ref<'a, K, V> = RefWrapper<K, Entry<'a, V>>;
8
9/// A type that represents a owned reference to a value in a [`super::ReSlab`].
10pub type OwnedRef<K, V> = RefWrapper<K, OwnedEntry<V>>;
11
12/// A trait to abstract over getting the offset of a slab entry.
13pub trait SlabEntry {
14    type Value;
15
16    /// Gets the offset to this entry in the slab.
17    fn offset(&self) -> usize;
18
19    /// Gets a reference to the value of this entry.
20    fn as_inner(&self) -> &Self::Value;
21}
22
23/// A wrapper to wrap reference to a value in a [`ReSlab`].
24#[derive(Debug)]
25pub struct RefWrapper<K, E> {
26    inner: E,
27    _marker: std::marker::PhantomData<K>,
28}
29
30impl<K, E: SlabEntry> RefWrapper<K, E> {
31    /// Creates a new instance of [`Ref`] with the provided slab entry.
32    #[inline]
33    pub(super) const fn new(inner: E) -> Self {
34        Self {
35            inner,
36            _marker: std::marker::PhantomData,
37        }
38    }
39
40    /// Gets the offset to this entry in the slab.
41    #[inline]
42    pub fn offset(&self) -> usize {
43        self.inner.offset()
44    }
45}
46
47impl<K, E: SlabEntry> Deref for RefWrapper<K, E> {
48    type Target = E::Value;
49
50    #[inline]
51    fn deref(&self) -> &Self::Target {
52        self.inner.as_inner()
53    }
54}
55
56impl<V> SlabEntry for Entry<'_, V> {
57    type Value = V;
58
59    #[inline]
60    fn offset(&self) -> usize {
61        self.key()
62    }
63
64    #[inline]
65    fn as_inner(&self) -> &V {
66        self.deref()
67    }
68}
69
70impl<V> SlabEntry for OwnedEntry<V> {
71    type Value = V;
72
73    #[inline]
74    fn offset(&self) -> usize {
75        self.key()
76    }
77
78    #[inline]
79    fn as_inner(&self) -> &V {
80        self.deref()
81    }
82}