jbig2-decoder 0.3.3

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
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
//! Text strip state, instance placement and region payload decoding.

use super::bitmap::refinement_template_from_u8;
use super::codec::{
    byte_align, decode_checked_symbol_id, decode_refined_bitmap, decode_symbol_id_code_lengths,
    new_arithmetic_codec, new_huffman_codec, normalized_bounded_arithmetic,
    read_symbol_id_runcode_lines, validate_bounded_arithmetic_marker,
};
use super::placement::{flush_placement_batch, prepare_placement};
#[cfg(verus_keep_ghost)]
use super::symbol_text_spec;
use super::tables::{
    associate_text_tables, materialize_huffman_table, select_text_tables, wrap_custom_tables,
};
use super::{
    compose_placement, enforce_limit, parse_text_region_header, required_integer,
    symbol_id_code_length, widen_u32_i64, widen_u8_i64, Bitmap, EntropyInteger, HuffmanChoiceSet,
    HuffmanFieldTables, HuffmanTable, HuffmanValue, IntegerField, LimitKind, Limits,
    MalformedError, Placement, PlacementBatch, ReferenceCorner, ResourceTracker,
    StandardHuffmanTables, StripState, SymbolCodebook, SymbolCodec, SymbolIdRequest,
    SymbolTextError, TextRegionConfig, TextRegionEnd, TextRegionInput, TextRegionOutput,
    TextRegionState,
};
#[cfg(verus_keep_ghost)]
use vstd::prelude::*;

