cfd16_lib_impl/
lib.rs

1//! Holds the trait Codeable for cfd16-lib, allowing the definition
2//! of a proc-macro.
3
4#![warn(missing_docs)]
5
6use std::{error, fmt, str};
7
8/// Error that may occur when parsing a Mode.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub struct ParseModeError {}
11
12impl fmt::Display for ParseModeError {
13    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
14        write!(f, "Error Parsing a CFD-16 Execution Mode.")
15    }
16}
17
18impl error::Error for ParseModeError {}
19
20/// Processor's current mode of execution.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
22pub enum Mode {
23    /// Unpriviledged mode of execution without direct access to system
24    /// registers required for more complex (and unsafe) operations.
25    User,
26
27    /// Priviledged mode of execution used mostly for interrupt service
28    /// routines and Operating Systems.
29    Kernel,
30}
31
32impl fmt::Display for Mode {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match self {
35            Mode::User => write!(f, "User"),
36            Mode::Kernel => write!(f, "Kernel"),
37        }
38    }
39}
40
41impl str::FromStr for Mode {
42    type Err = ParseModeError;
43
44    fn from_str(s: &str) -> Result<Self, Self::Err> {
45        match s.to_lowercase().as_str() {
46            "user" => Ok(Mode::User),
47            "kernel" => Ok(Mode::Kernel),
48            _ => Err(Self::Err {}),
49        }
50    }
51}
52
53/// Trait which allows for the encoding and decoding of instructions and
54/// portions thereof. This trait can only be implemented if it is
55/// impossible for the encoding of the implementing type to fail.
56pub trait Codable
57where
58    Self: Sized,
59{
60    /// Encodes the instruction or portion thereof.
61    fn encode(&self) -> u16;
62
63    /// Decodes the instruction given the current mode of execution.
64    fn decode(value: u16, mode: Mode) -> Option<Self>;
65}