refpack 2.0.0

A crate providing compression/decompression for the RefPack compression format, utilized by many early 2000s EA games
Documentation
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
////////////////////////////////////////////////////////////////////////////////
// This Source Code Form is subject to the terms of the Mozilla Public         /
// License, v. 2.0. If a copy of the MPL was not distributed with this         /
// file, You can obtain one at https://mozilla.org/MPL/2.0/.                   /
//                                                                             /
////////////////////////////////////////////////////////////////////////////////

//! control codes utilized by compression and decompression

pub(crate) mod iterator;
pub mod mode;

use std::io::{Read, Seek, Write};

#[cfg(test)]
use proptest::collection::{size_range, vec};
#[cfg(test)]
use proptest::prelude::*;

pub use crate::data::control::mode::Mode;
use crate::{RefPackError, RefPackResult};

/// The instruction part of a control block that dictates to the compression algorithm what
/// operations should be executed to decompress
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Command {
    /// Represents a two byte copy command
    Short {
        offset: u16,
        length: u8,
        literal: u8,
    },
    /// Represents a three byte copy command
    Medium {
        offset: u16,
        length: u8,
        literal: u8,
    },
    /// Represents a four byte copy command
    Long {
        offset: u32,
        length: u16,
        literal: u8,
    },
    /// Represents exclusively writing literal bytes from the stream
    ///
    /// u8: number of literal bytes following the command to write to the stream
    Literal(u8),
    /// Represents an end of stream, when this command is encountered during decompression it's
    /// evaluated and then decompression halts
    ///
    /// u8: Number of literal bytes to write to the stream before ending decompression
    Stop(u8),
}

impl Command {
    /// Create a new copy type `Command` struct.
    /// # Panics
    /// Panics if you attempt to create an invalid Command in some way
    #[must_use]
    pub fn new<M: Mode>(offset: usize, length: usize, literal: usize) -> Self {
        assert!(
            literal <= M::SIZES.copy_literal_max() as usize,
            "Literal length must be less than or equal to {} for commands ({})",
            M::SIZES.copy_literal_max(),
            literal
        );

        if offset > M::SIZES.long_offset_max() as usize
            || length > M::SIZES.long_length_max() as usize
        {
            panic!(
                "Invalid offset or length (Maximum offset {}, got {}) (Maximum length {}, got {})",
                M::SIZES.long_offset_max(),
                offset,
                M::SIZES.long_length_max(),
                length
            );
        } else if offset > M::SIZES.medium_offset_max() as usize
            || length > M::SIZES.medium_length_max() as usize
        {
            assert!(
                length >= M::SIZES.long_length_min() as usize,
                "Length must be greater than or equal to {} for long commands (Length: {}) (Offset: {})",
                M::SIZES.long_length_min(),
                length,
                offset
            );
            Self::Long {
                offset: offset as u32,
                length: length as u16,
                literal: literal as u8,
            }
        } else if offset > M::SIZES.short_offset_max() as usize
            || length > M::SIZES.short_length_max() as usize
        {
            assert!(
                length >= M::SIZES.medium_length_min() as usize,
                "Length must be greater than or equal to {} for medium commands (Length: {}) (Offset: {})",
                M::SIZES.medium_length_min(),
                length,
                offset
            );
            Self::Medium {
                offset: offset as u16,
                length: length as u8,
                literal: literal as u8,
            }
        } else {
            Self::Short {
                offset: offset as u16,
                length: length as u8,
                literal: literal as u8,
            }
        }
    }

    /// Creates a new literal command block
    /// # Panics
    /// Panics if you attempt to create too long of a literal command. This depends on control mode
    /// used.
    #[must_use]
    pub fn new_literal<M: Mode>(length: usize) -> Self {
        assert!(
            length <= M::SIZES.literal_max() as usize,
            "Literal received too long of a literal length (max {}, got {})",
            M::SIZES.literal_max(),
            length
        );
        Self::Literal(length as u8)
    }

    /// Creates a new stopcode command block
    /// # Panics
    /// Panics if you attempt to create too long of a stop code. This depends on control mode used.
    #[must_use]
    pub fn new_stop<M: Mode>(literal_length: usize) -> Self {
        assert!(
            literal_length <= 3,
            "Stopcode recieved too long of a literal length (max {}, got {})",
            M::SIZES.copy_literal_max(),
            literal_length
        );
        Self::Stop(literal_length as u8)
    }

    /// Get number of literal bytes on the command, if they have any
    /// Returns `None` if the length is 0
    #[must_use]
    pub fn num_of_literal(self) -> Option<usize> {
        match self {
            Command::Short { literal, .. }
            | Command::Medium { literal, .. }
            | Command::Long { literal, .. } => {
                if literal == 0 {
                    None
                } else {
                    Some(literal as usize)
                }
            }
            Command::Literal(number) => Some(number as usize),
            Command::Stop(number) => {
                if number == 0 {
                    None
                } else {
                    Some(number as usize)
                }
            }
        }
    }

