rspace_traits/ops/
get.rs

1/*
2    Appellation: get <module>
3    Created At: 2025.12.29:15:17:51
4    Contrib: @FL03
5*/
6
7/// [`Get`] defines an interface for entities that can be accessed by a key; the design is
8/// similar to the [`Index`](core::ops::Index) trait in the standard library, however, uses the
9/// [`Borrow`](core::borrow::Borrow) trait to allow for more flexible key types.
10pub trait Get<Q> {
11    type Key;
12    type Value: ?Sized;
13    /// returns a reference to the element at the specified index.
14    fn get(&self, index: Q) -> Option<&Self::Value>
15    where
16        Self::Key: core::borrow::Borrow<Q>;
17}
18/// [`GetMut`] defines an interface for entities that can be accessed by a key; the design
19/// is similar to the [`IndexMut`](core::ops::IndexMut) trait in the standard library
20pub trait GetMut<Q>: Get<Q> {
21    /// returns a mutable reference to the element at the specified index.
22    fn get_mut(&mut self, index: Q) -> Option<&mut Self::Value>
23    where
24        Self::Key: core::borrow::Borrow<Q>;
25}
26
27/*
28 ************* Implementations *************
29*/
30
31impl<Q, K, Y, U> Get<Q> for &U
32where
33    U: Get<Q, Key = K, Value = Y>,
34{
35    type Key = U::Key;
36    type Value = U::Value;
37
38    fn get(&self, index: Q) -> Option<&Y>
39    where
40        Self::Key: core::borrow::Borrow<Q>,
41    {
42        (*self).get(index)
43    }
44}
45
46impl<Q, T> Get<Q> for [T]
47where
48    Q: core::slice::SliceIndex<[T]>,
49{
50    type Key = usize;
51    type Value = Q::Output;
52
53    fn get(&self, index: Q) -> Option<&Self::Value>
54    where
55        Self::Key: core::borrow::Borrow<Q>,
56    {
57        self.as_ref().get(index)
58    }
59}
60
61#[cfg(feature = "hashbrown")]
62impl<Q, K, V, S> Get<Q> for hashbrown::HashMap<K, V, S>
63where
64    Q: Eq + core::hash::Hash,
65    K: Eq + core::hash::Hash,
66    S: core::hash::BuildHasher,
67{
68    type Key = K;
69    type Value = V;
70
71    fn get(&self, index: Q) -> Option<&V>
72    where
73        Self::Key: core::borrow::Borrow<Q>,
74    {
75        self.get(&index)
76    }
77}