summaryrefslogtreecommitdiff
path: root/src/types/word_template.rs
blob: 33d59333600cbdb206afdce64a769e761b5cdcba (plain) (blame)
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
use crate::*;


pub struct WordTemplate {
    pub value: usize,
    /// Width of the word in bits.
    pub width: u32,
    pub fields: Vec<Tracked<BitField>>,
}

pub struct BitField {
    pub name: char,
    /// Width of the field in bits.
    pub width: u32,
    /// Number of bits to the right of the field in the word.
    pub shift: u32,
}


impl std::fmt::Display for WordTemplate {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        if self.value == 0 {
            write!(f, "0")?;
        } else {
            let bitcount = (self.value.ilog2() + 1) as usize;
            'bit: for i in (0..bitcount).rev() {
                let is_first_bit = i+1 == bitcount;
                if !is_first_bit && (i+1) % 4 == 0 {
                    write!(f, "_")?;
                }
                for field in &self.fields {
                    let i = i as u32;
                    if i <= field.width + field.shift - 1 && i >= field.shift {
                        write!(f, "{}", field.name)?;
                        continue 'bit;
                    }
                }
                match (self.value >> i) & 1 {
                    0 => write!(f, "0")?,
                    _ => write!(f, "1")?,
                }
            }
        }
        return Ok(());
    }
}