1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use crate::rocket;

use std::ops::{Deref, DerefMut};

use rocket::form::{self, FromFormField, ValueField};
use rocket::request::FromParam;

/// A wrapper of `std::result::Result`, in order to implement the `FromFormField` trait of Rocket.
///
/// This struct uses the `FromParam` trait to implement the `FromFormField` trait (only impl the `from_value` method) so that it can remain the error type for checking later.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Result<T, E>(std::result::Result<T, E>);

impl<T, E> Result<T, E> {
    #[inline]
    pub fn into_std_result(self) -> std::result::Result<T, E> {
        self.0
    }

    #[inline]
    pub fn as_std_result(&self) -> &std::result::Result<T, E> {
        &self.0
    }
}

impl<T, E> From<std::result::Result<T, E>> for Result<T, E> {
    #[inline]
    fn from(result: std::result::Result<T, E>) -> Self {
        Self(result)
    }
}

impl<T, E> From<Result<T, E>> for std::result::Result<T, E> {
    #[inline]
    fn from(result: Result<T, E>) -> Self {
        result.0
    }
}

impl<T, E> Deref for Result<T, E> {
    type Target = std::result::Result<T, E>;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T, E> DerefMut for Result<T, E> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<'v, E: Sized + Send, T: FromParam<'v, Error = E> + Send> FromFormField<'v>
    for Result<T, T::Error>
{
    #[inline]
    fn from_value(v: ValueField<'v>) -> form::Result<'v, Self> {
        Ok(<T as FromParam>::from_param(v.value).into())
    }
}