jbig2-decoder 0.3.2

Memory-safe JBIG2 decoder under development
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
//! Prefix lookahead table builders for compact and wide Huffman tables.

#[cfg(verus_keep_ghost)]
use super::*;
#[cfg(not(verus_keep_ghost))]
use super::{
    try_reserve, HuffmanError, HuffmanTable, HuffmanTableError, MalformedError, TableSlice,
    WideCode, MAX_PREFIX_LEN, MIN_FAST_PREFIX_LEN, PREFIX_LOOKUP_BITS, PREFIX_LOOKUP_SIZE,
    SHORT_PREFIX_MAX,
};

#[cfg_attr(verus_keep_ghost, verus_spec(out =>
    ensures match out {
        Ok(lookup) =>
            lookup@.len() == 256
                && forall|prefix: int| 0 <= prefix < 256 ==>
                    #[trigger] lookup@[prefix] == huffman_lookup_spec::fast_slot(
                        WideCode { limbs: [short_first_code@[8] as u64, 0, 0, 0] },
                        short_length_count@[8],
                        short_first_line@[8],
                        ordered_lines@,
                        prefix as u8,
                        short_length_count@[8],
                    ),
        Err(_) => true,
    },
))]
#[allow(clippy::cast_possible_truncation)]
pub(super) fn build_prefix_lookup_short(
    short_length_count: &[u32; SHORT_PREFIX_MAX + 1],
    short_first_code: &[u32; SHORT_PREFIX_MAX + 1],
    short_first_line: &[u32; SHORT_PREFIX_MAX + 1],
    ordered_lines: &[u32],
) -> Result<Vec<u16>, HuffmanError> {
    let mut lookup = Vec::new();
    try_reserve::<u16>(&mut lookup, PREFIX_LOOKUP_SIZE)?;
    lookup.resize(PREFIX_LOOKUP_SIZE, 0);
    #[cfg(verus_keep_ghost)]
    proof! {
        assert(PREFIX_LOOKUP_SIZE == 256) by (bit_vector);
        assert(lookup@.len() == 256);
    }
    let count = short_length_count[8];
    let base = short_first_code[8];
    let first_line = short_first_line[8];
    let mut distance = 0_u32;
    #[cfg_attr(verus_keep_ghost, verus_spec(
        invariant
            lookup@.len() == 256,
            distance <= count,
            count == short_length_count@[8],
            base == short_first_code@[8],
            first_line == short_first_line@[8],
            forall|prefix: int| 0 <= prefix < 256 ==>
                #[trigger] lookup@[prefix] == huffman_lookup_spec::fast_slot(
                    WideCode { limbs: [base as u64, 0, 0, 0] },
                    count,
                    first_line,
                    ordered_lines@,
                    prefix as u8,
                    distance,
                ),
        decreases count - distance,
    ))]
    while distance < count {
        let code = base
            .checked_add(distance)
            .ok_or(HuffmanError::InvalidTable(
                HuffmanTableError::Oversubscribed,
            ))?;
        if code > u32::from(u8::MAX) || distance > u32::from(u8::MAX) {
            return Err(HuffmanError::InvalidTable(
                HuffmanTableError::Oversubscribed,
            ));
        }
        let ordered_index = first_line
            .checked_add(distance)
            .ok_or(MalformedError::IntegerOverflow)?;
        let line_index = *ordered_lines
            .get(ordered_index as usize)
            .ok_or(HuffmanError::InvalidTable(HuffmanTableError::InvalidCode))?;
        if line_index >= u32::from(u16::MAX) {
            #[cfg(verus_keep_ghost)]
            proof! {
                huffman_lookup_spec::advance_slot(
                    WideCode { limbs: [base as u64, 0, 0, 0] },
                    count,
                    first_line,
                    ordered_lines@,
                    distance,
                    code as u8,
                    0u16,
                );
            }
            distance += 1;
            continue;
        }
        let encoded_line = (line_index + 1) as u16;
        let slot_index = code as usize;
        if lookup[slot_index] != 0 {
            return Err(HuffmanError::InvalidTable(
                HuffmanTableError::Oversubscribed,
            ));
        }
        lookup[slot_index] = encoded_line;
        #[cfg(verus_keep_ghost)]
        proof! {
            huffman_lookup_spec::advance_slot(
                WideCode { limbs: [base as u64, 0, 0, 0] },
                count,
                first_line,
                ordered_lines@,
                distance,
                code as u8,
                encoded_line,
            );
        }
        distance += 1;
    }
    Ok(lookup)
}

