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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
use std::ops::DerefMut;
use std::ops::AddAssign;

#[derive(Clone, Debug)]
/// Raw chunk data.
pub struct SnapshotChunkData {
    /// Identifier of the chunk
    code: [u8; 4],
    /// Content of the chunk
    data: Vec<u8>,
}

#[allow(missing_docs)]
impl SnapshotChunkData {
    pub fn code(&self) -> &[u8; 4] {
        &(self.code)
    }

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

    pub fn size_as_array(&self) -> [u8; 4] {
        let mut size = self.size();
        let mut array = [0, 0, 0, 0];

        for item in &mut array {
            *item = (size % 256) as u8;
            size /= 256;
        }

        array
    }

    pub fn data(&self) -> &[u8] {
        &self.data
    }
}

#[derive(Clone, Debug)]
/// Memory chunk that superseeds the snapshot memory if any.
pub struct MemoryChunk {
    /// Raw content of the memory chunk (i.e. compressed version)
    pub(crate) data: SnapshotChunkData,
}

#[allow(missing_docs)]
impl MemoryChunk {
    /// Create a memory chunk.
    /// `code` identify with memory block is concerned
    /// `data` contains the crunched version of the code
    pub fn from(code: [u8; 4], data: Vec<u8>) -> Self {
        assert!(code[0] == b'M');
        assert!(code[1] == b'E');
        assert!(code[2] == b'M');
        assert!(code[3] == b'0' || 
                code[3] == b'1' || 
                code[3] == b'2' ||
                code[3] == b'3' ||
                code[3] == b'4' ||
                code[3] == b'5' ||
                code[3] == b'6' ||
                code[3] == b'7' ||
                code[3] == b'8' 
            );
        dbg!(code);
        Self {
            data: SnapshotChunkData { code, data },
        }
    }

    /// Build the memory chunk from the memory content. Chunk can be built in a compressed or uncompressed version
    pub fn build(code: [u8; 4], data: &[u8], compressed: bool) -> Self {
        assert_eq!(data.len(), 64*1024);
        let mut res = Vec::new();
     
        if !compressed {
            assert_eq!(data.len(), 64*1024);
            res.extend(data);
            assert_eq!(res.len(), data.len());
            res.resize(0x100000, 0);
        }
        else {

            let mut previous = None;
            let mut count = 0;

            for current in data.iter() {
                match previous {
                    None => {
                        previous = Some(*current);
                        count = 1;
                    },
                    Some(previous_value) => {
                        if *current == 0xe5 || previous_value != *current || count == 255 {
                            if previous.is_some() {
                                // previous value has been repeated several times
                                if count > 1 {
                                    res.push(0xe5);
                                    res.push(count);
                                }
                                res.push(previous_value); // store the value to be replaced
                            }

                            if *current == 0xe5 {
                                previous = None;
                                count = 0;
                                res.push(0xe5);
                                res.push(0);
                            }
                            else {
                                previous = Some(*current);
                                count = 1;
                            }
                        }
                        else{
                            assert_eq!(previous_value,*current);
                            count += 1;
                            previous = Some(*current);

                        }
                    }
                } // end match

            } // end for

            if previous.is_some() {
                // previous value has been repeated several times
                if count > 1 {
                    res.push(0xe5);
                    res.push(count);
                }
                res.push(previous.unwrap()); // store the value to be replaced
            }

        }

        Self::from(code, res)
    }

    /// Uncrunch the 64kbio of RLE crunched data if crunched. Otherwise, return the whole memory
    pub fn uncrunched_memory(&self) -> Vec<u8> {
        if self.is_crunched() {
            return self.data.data.clone()
        }

        let mut content = Vec::new();

        let idx = std::rc::Rc::new(std::cell::RefCell::new(0));
        let read_byte = || {
            let byte = self.data.data[*idx.borrow()];
            idx.borrow_mut().deref_mut().add_assign(1);
            byte
        };
        while *idx.borrow() != self.data.data.len() {
            match read_byte() {
                0xe5 => {
                    let amount = read_byte();
                    if amount == 0 {
                        content.push(0xe5)
                    }
                    else {
                        let val = read_byte();
                        for _idx in 0..amount { // TODO use resize
                            content.push(val);
                        }
                    }
                }
                val => {
                    content.push(val);
                }
            }
        }

        assert_eq!(content.len(), 64 * 1024);
        content
    }

     /// Returns the address in the memory array
    pub fn abstract_address(&self) -> usize {
        let nb = (self.data.code[3] - b'0') as usize;
        nb * 0x10000
    }

    /// A uncrunched memory taaks 64*1024 bytes
    pub fn is_crunched(&self) -> bool {
        self.data.data.len() == 64*1024
    }
}

#[derive(Clone, Debug)]
/// Unknwon kind of chunk
pub struct UnknownChunk {
    /// Raw data of the chunk
    data: SnapshotChunkData,
}

impl UnknownChunk {
    /// Generate the chunk from raw data
    pub fn from(code: [u8; 4], data: Vec<u8>) -> Self {
        Self {
            data: SnapshotChunkData { code, data },
        }
    }
}

/*
pub struct BreakpointChunk {
    pub fn from(code: [u8;4], content: Vec<u8>) -> Self {
        unimplemented!()
    }
}

pub struct InsertedDiscChunk {
    pub fn from(code: [u8;4], content: Vec<u8>) -> Self {
        unimplemented!()
    }
}

pub struct CPCPlusChunk {
    pub fn from(code: [u8;4], content: Vec<u8>) -> Self {
        unimplemented!()
    }
}
*/

#[derive(Clone, Debug)]
/// Represents any kind of chunks in order to manipulate them easily based on their semantic
pub enum SnapshotChunk {
    /// The chunk is a memory chunk
    Memory(MemoryChunk),
    /// The type of the chunk is unknown
    Unknown(UnknownChunk),
}

#[allow(missing_docs)]
impl SnapshotChunk {
    pub fn is_memory_chunk(&self) -> bool {
        self.memory_chunk().is_some()
    }

    pub fn memory_chunk(&self) -> Option<&MemoryChunk> {
        match self {
            SnapshotChunk::Memory(ref mem) => Some(mem),
            _ => None,
        }
    }

    /// Provides the code of the chunk
    pub fn code(&self) -> &[u8; 4] {
        match self {
            SnapshotChunk::Memory(ref chunk) => chunk.data.code(),

            SnapshotChunk::Unknown(ref chunk) => chunk.data.code(),
        }
    }

    pub fn size(&self) -> usize {
        match self {
            SnapshotChunk::Memory(ref chunk) => chunk.data.size(),

            SnapshotChunk::Unknown(ref chunk) => chunk.data.size(),
        }
    }

    pub fn size_as_array(&self) -> [u8; 4] {
        match self {
            SnapshotChunk::Memory(ref chunk) => chunk.data.size_as_array(),

            SnapshotChunk::Unknown(ref chunk) => chunk.data.size_as_array(),
        }
    }

    pub fn data(&self) -> &[u8] {
        match self {
            SnapshotChunk::Memory(ref chunk) => chunk.data.data(),

            SnapshotChunk::Unknown(ref chunk) => chunk.data.data(),
        }
    }
}

impl From<MemoryChunk> for SnapshotChunk {
    fn from(chunk: MemoryChunk) -> Self {
        SnapshotChunk::Memory(chunk)
    }
}

impl From<UnknownChunk> for SnapshotChunk {
    fn from(chunk: UnknownChunk) -> Self {
        SnapshotChunk::Unknown(chunk)
	}
}