ruby_marshal/value_arena/
value_handle.rs

1use std::hash::Hash;
2use std::hash::Hasher;
3use std::marker::PhantomData;
4
5/// A handle around a Ruby Value.
6#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq)]
7pub struct ValueHandle {
8    /// The arena index
9    pub(super) index: slotmap::DefaultKey,
10    // TODO: Should we an a counter to the arena itself to prevent accidental accesses to other arenas?
11}
12
13impl ValueHandle {
14    /// Create a new [`ValueHandle`] from an Index
15    pub(super) fn new(index: slotmap::DefaultKey) -> Self {
16        Self { index }
17    }
18}
19
20/// A typed version of a [`ValueHandle`].
21#[derive(Debug)]
22pub struct TypedValueHandle<T> {
23    handle: ValueHandle,
24    _data: PhantomData<T>,
25}
26
27impl<T> TypedValueHandle<T> {
28    /// Create a new [`TypedValueHandle`] from a [`ValueHandle`] without type checking.
29    pub(crate) fn new_unchecked(handle: ValueHandle) -> Self {
30        Self {
31            handle,
32            _data: PhantomData,
33        }
34    }
35
36    /// Get the raw untyped handle.
37    pub fn into_raw(self) -> ValueHandle {
38        self.handle
39    }
40}
41
42impl<T> Clone for TypedValueHandle<T> {
43    fn clone(&self) -> Self {
44        *self
45    }
46}
47
48impl<T> Copy for TypedValueHandle<T> {}
49
50impl<T> PartialEq<Self> for TypedValueHandle<T> {
51    fn eq(&self, other: &Self) -> bool {
52        self.handle.eq(&other.handle)
53    }
54}
55
56impl<T> Eq for TypedValueHandle<T> {}
57
58impl<T> Hash for TypedValueHandle<T> {
59    fn hash<H>(&self, state: &mut H)
60    where
61        H: Hasher,
62    {
63        self.handle.hash(state)
64    }
65}
66
67impl<T> From<TypedValueHandle<T>> for ValueHandle {
68    fn from(handle: TypedValueHandle<T>) -> Self {
69        handle.into_raw()
70    }
71}