/// Builds a 256-entry 8-bit prefix lookup table covering all prefix lengths `1..=8`.
#[cfg_attr(verus_keep_ghost, verus_spec(out =>
    requires
        1 <= max_prefix_len <= 32,
    ensures match out {
        Ok(lookup) => lookup@.len() == 256,
        Err(_) => true,
    },
))]
#[allow(clippy::cast_possible_truncation, clippy::too_many_lines)]
pub(super) fn build_prefix_lookup_1_to_8(
    short_length_count: &[u32; SHORT_PREFIX_MAX + 1],
    short_first_code: &[u32; SHORT_PREFIX_MAX + 1],
    short_first_line: &[u32; SHORT_PREFIX_MAX + 1],
    ordered_lines: &[u32],
    max_prefix_len: u8,
) -> Result<Vec<u16>, HuffmanError> {
    let mut lookup = Vec::new();
    try_reserve::<u16>(&mut lookup, PREFIX_LOOKUP_SIZE)?;
    lookup.resize(PREFIX_LOOKUP_SIZE, 0);
    #[cfg(verus_keep_ghost)]
    proof! {
        assert(PREFIX_LOOKUP_SIZE == 256) by (bit_vector);
        assert(lookup@.len() == 256);
    }
    let limit = usize::from(max_prefix_len).min(usize::from(PREFIX_LOOKUP_BITS));
    let _ordered_len = ordered_lines.len();
    let mut length = 1_usize;
    #[cfg_attr(verus_keep_ghost, verus_spec(
        invariant
            1 <= length <= limit + 1,
            limit <= 8,
            limit <= max_prefix_len as usize,
            ordered_lines@.len() <= usize::MAX,
            lookup@.len() == 256,
        decreases limit + 1 - length,
    ))]
    while length <= limit {
        let count = short_length_count[length];
        let base = short_first_code[length];
        let first_line = short_first_line[length];
        let end_line = u64::from(first_line) + u64::from(count);
        if end_line > ordered_lines.len() as u64 {
            return Err(HuffmanError::InvalidTable(HuffmanTableError::InvalidCode));
        }
        let max_codes = 1_u64 << (length as u64);
        if count > 0 && u64::from(base) + u64::from(count) > max_codes {
            return Err(HuffmanError::InvalidTable(
                HuffmanTableError::Oversubscribed,
            ));
        }
        let shift = 8 - length;
        let span_u64 = 1_u64 << (shift as u64);
        #[cfg(verus_keep_ghost)]
        proof! {
            let s64 = shift as u64;
            assert((1u64 << s64) <= 128u64) by (bit_vector)
                requires s64 <= 7u64;
        }
        let span = span_u64 as usize;
        let mut distance = 0_u32;
        #[cfg_attr(verus_keep_ghost, verus_spec(
            invariant
                1 <= length <= limit,
                limit <= 8,
                limit <= max_prefix_len as usize,
                shift == 8 - length,
                span as u64 == (1u64 << (shift as u64)),
                ordered_lines@.len() <= usize::MAX,
                count == short_length_count@[length as int],
                base == short_first_code@[length as int],
                first_line == short_first_line@[length as int],
                first_line as nat + count as nat <= ordered_lines@.len(),
                count > 0 ==> (base as u64 + count as u64) <= (1u64 << (length as u64)),
                lookup@.len() == 256,
                distance <= count,
            decreases count - distance,
        ))]
        while distance < count {
            #[cfg(verus_keep_ghost)]
            proof! {
                let l64 = length as u64;
                assert((1u64 << l64) <= 256u64) by (bit_vector)
                    requires 1u64 <= l64 <= 8u64;
            }
            let code = (base + distance) as usize;
            let ordered_index = (first_line as usize) + (distance as usize);
            let line_index = ordered_lines[ordered_index];
            if line_index < u32::from(u16::MAX) {
                let encoded_line = (line_index + 1) as u16;
                #[cfg(verus_keep_ghost)]
                proof! {
                    let l64 = length as u64;
                    let s64 = shift as u64;
                    let c64 = code as u64;
                    let sp = span as u64;
                    assert(
                        (c64 << s64) <= 256u64
                        && sp <= 128u64
                        && ((c64 << s64) as nat) + (sp as nat) <= 256nat
                    ) by (bit_vector)
                        requires
                            1u64 <= l64 <= 8u64,
                            s64 == sub(8u64, l64),
                            c64 < (1u64 << l64),
                            sp == (1u64 << s64);
                }
                let start = ((code as u64) << (shift as u64)) as usize;
                let end = start + span;
                let mut slot = start;
                #[cfg_attr(verus_keep_ghost, verus_spec(
                    invariant
                        start <= slot <= end,
                        end <= 256,
                        lookup@.len() == 256,
                    decreases end - slot,
                ))]
                while slot < end {
                    lookup[slot] = encoded_line;
                    slot += 1;
                }
            }
            distance += 1;
        }
        length += 1;
    }
    Ok(lookup)
}

