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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
use std::{
    collections::BTreeMap,
    fmt::{Debug, Display},
};

use derive_more::{Display, Error};

#[derive(Error)]
#[non_exhaustive]
pub struct StartError {
    pub errors: Vec<StartGroupError>,
}

impl StartError {
    pub(crate) fn single(group: String, reason: String) -> Self {
        Self {
            errors: vec![StartGroupError { group, reason }],
        }
    }

    pub(crate) fn multiple(errors: Vec<StartGroupError>) -> Self {
        Self { errors }
    }
}

fn group_errors(errors: Vec<StartGroupError>) -> BTreeMap<String, Vec<String>> {
    // `BTreeMap` is used purely to provide consistent group order in error
    // messages.
    let mut group_errors = BTreeMap::<String, Vec<String>>::new();
    for error in errors {
        group_errors
            .entry(error.group)
            .or_default()
            .push(error.reason);
    }
    // Sort errors to provide consistent order.
    for errors in group_errors.values_mut() {
        errors.sort();
    }
    group_errors
}

impl Debug for StartError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if f.alternate() {
            let mut s = f.debug_struct("StartError");
            s.field("errors", &self.errors);
            s.finish()
        } else {
            write!(f, "failed to start\n\n")?;
            for (group, errors) in group_errors(self.errors.clone()) {
                writeln!(f, "{group}:")?;
                for error in errors {
                    writeln!(f, "- {error}")?;
                }
                writeln!(f)?;
            }
            Ok(())
        }
    }
}

impl Display for StartError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "failed to start: ")?;
        let mut i = 1;
        for (group, errors) in group_errors(self.errors.clone()) {
            for error in errors {
                write!(f, "{i}. {error} ({group}); ")?;
                i += 1;
            }
        }
        Ok(())
    }
}

#[derive(Clone, Debug, Display, Error)]
#[non_exhaustive]
#[display(fmt = "error from group {group}: {reason}")]
pub struct StartGroupError {
    pub group: String,
    pub reason: String,
}

#[derive(Debug, Display, Error)]
#[display(fmt = "mailbox closed")]
pub struct SendError<T>(#[error(not(source))] pub T);

#[derive(Debug, Display, Error)]
pub enum TrySendError<T> {
    /// The mailbox is full.
    #[display(fmt = "mailbox full")]
    Full(#[error(not(source))] T),
    /// The mailbox has been closed.
    #[display(fmt = "mailbox closed")]
    Closed(#[error(not(source))] T),
}

impl<T> TrySendError<T> {
    /// Converts the error into its inner value.
    #[inline]
    pub fn into_inner(self) -> T {
        match self {
            Self::Closed(inner) => inner,
            Self::Full(inner) => inner,
        }
    }

    /// Transforms the inner message.
    #[inline]
    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> TrySendError<U> {
        match self {
            Self::Full(inner) => TrySendError::Full(f(inner)),
            Self::Closed(inner) => TrySendError::Closed(f(inner)),
        }
    }

    /// Returns whether the error is the `Full` variant.
    #[inline]
    pub fn is_full(&self) -> bool {
        matches!(self, Self::Full(_))
    }

    /// Returns whether the error is the `Closed` variant.
    #[inline]
    pub fn is_closed(&self) -> bool {
        matches!(self, Self::Closed(_))
    }
}

#[derive(Debug, Display, Error)]
pub enum RequestError {
    /// Receiver hasn't got the request.
    #[display(fmt = "request failed")]
    Failed,
    /// Receiver has got the request, but ignored it.
    #[display(fmt = "request ignored")]
    Ignored,
}

impl RequestError {
    /// Returns whether the error is the `Failed` variant.
    #[inline]
    pub fn is_failed(&self) -> bool {
        matches!(self, Self::Failed)
    }

    /// Returns whether the error is the `Ignored` variant.
    #[inline]
    pub fn is_ignored(&self) -> bool {
        matches!(self, Self::Ignored)
    }
}

#[derive(Debug, Clone, Display, Error)]
pub enum TryRecvError {
    /// The mailbox is empty.
    #[display(fmt = "mailbox empty")]
    Empty,
    /// The mailbox has been closed.
    #[display(fmt = "mailbox closed")]
    Closed,
}

impl TryRecvError {
    /// Returns whether the error is the `Empty` variant.
    #[inline]
    pub fn is_empty(&self) -> bool {
        matches!(self, Self::Empty)
    }

    /// Returns whether the error is the `Closed` variant.
    #[inline]
    pub fn is_closed(&self) -> bool {
        matches!(self, Self::Closed)
    }
}