rive_cache_inmemory/
reference.rs

1use dashmap::mapref::{multiple::RefMulti, one::Ref};
2use std::{
3    fmt::{Debug, Formatter, Result as FmtResult},
4    hash::Hash,
5    ops::Deref,
6};
7
8/// Immutable reference to a resource in the cache.
9// We need this so as not to expose the underlying cache implementation.
10// From https://github.com/twilight-rs/twilight/blob/main/twilight-cache-inmemory/src/lib.rs
11pub struct Reference<'a, K, V> {
12    inner: Ref<'a, K, V>,
13}
14
15impl<'a, K: Eq + Hash, V> Reference<'a, K, V> {
16    /// Create a new reference from a `DashMap` reference.
17    #[allow(clippy::missing_const_for_fn)]
18    pub(crate) fn new(inner: Ref<'a, K, V>) -> Self {
19        Self { inner }
20    }
21
22    /// Immutable reference to the key identifying the resource.
23    pub fn key(&'a self) -> &'a K {
24        self.inner.key()
25    }
26
27    /// Immutable reference to the underlying value.
28    pub fn value(&'a self) -> &'a V {
29        self.inner.value()
30    }
31}
32
33impl<K: Eq + Hash, V: Debug> Debug for Reference<'_, K, V> {
34    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
35        f.debug_struct("Reference")
36            .field("inner", self.value())
37            .finish()
38    }
39}
40
41impl<'a, K: Eq + Hash, V> Deref for Reference<'a, K, V> {
42    type Target = V;
43
44    fn deref(&self) -> &Self::Target {
45        self.value()
46    }
47}
48
49/// Reference to a resource value being iterated over in the cache.
50pub struct IterReference<'a, K, V> {
51    inner: RefMulti<'a, K, V>,
52}
53
54impl<'a, K, V> IterReference<'a, K, V> {
55    /// Create a new iterator element reference.
56    pub(crate) const fn new(inner: RefMulti<'a, K, V>) -> Self {
57        Self { inner }
58    }
59}
60
61impl<K: Eq + Hash, V> IterReference<'_, K, V> {
62    /// Immutable reference to the resource's key.
63    pub fn key(&self) -> &K {
64        self.inner.key()
65    }
66
67    /// Immutable reference to the resource's value.
68    pub fn value(&self) -> &V {
69        self.inner.value()
70    }
71}
72
73impl<K: Eq + Hash, V> Deref for IterReference<'_, K, V> {
74    type Target = V;
75
76    fn deref(&self) -> &Self::Target {
77        self.value()
78    }
79}
80
81impl<K: Eq + Hash, V: Debug> Debug for IterReference<'_, K, V> {
82    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
83        f.debug_struct("IterReference")
84            .field("inner", self.value())
85            .finish()
86    }
87}