    /// Get the offset and length of a copy command as a `(usize, usize)` tuple.
    ///
    /// Returns `None` if `self` is not a copy command.
    #[must_use]
    pub fn offset_copy(self) -> Option<(usize, usize)> {
        match self {
            Command::Short { offset, length, .. } | Command::Medium { offset, length, .. } => {
                Some((offset as usize, length as usize))
            }
            Command::Long { offset, length, .. } => Some((offset as usize, length as usize)),
            _ => None,
        }
    }

    /// Returns true if the command is a stopcode, false if it is not.
    #[must_use]
    pub fn is_stop(self) -> bool {
        matches!(self, Command::Stop(_))
    }

    /// Reads and decodes a command from a `Read + Seek` reader.
    /// # Errors
    /// Returns [RefPackError::Io](crate::RefPackError::Io) if a generic IO Error occurs while
    /// attempting to read data
    pub fn read<M: Mode>(reader: &mut (impl Read + Seek)) -> RefPackResult<Self> {
        M::read(reader)
    }

    /// Encodes and writes a command to a `Write + Seek` writer
    /// # Errors
    /// Returns [RefPackError::Io](crate::RefPackError::Io) if a generic IO Error occurs while
    /// attempting to write data
    pub fn write<M: Mode>(self, writer: &mut (impl Write + Seek)) -> RefPackResult<()> {
        M::write(self, writer)?;
        Ok(())
    }
}

#[cfg(test)]
prop_compose! {
    fn bytes_strategy(
        length: usize,
    )(
        vec in vec(any::<u8>(), size_range(length)),
    ) -> Vec<u8> {
        vec
    }
}

/// Full control block of command + literal bytes following it
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Control {
    /// The command code
    pub command: Command,
    /// the literal bytes to write to the stream
    pub bytes: Vec<u8>,
}

impl Control {
    /// Create a new Control given a command and bytes
    #[must_use]
    pub fn new(command: Command, bytes: Vec<u8>) -> Self {
        Self { command, bytes }
    }

    /// Create a new literal block given a slice of bytes.
    /// the `Command` is automatically generated from the length of the byte slice.
    #[must_use]
    pub fn new_literal_block<M: Mode>(bytes: &[u8]) -> Self {
        Self {
            command: Command::new_literal::<M>(bytes.len()),
            bytes: bytes.to_vec(),
        }
    }

    /// Create a new stop control block given a slice of bytes
    /// the `Command` is automatically generated from the length of the byte slice.
    #[must_use]
    pub fn new_stop<M: Mode>(bytes: &[u8]) -> Self {
        Self {
            command: Command::new_stop::<M>(bytes.len()),
            bytes: bytes.to_vec(),
        }
    }

    /// Reads and decodes a control block from a `Read + Seek` reader
    /// # Errors
    /// Returns [RefPackError::Io](crate::RefPackError::Io) if a generic IO Error occurs while
    /// attempting to read data
    pub fn read<M: Mode>(reader: &mut (impl Read + Seek)) -> Result<Self, RefPackError> {
        let command = Command::read::<M>(reader)?;
        let mut buf = vec![0u8; command.num_of_literal().unwrap_or(0)];
        reader.read_exact(&mut buf)?;
        Ok(Control {
            command,
            bytes: buf,
        })
    }

