summaryrefslogtreecommitdiffstats
path: root/src/hex/byte.rs
blob: 6337590495141ded8e1574c0d13a3ffac2b44092 (plain)
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
56
57
58
59
60
use {
    crate::{
        skin::StyleMap,
    },
    termimad::CompoundStyle,
};

pub enum ByteCategory {
    Null,
    AsciiGraphic,
    AsciiWhitespace,
    AsciiOther,
    NonAscii,
}

#[derive(Clone, Copy)]
pub struct Byte(u8);

impl From<u8> for Byte {
    fn from(u: u8) -> Self {
        Self(u)
    }
}

impl Byte {
    pub fn category(self) -> ByteCategory {
        if self.0 == 0x00 {
            ByteCategory::Null
        } else if self.0.is_ascii_graphic() {
            ByteCategory::AsciiGraphic
        } else if self.0.is_ascii_whitespace() {
            ByteCategory::AsciiWhitespace
        } else if self.0.is_ascii() {
            ByteCategory::AsciiOther
        } else {
            ByteCategory::NonAscii
        }
    }

    pub fn style(self, styles: &StyleMap) -> &CompoundStyle {
        match self.category() {
            ByteCategory::Null => &styles.hex_null,
            ByteCategory::AsciiGraphic => &styles.hex_ascii_graphic,
            ByteCategory::AsciiWhitespace => &styles.hex_ascii_whitespace,
            ByteCategory::AsciiOther => &styles.hex_ascii_other,
            ByteCategory::NonAscii => &styles.hex_non_ascii,
        }
    }

    pub fn as_char(self) -> char {
        match self.category() {
            ByteCategory::Null => '0',
            ByteCategory::AsciiGraphic => self.0 as char,
            ByteCategory::AsciiWhitespace if self.0 == 0x20 => ' ',
            ByteCategory::AsciiWhitespace => '_',
            ByteCategory::AsciiOther => '•',
            ByteCategory::NonAscii => '×',
        }
    }
}