rustberry 0.1.0

All-purpose Raspberry Pi library for Rust
Documentation
// Copyright (C) 2018  Adam Gausmann
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! Common error types used by the crate.

use std::error::Error as ErrorBase;
use std::fmt;
use std::io;

/// Types of errors returned by this crate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ErrorKind {

    /// The item requested has already been reserved.
    Reserved,

    /// The identifier given is invalid for this item type.
    OutOfRange,

    /// A critical I/O error occurred during this function call.
    IoError,

    /// The detected system is not supported by this crate.
    UnsupportedSystem,
}

impl fmt::Display for ErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ErrorKind::Reserved => f.write_str(
                "That item has already been reserved."
            ),
            ErrorKind::OutOfRange => f.write_str(
                "That identifier is out of range."
            ),
            ErrorKind::IoError => f.write_str(
                "An I/O error has occurred."
            ),
            ErrorKind::UnsupportedSystem => f.write_str(
                "The detected system is not supported by this crate."
            ),
        }
    }
}

/// Common error type returned by this crate.
#[derive(Debug)]
pub struct Error {
    kind: ErrorKind,
    cause: Option<Box<ErrorBase>>,
}

impl Error {
    pub(crate) fn new(kind: ErrorKind) -> Error {
        Error {
            kind,
            cause: None,
        }
    }

    pub(crate) fn with_cause<E>(kind: ErrorKind, cause: E) -> Error
    where
        E: ErrorBase + 'static,
    {
        Error {
            kind,
            cause: Some(Box::new(cause) as Box<ErrorBase>),
        }
    }

}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        <ErrorKind as fmt::Display>::fmt(&self.kind, f)
    }
}

impl ErrorBase for Error {
    fn cause(&self) -> Option<&ErrorBase> {
        self.cause.as_ref()
            .map(Box::as_ref)
    }
}

impl From<io::Error> for Error {
    fn from(e: io::Error) -> Error {
        Error::with_cause(ErrorKind::IoError, e)
    }
}