#[cfg_attr(verus_keep_ghost, verus_spec(out =>
    ensures match out {
        Ok(lookup) =>
            lookup@.len() == 256
                && (huffman_lookup_spec::fast_shape(length_count@) ==>
                    forall|prefix: int| 0 <= prefix < 256 ==>
                        #[trigger] lookup@[prefix] == huffman_lookup_spec::fast_slot(
                            first_code@[8], length_count@[8], first_line@[8], ordered_lines@,
                            prefix as u8, if maximum_length >= 8 { length_count@[8] } else { 0u32 },
                        )),
        Err(_) => true,
    },
))]
// Loop contracts and ghost proofs account for the additional source lines.
#[allow(
    clippy::cast_possible_truncation,
    clippy::redundant_closure,
    clippy::too_many_lines
)]
pub(super) fn build_prefix_lookup(
    length_count: &[u32; MAX_PREFIX_LEN + 1],
    first_code: &[WideCode; MAX_PREFIX_LEN + 1],
    first_line: &[u32; MAX_PREFIX_LEN + 1],
    ordered_lines: &[u32],
    maximum_length: usize,
) -> Result<Vec<u16>, HuffmanError> {
    let mut lookup = Vec::new();
    try_reserve::<u16>(&mut lookup, PREFIX_LOOKUP_SIZE)?;
    lookup.resize(PREFIX_LOOKUP_SIZE, 0);
    #[cfg(verus_keep_ghost)]
    proof! {
        assert(PREFIX_LOOKUP_SIZE == 256) by (bit_vector);
        assert(lookup@.len() == 256);
        assert forall|prefix: int| 0 <= prefix < 256 implies lookup@[prefix] == 0 by {
        }
    }
    let lookup_length = maximum_length.min(usize::from(PREFIX_LOOKUP_BITS));
    let mut length = 1_usize;
    #[cfg_attr(verus_keep_ghost, verus_spec(
        invariant
            lookup@.len() == PREFIX_LOOKUP_SIZE,
            lookup@.len() == 256,
            lookup_length <= PREFIX_LOOKUP_BITS as usize,
            1 <= length,
            length <= lookup_length + 1,
            huffman_lookup_spec::fast_shape(length_count@) ==>
                forall|prefix: int| 0 <= prefix < 256 ==>
                    #[trigger] lookup@[prefix] == huffman_lookup_spec::fast_slot(
                        first_code@[8], length_count@[8], first_line@[8], ordered_lines@,
                        prefix as u8, if length <= 8 { 0u32 } else { length_count@[8] },
                    ),
        decreases lookup_length + 1 - length,
    ))]
    while length <= lookup_length {
        let count = length_count[length];
        let mut distance = 0_u32;
        #[cfg_attr(verus_keep_ghost, verus_spec(
            invariant
                lookup@.len() == PREFIX_LOOKUP_SIZE,
                lookup@.len() == 256,
                lookup_length <= PREFIX_LOOKUP_BITS as usize,
                1 <= length,
                length <= lookup_length,
                distance <= count,
                count == length_count@[length as int],
                huffman_lookup_spec::fast_shape(length_count@) ==>
                    (length == 8 || count == 0),
                huffman_lookup_spec::fast_shape(length_count@) ==>
                    forall|prefix: int| 0 <= prefix < 256 ==>
                        #[trigger] lookup@[prefix] == huffman_lookup_spec::fast_slot(
                            first_code@[8], length_count@[8], first_line@[8], ordered_lines@,
                            prefix as u8, distance,
                        ),
            decreases count - distance,
        ))]
        while distance < count {
            let code = first_code[length]
                .checked_add_small(distance)
                .ok_or(HuffmanTableError::Oversubscribed)
                .map_err(|error| HuffmanError::InvalidTable(error))?;
            if code.limbs[1] != 0
                || code.limbs[2] != 0
                || code.limbs[3] != 0
                || code.limbs[0] > u64::from(u8::MAX)
                || distance > u32::from(u8::MAX)
            {
                return Err(HuffmanError::InvalidTable(
                    HuffmanTableError::Oversubscribed,
                ));
            }
            #[cfg(verus_keep_ghost)]
            proof! {
                if huffman_lookup_spec::fast_shape(length_count@) {
                    huffman_lookup_spec::small_code_value(
                        first_code@[8], distance, code,
                    );
                }
            }
            let suffix_bits = usize::from(PREFIX_LOOKUP_BITS) - length;
            let repeats = 1_usize << suffix_bits;
            let code = usize::try_from(code.limbs[0])
                .map_err(|_| HuffmanError::InvalidTable(HuffmanTableError::Oversubscribed))?;
            let first_prefix = code << suffix_bits;
            let ordered_index = first_line[length]
                .checked_add(distance)
                .ok_or(MalformedError::IntegerOverflow)?;
            let line_index = *ordered_lines
                .get(ordered_index as usize)
                .ok_or(HuffmanError::InvalidTable(HuffmanTableError::InvalidCode))?;
            if line_index >= u32::from(u16::MAX) {
                #[cfg(verus_keep_ghost)]
                proof! {
                    if huffman_lookup_spec::fast_shape(length_count@) {
                        assert(line_index as int + 1 > u16::MAX);
                        huffman_lookup_spec::advance_slot(
                            first_code@[8], count, first_line@[8], ordered_lines@,
                            distance, code as u8, 0u16,
                        );
                    }
                }
                distance += 1;
                continue;
            }
            let encoded_line = (line_index + 1) as u16;
            #[cfg(verus_keep_ghost)]
            proof! {
                if huffman_lookup_spec::fast_shape(length_count@) {
                    assert(length == 8);
                    assert(suffix_bits == 0);
                    assert((1usize << 0usize) == 1usize) by (bit_vector);
                    assert((code << 0usize) == code) by (bit_vector);
                    assert(repeats == 1);
                    assert(first_prefix == code);
                }
            }
            let mut suffix = 0_usize;
            #[cfg_attr(verus_keep_ghost, verus_spec(
                invariant
                    lookup@.len() == PREFIX_LOOKUP_SIZE,
                    lookup_length <= PREFIX_LOOKUP_BITS as usize,
                    1 <= length,
                    length <= lookup_length,
                    suffix <= repeats,
                    lookup@.len() == 256,
                    distance < count,
                    count == length_count@[length as int],
                    code <= 255,
                    ordered_index as int == first_line@[length as int] as int + distance as int,
                    ordered_index < ordered_lines@.len(),
                    line_index == ordered_lines@[ordered_index as int],
                    encoded_line as int == line_index as int + 1,
                    huffman_lookup_spec::fast_shape(length_count@) ==>
                        (length == 8 && repeats == 1 && first_prefix == code),
                    huffman_lookup_spec::fast_shape(length_count@) ==> (
                        first_code@[8].limbs@[1] == 0
                        && first_code@[8].limbs@[2] == 0
                        && first_code@[8].limbs@[3] == 0
                        && first_code@[8].limbs@[0] as int + distance as int == code as int
                    ),
                    huffman_lookup_spec::fast_shape(length_count@) ==>
                        forall|prefix: int| 0 <= prefix < 256 ==>
                            #[trigger] lookup@[prefix] == huffman_lookup_spec::fast_slot(
                                first_code@[8], length_count@[8], first_line@[8], ordered_lines@,
                                prefix as u8,
                                if suffix == 0 { distance } else { (distance + 1) as u32 },
                            ),
                decreases repeats - suffix,
            ))]
            while suffix < repeats {
                let index = first_prefix
                    .checked_add(suffix)
                    .ok_or(MalformedError::IntegerOverflow)?;
                let slot = lookup.get_mut(index).ok_or(HuffmanError::InvalidTable(
                    HuffmanTableError::Oversubscribed,
                ))?;
                if *slot != 0 {
                    return Err(HuffmanError::InvalidTable(
                        HuffmanTableError::Oversubscribed,
                    ));
                }
                *slot = encoded_line;
                #[cfg(verus_keep_ghost)]
                proof! {
                    if huffman_lookup_spec::fast_shape(length_count@) {
                        huffman_lookup_spec::advance_slot(
                            first_code@[8], count, first_line@[8], ordered_lines@,
                            distance, code as u8, encoded_line,
                        );
                    }
                }
                suffix += 1;
            }
            distance += 1;
        }
        length += 1;
    }
    Ok(lookup)
}

