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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
use delegate::delegate;

#[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
    }

    pub fn add_bytes(&mut self, data: &[u8]) {
        self.data.extend_from_slice(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 {
    delegate! {
        to self.data {
        pub fn code(&self) -> &[u8; 4];
            pub fn size(&self) -> usize;
            pub fn size_as_array(&self) -> [u8; 4];
            pub fn data(&self) -> &[u8];
        }
    }

    pub fn print_info(&self) {
        println!(
            "\t* Address: 0x{:X}\n\t* Size: 0x{:X}",
            self.abstract_address(),
            self.uncrunched_memory().len()
        );
    }

    /// 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'
        );
        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);
            Self::from(code, res)
        }
        else {
            let mut previous = None;
            let mut count = 0;

            let mut rle = |previous_value, count| {
                if count == 1 {
                    if previous_value == 0xE5 {
                        res.push(0xE5);
                        res.push(0x00);
                    }
                    else {
                        res.push(previous_value);
                    }
                }
                else if count == 2 && previous_value != 0xE5 {
                    res.push(previous_value);
                    res.push(previous_value);
                }
                else {
                    res.push(0xE5);
                    res.push(count);
                    res.push(previous_value);
                }
            };

            for current in data.iter() {
                let current = *current;
                match previous {
                    None => {
                        previous.replace(current);
                        count = 1;
                    }
                    Some(previous_value) => {
                        // we stop when 255 are read or when current differs
                        if previous_value != current || count == 255 {
                            rle(previous_value, count);

                            previous.replace(current);
                            count = 1;
                        }
                        else {
                            count += 1;
                        }
                    }
                } // end match
            } // end for

            if count > 0 {
                rle(previous.unwrap(), count);
            }

            // We may be unable to crunch the memory
            if res.len() >= 65536 {
                return Self::from(code, data.to_vec());
            }

            let chunk = Self::from(code, res.clone());

            // #[cfg(debug_assertions)]
            {
                let produced = chunk.uncrunched_memory();
                assert_eq!(&data, &produced);
            }

            chunk
        }
    }

    /// 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 mut idx = 0;
        let data = &self.data.data;
        let mut read_byte = move || {
            if idx == self.data.data.len() {
                None
            }
            else {
                let byte = data[idx];
                idx += 1;
                Some(byte)
            }
        };
        while let Some(byte) = read_byte() {
            match byte {
                0xE5 => {
                    let amount = read_byte().unwrap();
                    if amount == 0 {
                        content.push(0xE5)
                    }
                    else {
                        let val = read_byte().unwrap();
                        content.reserve(content.len() + amount as usize);
                        for _idx in 0..amount {
                            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)]
pub struct WinapeBreakPointChunk {
    data: SnapshotChunkData
}

impl WinapeBreakPointChunk {
    delegate! {
        to self.data {
        pub fn code(&self) -> &[u8; 4];
        pub fn size(&self) -> usize;
            pub fn size_as_array(&self) -> [u8; 4];
            pub fn data(&self) -> &[u8];
            pub fn add_bytes(&mut self, data: &[u8]);

        }
    }

    pub fn from(code: [u8; 4], content: Vec<u8>) -> Self {
        assert_eq!(code[0], b'B');
        assert_eq!(code[1], b'R');
        assert_eq!(code[2], b'K');
        assert_eq!(code[3], b'S');

        Self {
            data: SnapshotChunkData {
                code,
                data: content
            }
        }
    }

    pub fn add_breakpoint_raw(&mut self, raw: &[u8]) {
        assert!(raw.len() == 5);
        self.add_bytes(raw);
    }

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

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

impl UnknownChunk {
    delegate! {
        to self.data {
        pub fn code(&self) -> &[u8; 4];
            pub fn size(&self) -> usize;
            pub fn size_as_array(&self) -> [u8; 4];
            pub fn data(&self) -> &[u8];
        }
    }

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

// 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 chunk is a breakpoint chunk for winape emulator
    WinapeBreakPoint(WinapeBreakPointChunk),
    /// The type of the chunk is unknown
    Unknown(UnknownChunk)
}

#[allow(missing_docs)]
impl SnapshotChunk {
    pub fn print_info(&self) {
        println!(
            "- Chunk: {}{}{}{}",
            self.code()[0] as char,
            self.code()[1] as char,
            self.code()[2] as char,
            self.code()[3] as char,
        );

        if self.is_memory_chunk() {
            self.memory_chunk().unwrap().print_info();
        }
    }

    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(chunk) => chunk.code(),
            SnapshotChunk::Unknown(chunk) => chunk.code(),
            SnapshotChunk::WinapeBreakPoint(chunk) => chunk.code()
        }
    }

    pub fn size(&self) -> usize {
        match self {
            SnapshotChunk::Memory(chunk) => chunk.size(),
            SnapshotChunk::WinapeBreakPoint(chunk) => chunk.size(),
            SnapshotChunk::Unknown(chunk) => chunk.size()
        }
    }

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

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

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

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

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