badcontext 0.1.0

A small crate for creating Context structs that contain application components
Documentation
use std::any::{type_name, TypeId};
use std::cell::{BorrowError, BorrowMutError};
use std::fmt::{Debug, Formatter, Result};

#[derive(Debug)]
pub enum Error {
    AlreadyRegistered(AlreadyRegisteredError),
    NotRegistered(NotRegisteredError),
    BorrowedMutably(BorrowError),
    Borrowed(BorrowMutError),
    General(String),
}

pub struct AlreadyRegisteredError(TypeId, &'static str);

impl AlreadyRegisteredError {
    pub fn of_type<T: 'static>() -> Self {
        AlreadyRegisteredError(TypeId::of::<T>(), type_name::<T>())
    }

    pub fn get_msg(&self) -> String {
        format!("Element of type {} already registered", self.1)
    }

    pub fn get_type_name(&self) -> &'static str {
        self.1
    }

    pub fn get_type_id(&self) -> &TypeId {
        &self.0
    }
}

impl Debug for AlreadyRegisteredError {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.write_str(&self.get_msg())
    }
}

pub struct NotRegisteredError(TypeId, &'static str);

impl NotRegisteredError {
    pub fn of_type<T: 'static>() -> Self {
        NotRegisteredError(TypeId::of::<T>(), type_name::<T>())
    }

    pub fn get_msg(&self) -> String {
        format!("Element of type {} not registered", self.1)
    }

    pub fn get_type_name(&self) -> &'static str {
        self.1
    }

    pub fn get_type_id(&self) -> &TypeId {
        &self.0
    }
}

impl Debug for NotRegisteredError {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.write_str(&self.get_msg())
    }
}