impl HuffmanTable {
    #[cfg_attr(verus_keep_ghost, verus_spec(
        requires huffman_lookup_spec::table_lookup_valid(old(self)),
        ensures
            final(self).lines == old(self).lines,
            final(self).ordered_lines == old(self).ordered_lines,
            final(self).short_length_count == old(self).short_length_count,
            final(self).short_first_code == old(self).short_first_code,
            final(self).short_first_line == old(self).short_first_line,
            final(self).long_tables == old(self).long_tables,
            final(self).max_prefix_len == old(self).max_prefix_len,
            huffman_lookup_spec::table_lookup_valid(final(self)),
    ))]
    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
    pub(super) fn attach_short_prefix_lut(&mut self) {
        if self.prefer_prefix_lookup
            || self.long_tables.is_some()
            || self.max_prefix_len == 0
            || usize::from(self.max_prefix_len) > SHORT_PREFIX_MAX
        {
            return;
        }
        let mut has_short = false;
        let mut l = 1_usize;
        #[cfg_attr(verus_keep_ghost, verus_spec(
            invariant
                1 <= l <= MIN_FAST_PREFIX_LEN,
                has_short ==> exists|k: int| 1 <= k < 8 && self.short_length_count@[k] > 0,
            decreases MIN_FAST_PREFIX_LEN - l,
        ))]
        while l < MIN_FAST_PREFIX_LEN {
            if self.short_length_count[l] > 0 {
                has_short = true;
            }
            l += 1;
        }
        if !has_short {
            return;
        }
        if let Ok(lut) = build_prefix_lookup_1_to_8(
            &self.short_length_count,
            &self.short_first_code,
            &self.short_first_line,
            self.ordered_lines.as_slice(),
            self.max_prefix_len,
        ) {
            self.prefix_lookup = TableSlice::Owned(lut);
            self.prefer_prefix_lookup = true;
            #[cfg(verus_keep_ghost)]
            proof! {
                huffman_lookup_spec::table_lookup_definition();
                let counts = huffman_spec::table_length_counts(self);
                let k = choose|k: int| 1 <= k < 8 && self.short_length_count@[k] > 0;
                assert(counts[k] > 0);
                assert(!huffman_lookup_spec::fast_shape(counts));
            }
        }
    }
}