jkl 0.2.1

Asset compression and packing tool
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
use std::{hash::Hash, io, num::NonZero};

use crate::{
    ans,
    encode::VarCode,
    lz77,
    math::Delta,
    rle::{rle, Rle},
};

/// Trait for types viable as symbols for compression.
pub trait Symbol: Copy + Default + Ord + Hash + Delta + VarCode + 'static {}

/// Blanket implementation for all types that satisfy the trait bounds.
impl<T> Symbol for T where T: Default + Copy + Ord + Hash + VarCode + Delta + Sized + 'static {}

/// Compression algorithm interface.
pub trait Compressor {
    /// Token type produced by compression for symbols of type `T`.
    type Token<T: Symbol>: Symbol;

    /// Context is produced during compression and is used during decompression.
    type Context<T: Symbol>: VarCode;

    /// Compress the input symbols of type `T`.
    ///
    /// This function gets called with all chunks of symbols.
    ///
    /// Produces decompression context and writes output tokens of type `Self::Token<T>` to `output`.
    fn compress_symbols<T: Symbol>(
        &self,
        input: impl Iterator<Item = impl DoubleEndedIterator<Item = T>> + Clone,
        output: &mut Vec<Vec<Self::Token<T>>>,
    ) -> io::Result<Self::Context<T>>;

    /// Decompress the input tokens of type `Self::Token<T>`.
    ///
    /// Called for each chunk independently.
    fn decompress_tokens<T: Symbol>(
        &self,
        context: &Self::Context<T>,
        input: impl Iterator<Item = Self::Token<T>>,
        output: &mut impl Extend<T>,
    ) -> io::Result<()>;

    fn decompress_tokens2<T: Symbol>(
        &self,
        context: &Self::Context<T>,
        input: impl Iterator<Item = io::Result<Self::Token<T>>>,
    ) -> impl Iterator<Item = io::Result<T>>;
}

#[derive(Clone, Copy, Debug)]
pub struct LZ77Compressor {
    pub window_size: u32,
}

impl LZ77Compressor {
    pub fn new() -> Self {
        LZ77Compressor { window_size: 1024 }
    }
}

pub struct LZ77Context;

impl_fixedcode_zero!(LZ77Context);

impl Compressor for LZ77Compressor {
    type Token<T: Symbol> = lz77::Token<T>;
    type Context<T: Symbol> = LZ77Context;

    fn compress_symbols<'a, T: Symbol>(
        &self,
        input: impl Iterator<Item = impl Iterator<Item = T>>,
        output: &mut Vec<Vec<lz77::Token<T>>>,
    ) -> io::Result<Self::Context<T>> {
        for (i, chunk) in input.enumerate() {
            let mut encoder = lz77::Encoder::new(T::default(), self.window_size);
            if output.len() == i {
                output.push(Vec::new());
            }

            let stream = &mut output[i];
            stream.clear();

            for symbol in chunk {
                encoder.encode(symbol, stream);
            }

            encoder.finish(stream);
        }
        Ok(LZ77Context)
    }

    #[inline]
    fn decompress_tokens<T: Symbol>(
        &self,
        _cx: &LZ77Context,
        mut input: impl Iterator<Item = lz77::Token<T>>,
        output: &mut impl Extend<T>,
    ) -> io::Result<()> {
        let mut decoder = lz77::Decoder::new(T::default(), self.window_size);

        loop {
            match decoder.decode(input.by_ref()) {
                Ok(Some(symbol)) => output.extend(std::iter::once(symbol)),
                Ok(None) => break,
                Err(err) => return Err(io::Error::new(io::ErrorKind::InvalidData, err)),
            }
        }

        Ok(())
    }

    #[inline]
    fn decompress_tokens2<T: Symbol>(
        &self,
        _cx: &LZ77Context,
        input: impl Iterator<Item = io::Result<lz77::Token<T>>>,
    ) -> impl Iterator<Item = io::Result<T>> {
        let mut decoder = lz77::Decoder::new(T::default(), self.window_size);
        let mut extact_error = ExtractError::new(input);

        std::iter::from_fn(move || match decoder.decode(extact_error.by_ref()) {
            Ok(Some(symbol)) => Some(Ok(symbol)),
            Ok(None) => match extact_error.result() {
                Ok(()) => match decoder.finish() {
                    Ok(()) => None,
                    Err(err) => Some(Err(io::Error::new(io::ErrorKind::InvalidData, err))),
                },
                Err(err) => Some(Err(err)),
            },
            Err(err) => Some(Err(io::Error::new(io::ErrorKind::InvalidData, err))),
        })
    }
}

