try_traits/
borrow.rs

1//! Try traits for [`core::borrow`].
2
3use core::borrow::{Borrow, BorrowMut};
4
5/// The try trait for [`Borrow`].
6pub trait TryBorrow<Borrowed: ?Sized> {
7	/// The type returned in the event of an error.
8	type Error;
9
10	/// The fallible equivalent of [`Borrow::borrow`].
11	fn try_borrow(&self) -> Result<&Borrowed, Self::Error>;
12}
13
14/// The try trait for [`BorrowMut`].
15pub trait TryBorrowMut<Borrowed: ?Sized> : TryBorrow<Borrowed> {
16	/// The fallible equivalent of [`BorrowMut::try_borrowMut`].
17	fn try_borrow_mut(&mut self) -> Result<&mut Borrowed, <Self as TryBorrow<Borrowed>>::Error>;
18}
19
20impl<T: Borrow<Borrowed>, Borrowed: ?Sized> TryBorrow<Borrowed> for T {
21	type Error = crate::Infallible;
22
23	#[inline]
24	fn try_borrow(&self) -> Result<&Borrowed, Self::Error> {
25		Ok(self.borrow())
26	}
27}
28
29impl<T: BorrowMut<Borrowed>, Borrowed: ?Sized> TryBorrowMut<Borrowed> for T {
30	#[inline]
31	fn try_borrow_mut(&mut self) -> Result<&mut Borrowed, Self::Error> {
32		Ok(self.borrow_mut())
33	}
34}