Skip to main content

omega_cache/core/
key.rs

1use bytes::Bytes;
2use std::borrow::Borrow;
3use std::hash::{Hash, Hasher};
4use std::ops::Deref;
5use std::sync::Arc;
6
7/// A key wrapper that uses `Arc` for cheap cloning and equality comparisons.
8#[repr(transparent)]
9#[derive(Debug)]
10pub struct Key<K>(Arc<K>)
11where
12    K: Eq + Hash;
13
14impl<K> Key<K>
15where
16    K: Eq + Hash,
17{
18    /// Wraps a key in an Arc for shared ownership.
19    pub(crate) fn new(key: K) -> Self {
20        Self(Arc::new(key))
21    }
22}
23
24impl<K> Clone for Key<K>
25where
26    K: Eq + Hash,
27{
28    fn clone(&self) -> Self {
29        Self(self.0.clone())
30    }
31}
32
33impl<K> PartialEq<Self> for Key<K>
34where
35    K: Eq + Hash,
36{
37    fn eq(&self, other: &Self) -> bool {
38        self.0 == other.0
39    }
40}
41
42impl<K> Eq for Key<K> where K: Eq + Hash {}
43
44impl<K> Hash for Key<K>
45where
46    K: Eq + Hash,
47{
48    fn hash<H: Hasher>(&self, state: &mut H) {
49        self.0.hash(state)
50    }
51}
52
53impl<K> AsRef<K> for Key<K>
54where
55    K: Eq + Hash,
56{
57    fn as_ref(&self) -> &K {
58        self.0.as_ref()
59    }
60}
61
62impl<K> Borrow<K> for Key<K>
63where
64    K: Eq + Hash,
65{
66    fn borrow(&self) -> &K {
67        self.0.as_ref()
68    }
69}
70
71impl Borrow<str> for Key<String> {
72    fn borrow(&self) -> &str {
73        self.0.as_ref().borrow()
74    }
75}
76
77impl Borrow<[u8]> for Key<String> {
78    fn borrow(&self) -> &[u8] {
79        self.0.as_ref().as_bytes()
80    }
81}
82
83impl<T> Borrow<[T]> for Key<Vec<T>>
84where
85    T: Eq + Hash,
86{
87    fn borrow(&self) -> &[T] {
88        self.0.as_ref().as_slice()
89    }
90}
91
92impl Borrow<[u8]> for Key<Bytes> {
93    fn borrow(&self) -> &[u8] {
94        self.0.as_ref()
95    }
96}
97
98impl<K> Deref for Key<K>
99where
100    K: Eq + Hash,
101{
102    type Target = K;
103
104    fn deref(&self) -> &Self::Target {
105        self.0.as_ref()
106    }
107}