rspace_traits/
get.rs

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