aboutsummaryrefslogtreecommitdiff
path: root/lib/xixanta/src/mapping.rs
blob: c097fd8ba80d5aff3d5214fe19da1bf07b680eea (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
61
62
63
64
65
66
use crate::instruction::{Fill, Node, PString};
use std::collections::HashMap;

use crate::errors::ParseError;
type Result<T> = std::result::Result<T, ParseError>;

#[derive(Debug, Clone, Eq, Ord, PartialEq, PartialOrd)]
pub struct Segment {
    pub name: String,
    pub start: u16,
    pub size: usize,
    pub fill_value: Option<Fill>,
}

#[derive(Debug)]
pub struct Mapping {
    pub segments: Vec<Segment>,
    pub nodes: HashMap<String, Vec<Node>>,
    pub current: String,
}

impl Mapping {
    pub fn new(mut segments: Vec<Segment>) -> Self {
        segments.sort_by(|a, b| b.start.cmp(&a.start));

        let mut nodes = HashMap::new();
        for segment in segments.iter() {
            nodes.insert(segment.name.clone(), vec![]);
        }

        let current_segment = &segments.first().unwrap().name.clone();

        Mapping {
            segments,
            nodes,
            current: current_segment.to_string(),
        }
    }

    pub fn reset(&mut self) {
        // TODO
    }

    pub fn switch(&mut self, id: &PString) -> Result<()> {
        if !self.nodes.contains_key(&id.value) {
            return Err(
                id.parser_error(format!("segment '{}' has not been defined", id.value).as_str())
            );
        }

        id.value.clone_into(&mut self.current);
        Ok(())
    }

    pub fn current(&self) -> &Vec<Node> {
        self.nodes.get(&self.current).unwrap()
    }

    pub fn current_mut(&mut self) -> &mut Vec<Node> {
        self.nodes.get_mut(&self.current).unwrap()
    }

    pub fn push(&mut self, node: Node) {
        self.nodes.get_mut(&self.current).unwrap().push(node);
    }
}