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
use std::fmt;
use std::io;
use std::time::SystemTimeError;

// Deriving Debug is necessary to use .expect() method
#[derive(Debug)]
pub enum Error {
    IoError(io::Error),
    SystemTimeError(SystemTimeError),
    TooSmallWindow(usize, usize),
    UnknownWindowSize,
    NotUtf8Input(Vec<u8>),
    ControlCharInText(char),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use Error::*;
        match self {
            IoError(err) => write!(f, "{}", err),
            SystemTimeError(err) => write!(f, "{}", err),
            TooSmallWindow(w, h) => write!(
                f,
                "Screen {}x{} is too small. At least 1x3 is necessary in width x height",
                w, h
            ),
            UnknownWindowSize => write!(f, "Could not detect terminal window size"),
            NotUtf8Input(seq) => {
                write!(f, "Cannot handle non-UTF8 multi-byte input sequence: ")?;
                for byte in seq.iter() {
                    write!(f, "\\x{:x}", byte)?;
                }
                Ok(())
            }
            ControlCharInText(c) => write!(f, "Invalid character for text is included: {:?}", c),
        }
    }
}

impl From<io::Error> for Error {
    fn from(err: io::Error) -> Error {
        Error::IoError(err)
    }
}

impl From<SystemTimeError> for Error {
    fn from(err: SystemTimeError) -> Error {
        Error::SystemTimeError(err)
    }
}

pub type Result<T> = std::result::Result<T, Error>;