    /// Encodes and writes a control block to a `Write + Seek` writer
    /// # Errors
    /// Returns [RefPackError::Io](crate::RefPackError::Io) if a generic IO Error occurs while
    /// attempting to write data
    pub fn write<M: Mode>(&self, writer: &mut (impl Write + Seek)) -> Result<(), RefPackError> {
        self.command.write::<M>(writer)?;
        writer.write_all(&self.bytes)?;
        Ok(())
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use std::io::{Cursor, SeekFrom};

    use test_strategy::proptest;

    use super::*;
    use crate::data::control::mode::Reference;

    pub fn generate_random_valid_command<M: Mode>() -> BoxedStrategy<Command> {
        let sizes = M::SIZES;
        let short_copy_strat = (
            sizes.short_offset_min()..=sizes.short_offset_max(),
            sizes.short_length_min()..=sizes.short_length_max(),
            sizes.copy_literal_min()..=sizes.copy_literal_max(),
        )
            .prop_map(|(offset, length, literal)| Command::Short {
                offset,
                length,
                literal,
            });

        let medium_copy_strat = (
            sizes.medium_offset_min()..=sizes.medium_offset_max(),
            sizes.medium_length_min()..=sizes.medium_length_max(),
            sizes.copy_literal_min()..=sizes.copy_literal_max(),
        )
            .prop_map(|(offset, length, literal)| Command::Medium {
                offset,
                length,
                literal,
            });

        let long_copy_strat = (
            sizes.long_offset_min()..=sizes.long_offset_max(),
            sizes.long_length_min()..=sizes.long_length_max(),
            sizes.copy_literal_min()..=sizes.copy_literal_max(),
        )
            .prop_map(|(offset, length, literal)| Command::Long {
                offset,
                length,
                literal,
            });

        let literal_strat = sizes.literal_effective_min()..=sizes.literal_effective_max();
        let literal =
            Strategy::prop_map(literal_strat, |literal| Command::Literal((literal * 4) + 4));
        prop_oneof![
            short_copy_strat,
            medium_copy_strat,
            long_copy_strat,
            literal
        ]
        .boxed()
    }

    pub fn generate_stopcode<M: Mode>() -> BoxedStrategy<Command> {
        let sizes = M::SIZES;

        (sizes.copy_literal_min()..=sizes.copy_literal_max())
            .prop_map(Command::Stop)
            .boxed()
    }

    pub fn generate_control<M: Mode>() -> BoxedStrategy<Control> {
        generate_random_valid_command::<M>()
            .prop_flat_map(|command| {
                (
                    Just(command),
                    vec(any::<u8>(), command.num_of_literal().unwrap_or(0)),
                )
            })
            .prop_map(|(command, bytes)| Control { command, bytes })
            .boxed()
    }

    pub fn generate_stop_control<M: Mode>() -> BoxedStrategy<Control> {
        generate_stopcode::<M>()
            .prop_flat_map(|command| {
                (
                    Just(command),
                    vec(any::<u8>(), command.num_of_literal().unwrap_or(0)),
                )
            })
            .prop_map(|(command, bytes)| Control { command, bytes })
            .boxed()
    }

    pub fn generate_valid_control_sequence<M: Mode>(
        max_length: usize,
    ) -> BoxedStrategy<Vec<Control>> {
        (
            vec(generate_control::<M>(), 0..(max_length - 1)),
            generate_stop_control::<M>(),
        )
            .prop_map(|(vec, stopcode)| {
                let mut vec = vec;
                vec.push(stopcode);
                vec
            })
            .boxed()
    }

    #[proptest]
    fn symmetrical_command_copy(
        #[strategy(1..=131_071_usize)] offset: usize,
        #[strategy(5..=1028_usize)] length: usize,
        #[strategy(0..=3_usize)] literal: usize,
    ) {
        let expected = Command::new::<Reference>(offset, length, literal);
        let mut buf = Cursor::new(vec![]);
        expected.write::<Reference>(&mut buf).unwrap();
        buf.seek(SeekFrom::Start(0)).unwrap();
        let out: Command = Command::read::<Reference>(&mut buf).unwrap();

        prop_assert_eq!(out, expected);
    }

    #[proptest]
    fn symmetrical_command_literal(#[strategy(0..=27_usize)] literal: usize) {
        let real_length = (literal * 4) + 4;

        let expected = Command::new_literal::<Reference>(real_length);
        let mut buf = Cursor::new(vec![]);
        expected.write::<Reference>(&mut buf).unwrap();
        buf.seek(SeekFrom::Start(0)).unwrap();
        let out: Command = Command::read::<Reference>(&mut buf).unwrap();

        prop_assert_eq!(out, expected);
    }

    #[proptest]
    fn symmetrical_command_stop(#[strategy(0..=3_usize)] input: usize) {
        let expected = Command::new_stop::<Reference>(input);
        let mut buf = Cursor::new(vec![]);
        expected.write::<Reference>(&mut buf).unwrap();
        buf.seek(SeekFrom::Start(0)).unwrap();
        let out: Command = Command::read::<Reference>(&mut buf).unwrap();

        prop_assert_eq!(out, expected);
    }

    #[proptest]
    fn symmetrical_any_command(
        #[strategy(generate_random_valid_command::<Reference>())] input: Command,
    ) {
        let expected = input;
        let mut buf = Cursor::new(vec![]);
        expected.write::<Reference>(&mut buf).unwrap();
        buf.seek(SeekFrom::Start(0)).unwrap();
        let out: Command = Command::read::<Reference>(&mut buf).unwrap();

        prop_assert_eq!(out, expected);
    }

    #[test]
    #[should_panic]
    fn command_reject_new_stop_invalid() {
        let _invalid = Command::new_stop::<Reference>(8000);
    }

    #[test]
    #[should_panic]
    fn command_reject_new_literal_invalid() {
        let _invalid = Command::new_literal::<Reference>(8000);
    }

    #[test]
    #[should_panic]
    fn command_reject_new_invalid_high_offset() {
        let _invalid = Command::new::<Reference>(500_000, 0, 0);
    }

    #[test]
    #[should_panic]
    fn command_reject_new_invalid_high_length() {
        let _invalid = Command::new::<Reference>(0, 500_000, 0);
    }

    #[test]
    #[should_panic]
    fn command_reject_new_invalid_high_literal() {
        let _invalid = Command::new::<Reference>(0, 0, 6000);
    }

    #[proptest]
    fn symmetrical_control(#[strategy(generate_control::<Reference>())] input: Control) {
        let expected = input;
        let mut buf = Cursor::new(vec![]);
        expected.write::<Reference>(&mut buf).unwrap();
        buf.seek(SeekFrom::Start(0)).unwrap();
        let out: Control = Control::read::<Reference>(&mut buf).unwrap();

        prop_assert_eq!(out, expected);
    }
}