try_traits/ops/
index.rs

1use core::ops::{Index, IndexMut};
2
3///
4pub trait TryIndex<Idx> {
5	/// The type returned in the event of an error.
6	type Error;
7
8	/// The type returned after performing the operation.
9	type Output: ?Sized;
10
11	/// The fallible equivalent of [`Index::index`].
12	fn try_index(&self, index: Idx) -> Result<&Self::Output, Self::Error>;
13}
14
15/// The try trait for [`IndexMut`].
16pub trait TryIndexMut<Idx> : TryIndex<Idx> {
17	/// The fallible equivalent of [`Index::index`].
18	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}