summaryrefslogtreecommitdiff
path: root/src/formats/raw.rs
blob: ecc647332d49276e9d87faf98ad2ba8d9adb72b0 (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
use crate::*;


pub fn format_raw(segments: &[Segment], width: Option<u32>) -> Result<Vec<u8>, FormatError> {
    let Some(width) = width.or_else(|| calculate_fixed_width(&segments)) else {
        return Err(FormatError::ExpectedFixedWidth);
    };

    let mut address = 0;
    let bytes_per_word = ((width + 7) / 8) as usize;
    let mut bytes = Vec::new();

    for segment in segments {
        // Pad to the segment start address.
        let padding = segment.address.saturating_sub(address);
        bytes.resize(bytes.len() + (padding * bytes_per_word), 0);
        for word in &segment.words {
            // Decompose word value into bytes.
            let value = word.value.value;
            for i in (0..bytes_per_word).rev() {
                let byte = (value >> (i*8) & 0xff) as u8;
                bytes.push(byte);
            }
            address += 1;
        }
    }

    return Ok(bytes);
}