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
extern crate byteorder;

use std::io::{Cursor, Read, Write};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};

pub mod errors;
pub mod search;

/// Decompresses an LZ10/LZ11 compressed file. It returns an error when:
///
/// - The file is not a valid LZ10/LZ11 file
/// - The file is truncated (More data was expected than present)
///
/// # Example
///
/// ```rust,ignore
/// let mut f = File::open("Archive.bin.cmp");
/// let mut decompressed = nintendo_lz::decompress(&mut f).unwrap();
/// ```
pub fn decompress(inp: &mut Read) -> Result<Vec<u8>, Box<::std::error::Error>> {
    let mut length = inp.read_u32::<LittleEndian>()? as usize;
    let ver = match length & 0xFF {
        0x10 => Ok(0),
        0x11 => Ok(1),
        _ => Err(errors::InvalidMagicNumberError::new("Invalid magic number"))
    }?;
    length >>= 8;
    if length == 0 && ver == 1 {
        length = inp.read_u32::<LittleEndian>()? as usize;
    }
    let mut out: Vec<u8> = Vec::new();
    out.reserve(length);
    while out.len() < length {
        let byte = inp.read_u8()?;
        for bit_no in (0..8).rev() {
            if out.len() >= length {
                break;
            }
            if ((byte >> bit_no) & 1) == 0 {
                let data = inp.read_u8()?;
                out.push(data);
            } else {
                let lenmsb = inp.read_u8()? as usize;
                let lsb = inp.read_u8()? as usize;
                let mut length: usize = lenmsb >> 4;
                let mut disp: usize = ((lenmsb & 15) << 8) + lsb;
                if ver == 0 {
                    length += 3;
                } else if length > 1 {
                    length += 1;
                } else if length == 0 {
                    length = (lenmsb & 15) << 4;
                    length += lsb >> 4;
                    length += 0x11;
                    let msb = inp.read_u8()? as usize;
                    disp = ((lsb & 15) << 8) + msb;
                } else {
                    length = (lenmsb & 15) << 12;
                    length += lsb << 4;
                    let byte1 = inp.read_u8()? as usize;
                    let byte2 = inp.read_u8()? as usize;
                    length += byte1 >> 4;
                    length += 0x111;
                    disp = ((byte1 & 15) << 8) + byte2;
                }
                let start: usize = out.len() - disp - 1;

                for i in 0..length {
                    let val = out[start + i];
                    out.push(val);
                }
            }
        }
    }
    Ok(out)
}


/// This function is a convenience wrapper around `decompress` for decompressing slices, arrays or
/// vectors.
pub fn decompress_arr(input: &[u8]) -> Result<Vec<u8>, Box<::std::error::Error>> {
    let mut reader = Cursor::new(input);
    decompress(&mut reader)
}

/// This enum contains the possible compression levels for LZ compression.
pub enum CompressionLevel {
    /// LZ10 compression. Maximum repeat size: 18 bytes
    LZ10,
    /// LZ11 compression. Maximum repeat size: 65809 bytes
    ///
    /// Argument: Maximum repeat size (0..65810), lower means worse compression but higher speed.
    /// for values < 3 compression is disabled
    LZ11(u32)
}

fn find_longest_match(data: &[u8], off: usize, max: usize) -> Option<(usize, usize)> {
    if off < 4 || data.len() - off < 4 {
        return None;
    }
    let mut longest_pos: usize = 0;
    let mut longest_len: usize = 0;
    let mut start = 0;
    if off > 0x1000 {
        start = off - 0x1000;
    }
    for pos in search::search(&data[start..off+2], &data[off..off+3]) {
        let mut length = 0;
        for (i, p) in (off..data.len()).enumerate() {
            if length == max {
                return Some((start + pos, length));
            }
            if data[p] != data[start + pos + i] {
                break;
            }
            length += 1;
        }
        if length > longest_len {
            longest_pos = pos;
            longest_len = length;
        }
    }
    if longest_len < 3 {
        return None;
    }
    Some((start + longest_pos, longest_len))
}

