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
//! Errors that can be generated during Runt's execution.
use std::{error, fmt, string};

/// An error generated by Runt.
pub struct RuntError(pub String);

impl fmt::Debug for RuntError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl fmt::Display for RuntError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl error::Error for RuntError {}

impl From<string::FromUtf8Error> for RuntError {
    fn from(err: string::FromUtf8Error) -> Self {
        RuntError(err.to_string())
    }
}

impl From<std::io::Error> for RuntError {
    fn from(err: std::io::Error) -> Self {
        RuntError(err.to_string())
    }
}

impl From<tokio::task::JoinError> for RuntError {
    fn from(err: tokio::task::JoinError) -> Self {
        RuntError(err.to_string())
    }
}

impl From<tokio::time::error::Elapsed> for RuntError {
    fn from(err: tokio::time::error::Elapsed) -> Self {
        RuntError(err.to_string())
    }
}

/// Helper method to collapse nested Results
pub trait RichResult<T, E> {
    fn collapse(self) -> Result<T, E>;
}

impl<T, E> RichResult<T, E> for Result<Result<Result<T, E>, E>, E> {
    fn collapse(self) -> Result<T, E> {
        match self {
            Ok(Ok(Ok(v))) => Ok(v),
            Ok(Ok(Err(e))) => Err(e),
            Ok(Err(e)) => Err(e),
            Err(e) => Err(e),
        }
    }
}

impl<T, E> RichResult<T, E> for Result<Result<T, E>, E> {
    fn collapse(self) -> Result<T, E> {
        match self {
            Ok(Ok(v)) => Ok(v),
            Ok(Err(e)) => Err(e),
            Err(e) => Err(e),
        }
    }
}

/// Simple trait to implement partitioning methon on vectors of results.
pub trait RichVec<T, E> {
    /// Separate a Vec containing both `T` and `E` into two seperate `Vec`s.
    fn partition_results(self) -> (Vec<T>, Vec<E>);
}
impl<T, E> RichVec<T, E> for Vec<Result<T, E>>
where
    T: std::fmt::Debug,
    E: std::fmt::Debug,
{
    fn partition_results(self) -> (Vec<T>, Vec<E>) {
        let (ts, es): (Vec<_>, Vec<_>) =
            self.into_iter().partition(|el| el.is_ok());
        (
            ts.into_iter().map(Result::unwrap).collect::<Vec<T>>(),
            es.into_iter().map(Result::unwrap_err).collect::<Vec<E>>(),
        )
    }
}