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
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
use sdna::SDNA;
use utils;
use std::fmt::{Display, Formatter, Error};
use std::collections::HashMap;
// use fxhash::FxHashMap as HashMap;

#[derive(Debug, Clone)]
pub struct Field{
    type_idx: u16,
    name_idx: u16,
    lookup_name: String,
    name: String,
    type_name: String,
    size: usize,
    array_sizes: Vec<usize>,
    indirection_level: usize,
}

impl Field{
    fn new(type_idx: u16, name_idx: u16, dna: &SDNA) -> Field{
        let type_name = dna.type_name(type_idx);
        let name = dna.name(name_idx);
        let mut array_sizes = vec![];

        let type_size =
            if name.starts_with("*"){
                dna.pointer_bytes()
            }else{
                dna.size_of_type_idx(type_idx) as usize
            };
        let size = if name.ends_with("]"){
            array_sizes = name.split(|c| c==']' || c=='[')
                .filter_map(|part| match part.parse::<usize>(){
                    Ok(dim) => Some(dim),
                    _ => None
                }).collect();
            let total_array_size: usize = array_sizes.iter().fold(1,|acc, size| acc * size);
            type_size * total_array_size
        }else{
            type_size
        };

        let mut indirection_level = 0;
        let mut lookup_name = name.to_string();
        if name.starts_with("*"){
            indirection_level = lookup_name.chars().take_while(|c| *c=='*').count();
            lookup_name = lookup_name[indirection_level..].to_string();
        }
        if name.ends_with("]"){
            let opening_bracket = lookup_name.find('[').unwrap();
            lookup_name = lookup_name.split_at(opening_bracket).0.to_string()
        }

        Field{
            type_idx: type_idx,
            name_idx: name_idx,
            lookup_name: lookup_name,
            name: name.to_string(),
            type_name: type_name.to_string(),
            size: size,
            array_sizes: array_sizes,
            indirection_level: indirection_level,
        }
    }

    pub fn type_name(&self) -> &str{
        &self.type_name
    }

    pub fn name(&self) -> &str{
        &self.lookup_name
    }

    pub fn type_idx(&self) -> u16{
        self.type_idx
    }

    pub fn size(&self) -> usize{
        self.size
    }

    pub fn is_ptr(&self) -> bool{
        self.name.starts_with("*")
    }

    pub fn is_array(&self) -> bool{
        self.name.ends_with("]")
    }

    pub fn array_sizes(&self) -> &Vec<usize>{
        &self.array_sizes
    }

    pub fn total_array_size(&self) -> usize{
        if self.array_sizes.is_empty(){
            0
        }else{
            self.array_sizes.iter().fold(1,|acc, size| acc * size)
        }
    }

    pub fn dim(&self) -> usize{
        self.array_sizes.len()
    }

    pub fn indirection_level(&self) -> usize{
        self.indirection_level
    }
}

#[derive(Debug, Clone)]
pub struct Structure{
    type_idx: u16,
    fields: Vec<Field>,
    name: String,
    size: usize,
    field_index: HashMap<String, usize>,
}

impl Structure{
    pub fn new(data: &[u8], dna: &SDNA) -> Structure{
        let mut chunks = data.chunks(2);
        let type_idx = utils::read_u16(chunks.next().unwrap(), dna.endianness());
        let num_fields = utils::read_u16(chunks.next().unwrap(), dna.endianness());

        let (field_index, fields) = (0..num_fields).map(|f|{
            let field_type = utils::read_u16(chunks.next().unwrap(), dna.endianness());
            let field_name = utils::read_u16(chunks.next().unwrap(), dna.endianness());
            let field = Field::new(field_type, field_name, dna);
            ((field.name().to_string(), f as usize), field)
        }).unzip();

        Structure{
            type_idx: type_idx,
            name: dna.type_name(type_idx).to_string(),
            size: dna.size_of_type_idx(type_idx) as usize,
            fields: fields,
            field_index: field_index,
        }
    }

    pub fn name(&self) -> &str{
        &self.name
    }

    pub fn size(&self) -> usize{
        self.size
    }

    pub fn type_idx(&self) -> u16{
        self.type_idx
    }

    pub fn fields(&self) -> &[Field]{
        &self.fields
    }

    pub fn field(&self, name: &str) -> Option<&Field>{
        match self.field_index.get(name){
            Some(&idx) => Some(&self.fields[idx]),
            None => None
        }
    }

    pub fn field_offset(&self, field_name: &str) -> Option<usize>{
        match self.field_index.get(field_name){
            Some(&pos) => Some(self.fields.iter().take(pos).fold(0, |acc, field| acc + field.size())),
            None => None
        }
    }
}

impl Display for Structure{
     fn fmt(&self, f: &mut Formatter) -> Result<(), Error>{
        write!(f, "{} {}\n", self.name, "{")?;
        for field in self.fields.iter(){
            write!(f, "\t{} {};\n", field.type_name, field.name)?;
        }
        write!(f, "{};\n","}")
    }
}