optional_index/
lib.rs

1#![no_std]
2
3/// Optional immutable index.
4pub trait OptionalIndex<I>
5where
6    I: ?Sized,
7{
8    type Output: Clone + ?Sized;
9
10    fn optional_index(&self, index: I) -> Option<&Self::Output>;
11}
12
13/// Optional mutable index.
14pub trait OptionalIndexMut<I>: OptionalIndex<I>
15where
16    I: ?Sized,
17{
18    fn optional_index_mut(&mut self, index: I) -> Option<&mut Self::Output>;
19}
20
21impl<T, I> OptionalIndex<I> for &T
22where
23    T: OptionalIndex<I>,
24{
25    type Output = <T as OptionalIndex<I>>::Output;
26
27    fn optional_index(&self, index: I) -> Option<&Self::Output> {
28        (*self).optional_index(index)
29    }
30}
31
32impl<T, I> OptionalIndex<I> for &mut T
33where
34    T: OptionalIndex<I>,
35{
36    type Output = <T as OptionalIndex<I>>::Output;
37
38    fn optional_index(&self, index: I) -> Option<&Self::Output> {
39        (**self).optional_index(index)
40    }
41}
42
43impl<T, I> OptionalIndexMut<I> for &mut T
44where
45    T: OptionalIndexMut<I>,
46{
47    fn optional_index_mut(&mut self, index: I) -> Option<&mut Self::Output> {
48        (*self).optional_index_mut(index)
49    }
50}
51
52impl<T, I> OptionalIndex<I> for Option<T>
53where
54    T: OptionalIndex<I>,
55{
56    type Output = <T as OptionalIndex<I>>::Output;
57
58    fn optional_index(&self, index: I) -> Option<&Self::Output> {
59        self.as_ref().and_then(|t| t.optional_index(index))
60    }
61}
62
63impl<T, I> OptionalIndexMut<I> for Option<T>
64where
65    T: OptionalIndexMut<I>,
66{
67    fn optional_index_mut(&mut self, index: I) -> Option<&mut Self::Output> {
68        self.as_mut().and_then(|t| t.optional_index_mut(index))
69    }
70}