impl TextRegionState {
    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
        ensures out.is_ok() == symbol_text_spec::text_initialization_allowed(
            config, declared_instances, initial_strip_value, limits,
        ),
        match out {
            Ok(state) =>
                symbol_text_spec::text_state_valid(&state)
                && state.config == config
                && state.declared_instances == declared_instances
                && state.decoded_instances == 0
                && state.strip_t as int
                    == -(initial_strip_value as int * config.strip_size as int)
                && state.first_s == 0
                && state.strip.is_none(),
            Err(_) => true,
        },
    ))]
    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
    pub(crate) fn new(
        config: TextRegionConfig,
        declared_instances: u32,
        initial_strip_value: i64,
        limits: &Limits,
    ) -> Result<Self, SymbolTextError> {
        enforce_limit(
            LimitKind::Work,
            limits.max_work_units,
            u64::from(declared_instances),
        )?;
        let scaled = initial_strip_value
            .checked_mul(widen_u8_i64(config.strip_size))
            .ok_or(MalformedError::IntegerOverflow)?;
        let strip_t = 0_i64
            .checked_sub(scaled)
            .ok_or(MalformedError::IntegerOverflow)?;
        Ok(Self {
            config,
            declared_instances,
            decoded_instances: 0,
            strip_t,
            first_s: 0,
            strip: None,
        })
    }

    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
        requires symbol_text_spec::text_state_valid(old(self)),
        ensures match out {
            Ok(()) =>
                symbol_text_spec::text_state_valid(final(self))
                && final(self).strip.is_some()
                && final(self).decoded_instances == old(self).decoded_instances,
            Err(_) => true,
        },
    ))]
    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
    pub(crate) fn begin_strip(
        &mut self,
        strip_delta: i64,
        first_s_delta: i64,
    ) -> Result<(), SymbolTextError> {
        if self.strip.is_some() {
            return Err(SymbolTextError::InvalidState("strip already open"));
        }
        if self.decoded_instances >= self.declared_instances {
            return Err(SymbolTextError::InvalidState("strip after final instance"));
        }
        let scaled = strip_delta
            .checked_mul(widen_u8_i64(self.config.strip_size))
            .ok_or(MalformedError::IntegerOverflow)?;
        self.strip_t = self
            .strip_t
            .checked_add(scaled)
            .ok_or(MalformedError::IntegerOverflow)?;
        self.first_s = self
            .first_s
            .checked_add(first_s_delta)
            .ok_or(MalformedError::IntegerOverflow)?;
        self.strip = Some(StripState {
            cursor_s: self.first_s,
            has_instance: false,
        });
        Ok(())
    }

    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
        requires symbol_text_spec::text_state_valid(old(self)),
        ensures match out {
            Ok(placement) =>
                symbol_text_spec::text_state_valid(final(self))
                && final(self).decoded_instances == old(self).decoded_instances + 1
                && final(self).strip.is_some()
                && symbol_text_spec::work_units(final(resources))
                    <= limits.max_work_units
                && symbol_text_spec::work_units(final(resources))
                    == symbol_text_spec::work_units(old(resources)) + 1
                && symbol_text_spec::placement_within_extents(placement, width, height),
            Err(_) => true,
        },
    ))]
    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
    pub(crate) fn place_first(
        &mut self,
        within_strip_t: u8,
        width: u32,
        height: u32,
        limits: &Limits,
        resources: &mut ResourceTracker,
    ) -> Result<Placement, SymbolTextError> {
        let strip = self
            .strip
            .as_ref()
            .ok_or(SymbolTextError::InvalidState("no open strip"))?;
        if strip.has_instance {
            return Err(SymbolTextError::InvalidState(
                "first instance already placed",
            ));
        }
        self.place_current(within_strip_t, width, height, limits, resources)
    }

    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
        requires symbol_text_spec::text_state_valid(old(self)),
        ensures match out {
            Ok(placement) =>
                symbol_text_spec::text_state_valid(final(self))
                && final(self).decoded_instances == old(self).decoded_instances + 1
                && final(self).strip.is_some()
                && symbol_text_spec::work_units(final(resources))
                    <= limits.max_work_units
                && symbol_text_spec::work_units(final(resources))
                    == symbol_text_spec::work_units(old(resources)) + 1
                && symbol_text_spec::placement_within_extents(placement, width, height),
            Err(_) => true,
        },
    ))]
    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
    pub(crate) fn place_subsequent(
        &mut self,
        delta_s: i64,
        within_strip_t: u8,
        width: u32,
        height: u32,
        limits: &Limits,
        resources: &mut ResourceTracker,
    ) -> Result<Placement, SymbolTextError> {
        let strip = self
            .strip
            .as_mut()
            .ok_or(SymbolTextError::InvalidState("no open strip"))?;
        if !strip.has_instance {
            return Err(SymbolTextError::InvalidState(
                "subsequent instance before first",
            ));
        }
        strip.cursor_s = strip
            .cursor_s
            .checked_add(delta_s)
            .and_then(|value| value.checked_add(i64::from(self.config.s_offset)))
            .ok_or(MalformedError::IntegerOverflow)?;
        self.place_current(within_strip_t, width, height, limits, resources)
    }

    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
        requires symbol_text_spec::text_state_valid(old(self)),
        ensures match out {
            Ok(placement) =>
                symbol_text_spec::text_state_valid(final(self))
                && final(self).decoded_instances == old(self).decoded_instances + 1
                && final(self).strip.is_some()
                && symbol_text_spec::work_units(final(resources))
                    <= limits.max_work_units
                && symbol_text_spec::work_units(final(resources))
                    == symbol_text_spec::work_units(old(resources)) + 1
                && symbol_text_spec::placement_within_extents(placement, width, height)
                && symbol_text_spec::placement_for_current(
                    old(self), within_strip_t, width, height, placement
                ),
            Err(_) => true,
        },
        out.is_ok() == symbol_text_spec::text_placement_allowed(
            old(self), within_strip_t, width, height, old(resources), limits,
        ),
    ))]
    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
    pub(super) fn place_current(
        &mut self,
        within_strip_t: u8,
        width: u32,
        height: u32,
        limits: &Limits,
        resources: &mut ResourceTracker,
    ) -> Result<Placement, SymbolTextError> {
        if width == 0 || height == 0 {
            return Err(SymbolTextError::InvalidDimensions);
        }
        if within_strip_t >= self.config.strip_size {
            return Err(SymbolTextError::InvalidEntropyValue(
                "within-strip T coordinate",
            ));
        }
        if self.decoded_instances >= self.declared_instances {
            return Err(SymbolTextError::InvalidCount("too many text instances"));
        }
        resources.charge_work(1, limits)?;
        let strip = self
            .strip
            .as_mut()
            .ok_or(SymbolTextError::InvalidState("no open strip"))?;
        let width_extent = widen_u32_i64(width) - 1;
        let height_extent = widen_u32_i64(height) - 1;
        if (!self.config.transposed
            && matches!(
                self.config.reference_corner,
                ReferenceCorner::TopRight | ReferenceCorner::BottomRight
            ))
            || (self.config.transposed
                && matches!(
                    self.config.reference_corner,
                    ReferenceCorner::BottomLeft | ReferenceCorner::BottomRight
                ))
        {
            let extent = if self.config.transposed {
                height_extent
            } else {
                width_extent
            };
            strip.cursor_s = strip
                .cursor_s
                .checked_add(extent)
                .ok_or(MalformedError::IntegerOverflow)?;
        }
        let symbol_s = strip.cursor_s;
        let symbol_t = self
            .strip_t
            .checked_add(widen_u8_i64(within_strip_t))
            .ok_or(MalformedError::IntegerOverflow)?;
        let (reference_x, reference_y) = if self.config.transposed {
            (symbol_t, symbol_s)
        } else {
            (symbol_s, symbol_t)
        };
        let x = match self.config.reference_corner {
            ReferenceCorner::TopLeft | ReferenceCorner::BottomLeft => reference_x,
            ReferenceCorner::TopRight | ReferenceCorner::BottomRight => reference_x
                .checked_sub(width_extent)
                .ok_or(MalformedError::IntegerOverflow)?,
        };
        let y = match self.config.reference_corner {
            ReferenceCorner::TopLeft | ReferenceCorner::TopRight => reference_y,
            ReferenceCorner::BottomLeft | ReferenceCorner::BottomRight => reference_y
                .checked_sub(height_extent)
                .ok_or(MalformedError::IntegerOverflow)?,
        };
        if (!self.config.transposed
            && matches!(
                self.config.reference_corner,
                ReferenceCorner::TopLeft | ReferenceCorner::BottomLeft
            ))
            || (self.config.transposed
                && matches!(
                    self.config.reference_corner,
                    ReferenceCorner::TopLeft | ReferenceCorner::TopRight
                ))
        {
            let extent = if self.config.transposed {
                height_extent
            } else {
                width_extent
            };
            strip.cursor_s = strip
                .cursor_s
                .checked_add(extent)
                .ok_or(MalformedError::IntegerOverflow)?;
        }
        strip.has_instance = true;
        self.decoded_instances = self
            .decoded_instances
            .checked_add(1)
            .ok_or(MalformedError::IntegerOverflow)?;
        #[cfg(verus_keep_ghost)]
        production_symbol_current_placement_witness!(self, within_strip_t, width, height, x, y);
        Ok(Placement { x, y })
    }

    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
        requires symbol_text_spec::text_state_valid(old(self)),
        ensures match out {
            Ok(()) =>
                symbol_text_spec::text_state_valid(final(self))
                && final(self).strip.is_none()
                && final(self).decoded_instances == old(self).decoded_instances,
            Err(_) => true,
        },
    ))]
    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
    pub(crate) fn end_strip(&mut self) -> Result<(), SymbolTextError> {
        let strip = self
            .strip
            .take()
            .ok_or(SymbolTextError::InvalidState("no open strip"))?;
        if !strip.has_instance {
            return Err(SymbolTextError::InvalidState("empty text strip"));
        }
        Ok(())
    }

    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
        requires symbol_text_spec::text_state_valid(&self),
        ensures match out {
            Ok(()) =>
                self.strip.is_none()
                && self.decoded_instances == self.declared_instances,
            Err(_) => true,
        },
    ))]
    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
    pub(crate) fn finish(self) -> Result<(), SymbolTextError> {
        if self.strip.is_some() {
            return Err(SymbolTextError::InvalidState("text strip still open"));
        }
        if self.decoded_instances != self.declared_instances {
            return Err(SymbolTextError::InvalidCount(
                "text instance count mismatch",
            ));
        }
        Ok(())
    }
}

