hack_asm/
hack_int.rs

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
49
50
51
52
53
54
55
use thiserror::Error;

/// A HackInt is an integer between 0 and 32767 (inclusive).
/// So technically a u16 is one bit larger but it is an in-built type we can use.
/// However, a HackInt shall always be inside of the aforementioned bounds.
/// We assure the correctness of this by checking the user input inside of the parser.
#[derive(PartialEq, PartialOrd, Copy, Clone)]
pub struct HackInt(u16);

#[derive(Error, Debug)]
pub enum ParseHackIntError {
    #[error("number is not in bounds")]
    SizeExceeded,
    #[error("could not parse int")]
    ParseInt(#[from] std::num::ParseIntError),
}

impl HackInt {
    const MAX: u16 = 32767;

    pub fn try_new(value: u16) -> Result<Self, ParseHackIntError> {
        if value > Self::MAX {
            return Err(ParseHackIntError::SizeExceeded);
        }

        Ok(Self(value))
    }

    pub fn parse(input: &str) -> Result<Self, ParseHackIntError> {
        let value: u16 = input.parse()?;
        Self::try_new(value)
    }

    pub const fn new_unchecked(value: u16) -> HackInt {
        Self(value)
    }

    pub fn inc_unchecked(&mut self) {
        self.0 += 1;
    }
}

impl From<HackInt> for u16 {
    fn from(hack_int: HackInt) -> Self {
        hack_int.0
    }
}

impl TryInto<HackInt> for u16 {
    type Error = ParseHackIntError;

    fn try_into(self) -> Result<HackInt, Self::Error> {
        HackInt::try_new(self)
    }
}