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
64
65
66
67
68
69
70
71
72
73
use serde::Serialize;

#[derive(Clone, PartialEq, Eq, Serialize, Debug)]
#[serde(tag = "type", content = "content")]
pub enum Loadable<R, E> {
    Loading,
    Ready(R),
    Err(E),
}

impl<R, E> Default for Loadable<R, E> {
    fn default() -> Self {
        Self::Loading
    }
}

impl<R, E> Loadable<R, E> {
    #[inline]
    pub fn is_ready(&self) -> bool {
        matches!(self, Loadable::Ready(_))
    }
    #[inline]
    pub fn is_err(&self) -> bool {
        matches!(self, Loadable::Err(_))
    }
    #[inline]
    pub fn is_loading(&self) -> bool {
        matches!(self, Loadable::Loading)
    }
    #[inline]
    pub fn as_ref(&self) -> Loadable<&R, &E> {
        match *self {
            Loadable::Err(ref e) => Loadable::Err(e),
            Loadable::Ready(ref r) => Loadable::Ready(r),
            Loadable::Loading => Loadable::Loading,
        }
    }
    #[inline]
    pub fn ready(&self) -> Option<&R> {
        match self {
            Loadable::Ready(r) => Some(r),
            _ => None,
        }
    }
    #[inline]
    pub fn err(&self) -> Option<&E> {
        match self {
            Loadable::Err(e) => Some(e),
            _ => None,
        }
    }
    #[inline]
    pub fn expect(self, msg: &str) -> R {
        match self {
            Self::Ready(r) => r,
            _ => panic!("{}", msg),
        }
    }
    #[inline]
    pub fn expect_err(self, msg: &str) -> E {
        match self {
            Self::Err(e) => e,
            _ => panic!("{}", msg),
        }
    }
    #[inline]
    pub fn expect_loading(self, msg: &str) {
        match self {
            Self::Loading => {}
            _ => panic!("{}", msg),
        }
    }
}