/// The base-two logarithm of a strip size that is always a power of two
/// (T.88 7.4.3.1.1's two-bit `LOGSBSTRIPS` field).
#[cfg_attr(verus_keep_ghost, verus_spec(out =>
    requires symbol_text_spec::valid_strip_size(strip_size),
    ensures symbol_text_spec::strip_log_valid(strip_size, out),
))]
pub(super) fn log2_strip_size(strip_size: u8) -> u8 {
    if strip_size <= 1 {
        0
    } else if strip_size <= 3 {
        1
    } else if strip_size <= 7 {
        2
    } else if strip_size <= 15 {
        3
    } else if strip_size <= 31 {
        4
    } else if strip_size <= 63 {
        5
    } else if strip_size <= 127 {
        6
    } else {
        7
    }
}

/// Decodes one complete text-region bitmap (T.88 6.4), shared by top-level
/// text-region segments and the nested multiple-instance aggregate
/// procedure invoked from a symbol dictionary (T.88 6.5.8.2.1).
///
/// `code_length` is the fixed IAID bit width for the whole enclosing segment;
/// `available_symbols` is the (possibly
/// smaller, for a nested aggregate call still in progress) slice used both
/// to validate decoded IDs and to look up referenced bitmaps.
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
#[cfg_attr(verus_keep_ghost, verus_spec(out =>
    requires
        symbol_text_spec::codec_valid(old(codec)),
        symbol_text_spec::codebook_valid(available_symbols),
        symbol_text_spec::work_units(old(resources)) <= limits.max_work_units,
    ensures match out {
        Ok(bitmap) =>
            symbol_text_spec::codec_valid(final(codec))
                && crate::spec::bitmap::storage_valid(&bitmap)
                && crate::views::bitmap_width(&bitmap) == width
                && crate::views::bitmap_height(&bitmap) == height
                && symbol_text_spec::work_units(final(resources))
                    <= limits.max_work_units,
        Err(_) => true,
    },
))]
pub(super) fn decode_text_region_body(
    codec: &mut SymbolCodec<'_>,
    available_symbols: SymbolCodebook<'_>,
    code_length: u8,
    width: u32,
    height: u32,
    number_of_instances: u32,
    config: &TextRegionConfig,
    refinement_adaptive: [(i8, i8); 2],
    limits: &Limits,
    resources: &mut ResourceTracker,
) -> Result<Bitmap, SymbolTextError> {
    decode_text_region_body_with_end(
        codec,
        available_symbols,
        code_length,
        width,
        height,
        number_of_instances,
        config,
        refinement_adaptive,
        limits,
        resources,
        &mut TextRegionEnd::Strict,
    )
}

