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
use std::error;
use std::fmt;

/// An error that can be cloned.
pub trait ErrorClone: error::Error + Send + Sync + 'static {
    /// Clone the error.
    fn clone_box(&self) -> Box<ErrorClone>;
}

impl<E> ErrorClone for E
where
    E: error::Error + Clone + Send + Sync + 'static,
{
    fn clone_box(&self) -> Box<ErrorClone> {
        Box::new(self.clone())
    }
}

impl Clone for Box<ErrorClone> {
    fn clone(&self) -> Box<ErrorClone> {
        self.clone_box()
    }
}

/// A lossy way to have any error be clonable.
#[derive(Debug, Clone)]
pub struct CloneableError {
    error: String,
}

impl CloneableError {
    /// Lossily make any error cloneable.
    pub fn new<E>(error: E) -> Self
    where
        E: error::Error + Send + Sync + 'static,
    {
        Self {
            error: error.to_string(),
        }
    }
}

impl fmt::Display for CloneableError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "{}", self.error)
    }
}

impl error::Error for CloneableError {
    fn description(&self) -> &str {
        self.error.as_str()
    }

    fn cause(&self) -> Option<&error::Error> {
        None
    }
}