cfd16-lib-impl 0.7.0

Holds the trait Codeable for cfd16-lib, allowing the definition of a proc-macro.
Documentation
//! Holds the trait Codeable for cfd16-lib, allowing the definition
//! of a proc-macro.

#![warn(missing_docs)]

use std::{error, fmt, str};

/// Error that may occur when parsing a Mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParseModeError {}

impl fmt::Display for ParseModeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Error Parsing a CFD-16 Execution Mode.")
    }
}

impl error::Error for ParseModeError {}

/// Processor's current mode of execution.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Mode {
    /// Unpriviledged mode of execution without direct access to system
    /// registers required for more complex (and unsafe) operations.
    User,

    /// Priviledged mode of execution used mostly for interrupt service
    /// routines and Operating Systems.
    Kernel,
}

impl fmt::Display for Mode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Mode::User => write!(f, "User"),
            Mode::Kernel => write!(f, "Kernel"),
        }
    }
}

impl str::FromStr for Mode {
    type Err = ParseModeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "user" => Ok(Mode::User),
            "kernel" => Ok(Mode::Kernel),
            _ => Err(Self::Err {}),
        }
    }
}

/// Trait which allows for the encoding and decoding of instructions and
/// portions thereof. This trait can only be implemented if it is
/// impossible for the encoding of the implementing type to fail.
pub trait Codable
where
    Self: Sized,
{
    /// Encodes the instruction or portion thereof.
    fn encode(&self) -> u16;

    /// Decodes the instruction given the current mode of execution.
    fn decode(value: u16, mode: Mode) -> Option<Self>;
}