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

/// `legacylisten`'s Error type.
///
/// This type bundles all errors which could occur.
#[derive(Debug)]
pub enum Error
{
    /// The CSV file which stores the playing likelihoods and
    /// the volumes was malformatted.
    MalformattedSongsCsv,
    MalformattedListOfCommandCharacters,
    Custom(String),
    Vec(Vec<Error>),
}

impl fmt::Display for Error
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error>
    {
        match self
        {
            Self::MalformattedSongsCsv => write!(f, "Malformatted songs.csv file"),
            Self::MalformattedListOfCommandCharacters =>
            {
                write!(f, "Malformatted list of command characters")
            }
            Self::Custom(err) => write!(f, "Custom error: {err}"),
            Self::Vec(v) =>
            {
                if v.len() == 1
                {
                    write!(f, "{}", v[0])
                }
                else
                {
                    writeln!(f, "Multiple errors ({}):", v.len())?;
                    for (i, e) in v.iter().enumerate()
                    {
                        write!(f, "{i}: {e}")?;
                        if i != v.len() + 1
                        {
                            writeln!(f)?;
                        }
                    }

                    Ok(())
                }
            }
        }
    }
}

impl error::Error for Error {}

impl From<String> for Error
{
    fn from(err: String) -> Self
    {
        Self::Custom(err)
    }
}

impl<T> From<Vec<T>> for Error
where
    Self: From<T>,
{
    fn from(err: Vec<T>) -> Self
    {
        Self::Vec(err.into_iter().map(Into::into).collect())
    }
}