Skip to main content

mylib/bytes/
fourbit.rs

1use super::Signal;
2use std::str::FromStr;
3
4#[derive(Debug, PartialEq)]
5pub struct FourBit {
6    pub bit1: Signal,
7    pub bit2: Signal,
8    pub bit3: Signal,
9    pub bit4: Signal,
10}
11
12impl FourBit {
13    pub fn convert(&self) -> i32 {
14        let mut number = 0;
15        if self.bit1 == Signal::One {
16            number += 8;
17        }
18        if self.bit2 == Signal::One {
19            number += 4;
20        }
21        if self.bit3 == Signal::One {
22            number += 2;
23        }
24        if self.bit4 == Signal::One {
25            number += 1;
26        }
27
28        number
29    }
30}
31
32#[derive(Debug)]
33pub struct ParseFourBitError;
34
35impl std::fmt::Display for ParseFourBitError {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        write!(f, "ERROR: Cannot parse given string to a Four Bit")
38    }
39}
40
41impl std::error::Error for ParseFourBitError {}
42
43impl FromStr for FourBit {
44    type Err = ParseFourBitError;
45
46    fn from_str(s: &str) -> Result<Self, Self::Err> {
47        let mut byte = FourBit {
48            bit1: Signal::Zero,
49            bit2: Signal::Zero,
50            bit3: Signal::Zero,
51            bit4: Signal::Zero,
52        };
53
54        if s.len() != 4 {
55            return Err(ParseFourBitError);
56        }
57
58        for (i, c) in s.chars().enumerate() {
59            match c {
60                '1' => {
61                    if i == 0 {
62                        byte.bit1 = Signal::One;
63                    } else if i == 1 {
64                        byte.bit2 = Signal::One;
65                    } else if i == 2 {
66                        byte.bit3 = Signal::One;
67                    } else if i == 3 {
68                        byte.bit4 = Signal::One;
69                    }
70                }
71                '0' => {
72                    if i == 0 {
73                        byte.bit1 = Signal::Zero;
74                    } else if i == 1 {
75                        byte.bit2 = Signal::Zero;
76                    } else if i == 2 {
77                        byte.bit3 = Signal::Zero;
78                    } else if i == 3 {
79                        byte.bit4 = Signal::Zero;
80                    }
81                }
82                _ => (),
83            }
84        }
85
86        Ok(byte)
87    }
88}