1use core::ops::{Index, IndexMut};
2
3pub trait TryIndex<Idx> {
5 type Error;
7
8 type Output: ?Sized;
10
11 fn try_index(&self, index: Idx) -> Result<&Self::Output, Self::Error>;
13}
14
15pub trait TryIndexMut<Idx> : TryIndex<Idx> {
17 fn try_index_mut(&mut self, index: Idx) -> Result<&mut Self::Output, Self::Error>;
19}
20
21impl<T: Index<Idx>, Idx> TryIndex<Idx> for T {
22 type Error = crate::Infallible;
23 type Output = <Self as Index<Idx>>::Output;
24
25 fn try_index(&self, index: Idx) -> Result<&Self::Output, Self::Error> {
26 Ok(self.index(index))
27 }
28}
29
30impl<T: IndexMut<Idx>, Idx> TryIndexMut<Idx> for T {
31 fn try_index_mut(&mut self, index: Idx) -> Result<&mut Self::Output, Self::Error> {
32 Ok(self.index_mut(index))
33 }
34}