#[derive(Clone, Copy, Debug)]
pub struct AnsCompressor;

impl Compressor for AnsCompressor {
    type Token<T: Symbol> = u32;
    type Context<T: Symbol> = ans::Context<T>;

    fn compress_symbols<T: Symbol>(
        &self,
        input: impl Iterator<Item = impl DoubleEndedIterator<Item = T>> + Clone,
        output: &mut Vec<Vec<u32>>,
    ) -> io::Result<Self::Context<T>> {
        let context = ans::Context::from_input(input.clone().flatten());

        for (i, chunk) in input.enumerate() {
            let mut encoder = ans::Encoder::new(&context);

            if output.len() == i {
                output.push(Vec::new());
            }
            let stream = &mut output[i];
            stream.clear();

            for symbol in chunk.rev() {
                stream.extend(encoder.encode(symbol));
            }

            stream.extend(encoder.finish());
            stream.reverse();
        }

        Ok(context)
    }

    #[inline]
    fn decompress_tokens<T: Symbol>(
        &self,
        context: &ans::Context<T>,
        mut input: impl Iterator<Item = u32>,
        output: &mut impl Extend<T>,
    ) -> io::Result<()> {
        let mut decoder = ans::Decoder::new(context);

        while let Some(symbol) = decoder.decode(input.by_ref()) {
            output.extend(std::iter::once(symbol));
        }

        match decoder.finish() {
            Ok(()) => Ok(()),
            Err(err) => Err(io::Error::new(io::ErrorKind::InvalidData, err)),
        }
    }

    #[inline]
    fn decompress_tokens2<T: Symbol>(
        &self,
        context: &ans::Context<T>,
        input: impl Iterator<Item = io::Result<u32>>,
    ) -> impl Iterator<Item = io::Result<T>> {
        let mut decoder = ans::Decoder::new(context);
        let mut extact_error = ExtractError::new(input);

        std::iter::from_fn(move || match decoder.decode(extact_error.by_ref()) {
            Some(symbol) => Some(Ok(symbol)),
            None => match extact_error.result() {
                Ok(()) => match decoder.finish() {
                    Ok(()) => None,
                    Err(err) => Some(Err(io::Error::new(io::ErrorKind::InvalidData, err))),
                },
                Err(err) => Some(Err(err)),
            },
        })
    }
}

impl Compressor for () {
    type Token<T: Symbol> = T;
    type Context<T: Symbol> = ();

    fn compress_symbols<T: Symbol>(
        &self,
        input: impl Iterator<Item = impl DoubleEndedIterator<Item = T>> + Clone,
        output: &mut Vec<Vec<T>>,
    ) -> io::Result<()> {
        for (i, chunk) in input.enumerate() {
            if output.len() == i {
                output.push(Vec::new());
            }
            let stream = &mut output[i];
            stream.clear();

            for symbol in chunk {
                stream.push(symbol);
            }
        }
        Ok(())
    }

    #[inline]
    fn decompress_tokens<T: Symbol>(
        &self,
        _cx: &(),
        input: impl Iterator<Item = T>,
        output: &mut impl Extend<T>,
    ) -> io::Result<()> {
        output.extend(input);
        Ok(())
    }

    #[inline]
    fn decompress_tokens2<T: Symbol>(
        &self,
        _cx: &(),
        input: impl Iterator<Item = io::Result<T>>,
    ) -> impl Iterator<Item = io::Result<T>> {
        input
    }
}