#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
#[cfg_attr(verus_keep_ghost, verus_spec(out =>
    requires
        symbol_text_spec::codec_valid(old(codec)),
        symbol_text_spec::codebook_valid(available_symbols),
        symbol_text_spec::work_units(old(resources)) <= limits.max_work_units,
        *old(end) == TextRegionEnd::Strict || *old(end) == TextRegionEnd::BoundedHuffman
            || *old(end) == TextRegionEnd::BoundedArithmetic,
    ensures match out {
        Ok(bitmap) =>
            symbol_text_spec::codec_valid(final(codec))
                && crate::spec::bitmap::storage_valid(&bitmap)
                && crate::views::bitmap_width(&bitmap) == width
                && crate::views::bitmap_height(&bitmap) == height
                && symbol_text_spec::work_units(final(resources)) <= limits.max_work_units
                && match *final(end) {
                    TextRegionEnd::RecoveredHuffman { instances, padding_start } =>
                        *old(end) == TextRegionEnd::BoundedHuffman
                        && instances == number_of_instances && instances > 0
                        && !config.refinement
                        && match *final(codec) {
                            SymbolCodec::Huffman(h) =>
                                padding_start <= h.reader.bit_position
                                && h.reader.bit_position - padding_start < 8
                                && h.reader.bit_position == h.reader.bytes@.len() * 8,
                            _ => false,
                        },
                    TextRegionEnd::RecoveredArithmetic { instances } =>
                        *old(end) == TextRegionEnd::BoundedArithmetic
                        && instances == number_of_instances && instances > 0
                        && symbol_text_spec::text_end_matches_count(*final(end),
                            final(codec), number_of_instances, config.refinement),
                    _ => *final(end) == *old(end),
                },
        Err(_) => true,
    },
))]
pub(super) fn decode_text_region_body_with_end(
    codec: &mut SymbolCodec<'_>,
    available_symbols: SymbolCodebook<'_>,
    code_length: u8,
    width: u32,
    height: u32,
    number_of_instances: u32,
    config: &TextRegionConfig,
    refinement_adaptive: [(i8, i8); 2],
    limits: &Limits,
    resources: &mut ResourceTracker,
    end: &mut TextRegionEnd,
) -> Result<Bitmap, SymbolTextError> {
    #[cfg(verus_keep_ghost)]
    proof_decl! { let ghost initial_end = *end; }
    resources.charge_bitmap(width, height, limits)?;
    let mut bitmap = Bitmap::filled(width, height, config.default_pixel, limits)?;
    let mut placement_batch = PlacementBatch::new();
    if !config.refinement {
        placement_batch.reserve(
            usize::try_from(number_of_instances).map_err(|_| MalformedError::IntegerOverflow)?,
            limits,
        )?;
    }
    #[cfg(verus_keep_ghost)]
    proof! {
        reveal(symbol_text_spec::placement_batch_valid);
    }

    let initial_strip = required_integer(codec, IntegerField::StripDelta)?;
    let mut state = TextRegionState::new(*config, number_of_instances, initial_strip, limits)?;

    let available_count =
        u32::try_from(available_symbols.len()).map_err(|_| MalformedError::IntegerOverflow)?;

    let mut decoded = 0_u32;
    let mut recovered_padding = None;
    let mut recovered_arithmetic = false;
    #[cfg_attr(verus_keep_ghost, verus_spec(
        invariant
            decoded <= number_of_instances,
            state.decoded_instances == decoded,
            state.strip.is_none(),
            symbol_text_spec::text_state_valid(&state),
            symbol_text_spec::codec_valid(codec),
            symbol_text_spec::codebook_valid(available_symbols),
            available_count as nat == symbol_text_spec::codebook_len(available_symbols),
            crate::spec::bitmap::storage_valid(&bitmap),
            crate::views::bitmap_width(&bitmap) == width,
            crate::views::bitmap_height(&bitmap) == height,
            symbol_text_spec::placement_batch_valid(&placement_batch, &bitmap),
            symbol_text_spec::work_units(resources) <= limits.max_work_units,
            initial_end == *old(end),
            *end == initial_end,
            recovered_arithmetic ==> (
                initial_end == TextRegionEnd::BoundedArithmetic
                && decoded == number_of_instances
                && symbol_text_spec::text_end_matches_count(
                    TextRegionEnd::RecoveredArithmetic { instances: decoded },
                    codec, decoded, config.refinement)
            ),
            recovered_padding.is_some() ==> (
                initial_end == TextRegionEnd::BoundedHuffman
                && decoded == number_of_instances
                && symbol_text_spec::text_end_matches_count(
                    TextRegionEnd::RecoveredHuffman { instances: decoded, padding_start: recovered_padding.unwrap() },
                    codec, decoded, config.refinement,
                )
            ),
        decreases number_of_instances - decoded,
    ))]
    while decoded < number_of_instances {
        let strip_start = decoded;
        let strip_delta = required_integer(codec, IntegerField::StripDelta)?;
        let first_s_delta = required_integer(codec, IntegerField::FirstS)?;
        state.begin_strip(strip_delta, first_s_delta)?;
        let mut first = true;
        #[cfg_attr(verus_keep_ghost, verus_spec(
            invariant
                decoded <= number_of_instances,
                strip_start <= decoded,
                strip_start < number_of_instances,
                first ==> decoded == strip_start,
                !first ==> decoded > strip_start,
                state.decoded_instances == decoded,
                state.strip.is_some(),
                symbol_text_spec::text_state_valid(&state),
                symbol_text_spec::codec_valid(codec),
                symbol_text_spec::codebook_valid(available_symbols),
                available_count as nat == symbol_text_spec::codebook_len(available_symbols),
                crate::spec::bitmap::storage_valid(&bitmap),
                crate::views::bitmap_width(&bitmap) == width,
                crate::views::bitmap_height(&bitmap) == height,
                symbol_text_spec::placement_batch_valid(&placement_batch, &bitmap),
                symbol_text_spec::work_units(resources) <= limits.max_work_units,
                *end == initial_end,
            invariant_except_break
                recovered_padding.is_none(), !recovered_arithmetic,
            ensures
                recovered_arithmetic ==> (
                    initial_end == TextRegionEnd::BoundedArithmetic
                    && decoded == number_of_instances
                    && symbol_text_spec::text_end_matches_count(
                        TextRegionEnd::RecoveredArithmetic { instances: decoded },
                        codec, decoded, config.refinement)
                ),
                symbol_text_spec::codec_valid(codec),
                recovered_padding.is_none() || (
                    initial_end == TextRegionEnd::BoundedHuffman
                    && decoded == number_of_instances
                    && symbol_text_spec::text_end_matches_count(
                        TextRegionEnd::RecoveredHuffman { instances: decoded, padding_start: recovered_padding.unwrap() },
                        codec, decoded, config.refinement,
                    )
                ),
            decreases number_of_instances - decoded,
        ))]
        loop {
            if decoded == number_of_instances
                && matches!(end, TextRegionEnd::BoundedArithmetic)
                && !config.refinement
            {
                if let SymbolCodec::Arithmetic(arithmetic) = codec {
                    recovered_arithmetic = arithmetic.decode_final_strip(decoded)?;
                    break;
                }
            }
            if decoded == number_of_instances
                && matches!(end, TextRegionEnd::BoundedHuffman)
                && !config.refinement
            {
                if let SymbolCodec::Huffman(huffman) = codec {
                    let table = huffman.tables.table_for(IntegerField::SubsequentS).ok_or(
                        SymbolTextError::InvalidTableAssociation(
                            "no Huffman table bound for field",
                        ),
                    )?;
                    let padding_start = huffman.reader.bit_position;
                    match table.decode_final_strip_value(&mut huffman.reader)? {
                        Some(HuffmanValue::OutOfBand) => break,
                        Some(HuffmanValue::Integer(_)) => {
                            return Err(SymbolTextError::InvalidCount("too many text instances"));
                        }
                        None => {
                            #[cfg(verus_keep_ghost)]
                            proof! {
                                assert(decoded > 0);
                                assert(padding_start <= huffman.reader.bit_position);
                                assert(huffman.reader.bit_position - padding_start < 8);
                            }
                            recovered_padding = Some(padding_start);
                            #[cfg(verus_keep_ghost)]
                            proof! {
                                assert(initial_end == TextRegionEnd::BoundedHuffman);
                                assert(decoded == number_of_instances);
                                assert(symbol_text_spec::text_end_matches_count(
                                    TextRegionEnd::RecoveredHuffman { instances: decoded, padding_start },
                                    codec, decoded, config.refinement,
                                ));
                            }
                            break;
                        }
                    }
                }
            }
            let delta_s = if first {
                None
            } else {
                match codec.decode_integer(IntegerField::SubsequentS)? {
                    EntropyInteger::Value(value) => Some(value),
                    EntropyInteger::OutOfBand => {
                        #[cfg(verus_keep_ghost)]
                        proof! {
                            assert(decoded > strip_start);
                        }
                        break;
                    }
                }
            };
            if decoded >= number_of_instances {
                return Err(SymbolTextError::InvalidCount("too many text instances"));
            }
            let within_strip_t = if config.strip_size > 1 {
                match codec.decode_integer(IntegerField::WithinStripT)? {
                    EntropyInteger::Value(value) => u8::try_from(value).map_err(|_| {
                        SymbolTextError::InvalidEntropyValue("within-strip T coordinate")
                    })?,
                    EntropyInteger::OutOfBand => {
                        return Err(SymbolTextError::UnexpectedOutOfBand(
                            "within-strip T coordinate",
                        ))
                    }
                }
            } else {
                0
            };
            let id_request = SymbolIdRequest {
                available_symbols: available_count,
                code_length,
                huffman: config.huffman,
            };
            #[cfg(verus_keep_ghost)]
            production_symbol_id_request!(
                id_request,
                symbol_text_spec::codebook_len(available_symbols),
                code_length,
                config.huffman
            );
            let symbol_id = decode_checked_symbol_id(codec, id_request)?;
            let base_symbol = available_symbols
                .get(usize::try_from(symbol_id).map_err(|_| MalformedError::IntegerOverflow)?)
                .ok_or(SymbolTextError::SymbolIdOutOfRange {
                    id: symbol_id,
                    available: available_count,
                })?;

            let refined_storage;
            let placed_bitmap: &Bitmap = if config.refinement {
                let indicator = match codec.decode_integer(IntegerField::RefinementIndicator)? {
                    EntropyInteger::Value(value) => value,
                    EntropyInteger::OutOfBand => {
                        return Err(SymbolTextError::UnexpectedOutOfBand("refinement indicator"))
                    }
                };
                if indicator != 0 {
                    refined_storage = Some(decode_refined_bitmap(
                        codec,
                        base_symbol,
                        config.refinement_template,
                        refinement_adaptive,
                        config.huffman,
                        limits,
                        resources,
                    )?);
                    refined_storage.as_ref().unwrap_or(base_symbol)
                } else {
                    base_symbol
                }
            } else {
                base_symbol
            };

            let symbol_width = placed_bitmap.width();
            let symbol_height = placed_bitmap.height();
            let placement = match delta_s {
                None => state.place_first(
                    within_strip_t,
                    symbol_width,
                    symbol_height,
                    limits,
                    resources,
                )?,
                Some(delta) => state.place_subsequent(
                    delta,
                    within_strip_t,
                    symbol_width,
                    symbol_height,
                    limits,
                    resources,
                )?,
            };
            if config.refinement {
                flush_placement_batch(&mut bitmap, &mut placement_batch, config.operator)?;
                compose_placement(
                    &mut bitmap,
                    placed_bitmap,
                    placement,
                    config.operator,
                    limits,
                    resources,
                )?;
            } else if let Some(prepared) =
                prepare_placement(&bitmap, base_symbol, placement, limits, resources)?
            {
                if !placement_batch.compatible(prepared) {
                    flush_placement_batch(&mut bitmap, &mut placement_batch, config.operator)?;
                }
                placement_batch.push(prepared, &bitmap)?;
            }

            decoded = decoded
                .checked_add(1)
                .ok_or(MalformedError::IntegerOverflow)?;
            first = false;
        }
        if decoded == strip_start {
            return Err(SymbolTextError::InvalidState("empty text strip"));
        }
        flush_placement_batch(&mut bitmap, &mut placement_batch, config.operator)?;
        state.end_strip()?;
    }
    if let Some(padding_start) = recovered_padding {
        *end = TextRegionEnd::RecoveredHuffman {
            instances: decoded,
            padding_start,
        };
    }
    if recovered_arithmetic {
        *end = TextRegionEnd::RecoveredArithmetic { instances: decoded };
    }
    flush_placement_batch(&mut bitmap, &mut placement_batch, config.operator)?;
    state.finish()?;
    Ok(bitmap)
}

mod body;
mod segment;
pub(crate) use segment::{decode_text_region, decode_text_region_into};