/// Compresses data to LZ10/LZ11. It returns an error when:
///
/// - The input is too large for the selected LZ version (LZ10 supports at most 16MiB)
/// - The maximum repeat length is out of range (for LZ11, has to be in the range (0..65810)
/// - Writing to the output file failed
///
/// # Example
///
/// ```rust,ignore
/// let mut f = File::create("Archive.bin.cmp");
/// let data = b"This is an example text. This is an example text";
/// nintendo_lz::compress(&data, &mut f, nintendo_lz::CompressionLevel::LZ11(65809)).unwrap();
/// ```
pub fn compress(inp: &[u8], out: &mut Write, level: CompressionLevel) -> Result<(), Box<::std::error::Error>> {
    let ver = match level {
        CompressionLevel::LZ10 => 0,
        CompressionLevel::LZ11(_) => 1
    };
    if ver == 0 && inp.len() > 16777216 {
        return Err(errors::OutOfRangeError::new("Input data too large for LZ10").into());
    }
    if ver == 1 && inp.len() as u64 > 0xFFFFFFFF {
        return Err(errors::OutOfRangeError::new("Input data too large for LZ11").into());
    }
    let repeat_size = match level {
        CompressionLevel::LZ10 => 18,
        CompressionLevel::LZ11(max) => max
    };
    if repeat_size > 65809 {
        return Err(errors::OutOfRangeError::new("Maximum repeat size out of range. (0..65810)").into());
    }

    let size: usize = inp.len();

    if size < 16777216 && (size != 0 || ver == 0) {
        let header = 0x10 + ver + ((size as u32) << 8);
        out.write_u32::<LittleEndian>(header)?;
    } else {
        out.write_u32::<LittleEndian>(0x11)?;
        out.write_u32::<LittleEndian>(size as u32)?;
    }

    let mut off: usize = 0;
    let mut byte: u8 = 0;
    let mut index = 7;
    let mut cmpbuf: Vec<u8> = Vec::new();

    while off < size {
        match find_longest_match(&inp, off, repeat_size as usize) {
            None => {
                index -= 1;
                cmpbuf.push(inp[off]);
                off += 1;
            },
            Some((pos, len)) => {
                let lz_off: usize = off - pos - 1;
                byte |= 1 << index;
                index -= 1;
                if ver == 0 {
                    let l = len - 3;
                    let cmp: [u8;2] = [
                        ((lz_off >> 8) as u8) + ((l << 4) as u8),
                        lz_off as u8
                    ];
                    cmpbuf.extend_from_slice(&cmp);
                } else if len < 0x11 {
                    let l = len - 1;
                    let cmp: [u8;2] = [
                        ((lz_off >> 8) as u8) + ((l << 4) as u8),
                        lz_off as u8
                    ];
                    cmpbuf.extend_from_slice(&cmp);
                } else if len < 0x111 {
                    let l = len - 0x11;
                    let cmp: [u8;3] = [
                        (l >> 4) as u8,
                        ((lz_off >> 8) as u8) + ((l << 4) as u8),
                        lz_off as u8
                    ];
                    cmpbuf.extend_from_slice(&cmp);
                } else {
                    let l = len - 0x111;
                    let cmp: [u8;4] = [
                        (l >> 12) as u8 + 0x10,
                        (l >> 4) as u8,
                        ((lz_off >> 8) as u8) + ((l << 4) as u8),
                        lz_off as u8
                    ];
                    cmpbuf.extend_from_slice(&cmp);
                }
                off += len as usize;
            }
        };
        if index < 0 {
            out.write_u8(byte)?;
            out.write(&cmpbuf)?;
            byte = 0;
            index = 7;
            cmpbuf.clear();
        }
    }
    if cmpbuf.len() != 0 {
        out.write_u8(byte)?;
        out.write(&cmpbuf)?;
    }
    out.write_u8(0xFF)?;

    Ok(())
}


/// This function is a convenience wrapper around `compress` for compressing to a Vec<u8>.
/// Additionally it uses LZ11 as compression algorithm by default.
pub fn compress_arr(input: &[u8]) -> Result<Vec<u8>, Box<::std::error::Error>> {
    let mut out: Vec<u8> = Vec::new();
    {
        let mut writer = Cursor::new(&mut out);
        compress(input, &mut writer, CompressionLevel::LZ11(65809))?;
    }
    Ok(out)
}