impl<A, B> Compressor for (A, B)
where
    A: Compressor,
    B: Compressor,
{
    type Token<T: Symbol> = B::Token<A::Token<T>>;
    type Context<T: Symbol> = (A::Context<T>, B::Context<A::Token<T>>);

    fn compress_symbols<T: Symbol>(
        &self,
        input: impl Iterator<Item = impl DoubleEndedIterator<Item = T>> + Clone,
        output: &mut Vec<Vec<B::Token<A::Token<T>>>>,
    ) -> io::Result<Self::Context<T>> {
        let (a, b) = self;

        let mut a_tokens = Vec::new();

        let a_cx = a.compress_symbols(input, &mut a_tokens)?;
        let b_cx = b.compress_symbols(a_tokens.iter().map(|v| v.iter().copied()), output)?;
        Ok((a_cx, b_cx))
    }

    #[inline]
    fn decompress_tokens<T: Symbol>(
        &self,
        context: &Self::Context<T>,
        input: impl Iterator<Item = B::Token<A::Token<T>>>,
        output: &mut impl Extend<T>,
    ) -> io::Result<()> {
        let (a, b) = self;

        let (a_cx, b_cx) = context;
        let mut a_tokens = Vec::new();

        b.decompress_tokens(b_cx, input, &mut a_tokens)?;
        a.decompress_tokens(a_cx, a_tokens.into_iter(), output)?;
        Ok(())
    }

    #[inline]
    fn decompress_tokens2<T: Symbol>(
        &self,
        context: &Self::Context<T>,
        input: impl Iterator<Item = io::Result<Self::Token<T>>>,
    ) -> impl Iterator<Item = io::Result<T>> {
        let (a, b) = self;

        let (a_cx, b_cx) = context;

        let a_tokens = b.decompress_tokens2(b_cx, input);
        let symbols = a.decompress_tokens2(a_cx, a_tokens);

        symbols
    }
}

// fn take_error_or_eof(read_error: &mut Option<io::Error>) -> io::Error {
//     match read_error.take() {
//         Some(err) => err,
//         None => io::Error::new(io::ErrorKind::UnexpectedEof, "Unexpected EOF"),
//     }
// }

// fn codes_read_iter<'a>(
//     read: &'a mut ReadBits<impl io::Read>,
//     read_error: &'a mut Option<io::Error>,
// ) -> impl Iterator<Item = u32> + 'a {
//     std::iter::from_fn(|| match u32::read(read) {
//         Ok(code) => Some(code),
//         Err(err) => {
//             *read_error = Some(err);
//             None
//         }
//     })
// }

struct ExtractError<I> {
    iter: I,
    error: Option<io::Error>,
}

impl<I> ExtractError<I> {
    #[inline]
    fn new(iter: I) -> Self {
        ExtractError { iter, error: None }
    }

    #[inline]
    fn result(&mut self) -> io::Result<()> {
        match self.error.take() {
            Some(err) => Err(err),
            None => Ok(()),
        }
    }
}

impl<T, I> Iterator for ExtractError<I>
where
    I: Iterator<Item = io::Result<T>>,
{
    type Item = T;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match self.iter.next()? {
            Ok(token) => Some(token),
            Err(err) => {
                self.error = Some(err);
                None
            }
        }
    }
}

pub struct RleIoExpand<T>(RleIoExpandVariant<T>);

impl<T> RleIoExpand<T> {
    pub fn new(rle: Rle<T>) -> Self {
        RleIoExpand(RleIoExpandVariant::Repeat {
            value: rle.value,
            count: rle.count,
        })
    }

    pub fn error(err: io::Error) -> Self {
        RleIoExpand(RleIoExpandVariant::NoRepeat { error: Some(err) })
    }
}

enum RleIoExpandVariant<T> {
    Repeat { value: T, count: NonZero<usize> },
    NoRepeat { error: Option<io::Error> },
}

