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
// Copyright 2021, Benjamin Ludewig
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::ffi::NulError;
use std::fmt::{Debug, Display, Formatter};
use std::option::Option::None;
use std::str::Utf8Error;

#[derive(Debug, Clone)]
pub enum Error {
    Message(String),
    Utf8Error(Utf8Error),
    NulError(NulError),
}

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

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

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

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::Message(_) => None,
            Error::Utf8Error(err) => Some(err),
            Error::NulError(err) => Some(err),
        }
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::Message(msg) => Display::fmt(msg, f),
            Error::Utf8Error(err) => Display::fmt(err, f),
            Error::NulError(err) => Display::fmt(err, f),
        }
    }
}