nvim_oxi_luajit/into_result.rs
1use core::convert::Infallible;
2
3/// A trait for types that can be converted into a `Result`.
4///
5/// This trait can be used to be generic over functions that can return either
6/// a `T` or a `Result<T, E>`.
7///
8/// # Examples
9///
10/// ```
11/// # use nvim_oxi_luajit::IntoResult;
12/// fn double<F: Fn() -> R, R: IntoResult<usize>>(
13/// f: F,
14/// ) -> Result<usize, R::Error> {
15/// f().into_result().map(|x| x * 2)
16/// }
17///
18/// # fn main() {
19/// // `double` takes a closure whose return type is generic over `IntoResult`,
20/// // so we don't have to return `Ok(21)`.
21/// assert_eq!(double(|| 21), Ok(42));
22/// # }
23/// ```
24pub trait IntoResult<T> {
25 /// The error type in the returned `Result`.
26 type Error;
27
28 /// Converts the value into a `Result`.
29 fn into_result(self) -> Result<T, Self::Error>;
30}
31
32impl<T> IntoResult<T> for T {
33 type Error = Infallible;
34
35 #[inline]
36 fn into_result(self) -> Result<T, Self::Error> {
37 Ok(self)
38 }
39}
40
41impl<T, E> IntoResult<T> for Result<T, E> {
42 type Error = E;
43
44 #[inline]
45 fn into_result(self) -> Result<T, Self::Error> {
46 self
47 }
48}