impl<T> Iterator for RleIoExpand<T>
where
    T: Copy,
{
    type Item = io::Result<T>;

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.len();
        (len, Some(len))
    }

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match &mut self.0 {
            RleIoExpandVariant::Repeat { value, count } => {
                let result = *value;
                match NonZero::new(count.get() - 1) {
                    Some(new_count) => *count = new_count,
                    None => self.0 = RleIoExpandVariant::NoRepeat { error: None },
                }
                Some(Ok(result))
            }
            RleIoExpandVariant::NoRepeat { error } => error.take().map(Err),
        }
    }

    #[inline]
    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        match &mut self.0 {
            RleIoExpandVariant::Repeat { value, count } => {
                let result = *value;

                match count.get() {
                    c if c >= n => {
                        match NonZero::new(c - n) {
                            Some(new_count) => *count = new_count,
                            None => self.0 = RleIoExpandVariant::NoRepeat { error: None },
                        }
                        Some(Ok(result))
                    }
                    _ => {
                        self.0 = RleIoExpandVariant::NoRepeat { error: None };
                        None
                    }
                }
            }
            RleIoExpandVariant::NoRepeat { error } => error.take().map(Err),
        }
    }

    #[inline]
    fn fold<B, F>(self, init: B, mut f: F) -> B
    where
        F: FnMut(B, io::Result<T>) -> B,
    {
        match self.0 {
            RleIoExpandVariant::Repeat { value, count } => {
                let mut acc = init;
                for _ in 0..count.get() {
                    acc = f(acc, Ok(value));
                }
                acc
            }
            RleIoExpandVariant::NoRepeat { error } => match error {
                Some(err) => f(init, Err(err)),
                None => init,
            },
        }
    }
}

impl<T> ExactSizeIterator for RleIoExpand<T>
where
    T: Copy,
{
    #[inline]
    fn len(&self) -> usize {
        match &self.0 {
            RleIoExpandVariant::Repeat { count, .. } => count.get(),
            RleIoExpandVariant::NoRepeat { error } => error.is_some() as usize,
        }
    }
}

impl<T> DoubleEndedIterator for RleIoExpand<T>
where
    T: Copy,
{
    #[inline]
    fn next_back(&mut self) -> Option<io::Result<T>> {
        // In case of repeat, it yields same `Ok(T)` values.
        // In case of error it yields just one `Err(io::Error)`.
        // Thus iteration direction doesn't matter, and we can just call `next()`.
        self.next()
    }

    #[inline]
    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
        // Similar to `next_back()`, we can just call `nth(n)`.
        self.nth(n)
    }

    fn rfold<B, F>(self, init: B, f: F) -> B
    where
        F: FnMut(B, io::Result<T>) -> B,
    {
        // Similar to `next_back()`, we can just call `fold(init, f)`.
        self.fold(init, f)
    }

    fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>
    where
        Self: Sized,
        P: FnMut(&Self::Item) -> bool,
    {
        // Similar to `next_back()`, we can just call `find(predicate)`.
        self.find(predicate)
    }
}

pub struct RleCompressor;

pub struct RleContext;

impl_fixedcode_zero!(RleContext);

impl Compressor for RleCompressor {
    type Token<T: Symbol> = Rle<T>;
    type Context<T: Symbol> = RleContext;

    fn compress_symbols<T: Symbol>(
        &self,
        input: impl Iterator<Item = impl DoubleEndedIterator<Item = T>> + Clone,
        output: &mut Vec<Vec<Rle<T>>>,
    ) -> io::Result<Self::Context<T>> {
        for (i, chunk) in input.enumerate() {
            if output.len() == i {
                output.push(Vec::new());
            }

            let stream = &mut output[i];
            stream.clear();
            stream.extend(rle(chunk));
        }
        Ok(RleContext)
    }

    fn decompress_tokens<T: Symbol>(
        &self,
        _cx: &RleContext,
        input: impl Iterator<Item = Rle<T>>,
        output: &mut impl Extend<T>,
    ) -> io::Result<()> {
        for rle in input {
            output.extend(rle);
        }
        Ok(())
    }

    fn decompress_tokens2<T: Symbol>(
        &self,
        _cx: &RleContext,
        input: impl Iterator<Item = io::Result<Rle<T>>>,
    ) -> impl Iterator<Item = io::Result<T>> {
        input.flat_map(|rle| match rle {
            Ok(rle) => RleIoExpand::new(rle),
            Err(err) => RleIoExpand::error(err),
        })
    }
}