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
//! Explicit, bounded recovery of supported embedded metadata inconsistencies.

use super::embedded_recoveries::{
    apply_embedded_edits, collect_segment_windows, plan_pre_page_resource_recoveries,
    plan_retention_recoveries,
};
use super::embedded_stripes::{
    plan_end_of_stripe_recoveries, record_arithmetic_marker, record_page_flags, required_flags,
};
use super::{
    allocation_size, build_document_info, enforce_input_work, enforce_stream_limit,
    enforce_work_limit, parse_sequential, DecodeError, Decoder, DecoderContext, DocumentInfo,
    GlobalSegments, LimitExceeded, LimitKind, Limits, MalformedError, Organization, ParsedData,
    ParsedSegment, SegmentType,
};
#[cfg(verus_keep_ghost)]
use vstd::prelude::*;

/// Caller-selected policy for embedded JBIG2 streams. Existing APIs stay strict.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(verus_keep_ghost, verus_verify)]
pub enum EmbeddedPolicy {
    /// Apply the same validation as the existing embedded entry points.
    Strict,
    /// Allow only the documented metadata, flag, stripe, and complete-marker recoveries.
    BestEffort,
}

/// A metadata inconsistency explicitly recovered by the embedded policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(verus_keep_ghost, verus_verify)]
pub enum EmbeddedRecoveryKind {
    /// A page used an intermediate region despite its auxiliary-buffer flag.
    AuxiliaryBuffersFlag,
    /// A page used a refinement region despite its refinement-capability flag.
    RefinementsFlag,
    /// A complete known-length arithmetic generic region ended in FF D0.
    ///
    /// BYTEIN treats this existing marker identically to FF AC; only its
    /// nonstandard terminator code is normalized. Missing bytes are never added.
    ArithmeticTerminatorCode,
    /// Missing advisory retention flag (`retain_this_segment` or
    /// `retain_referred_segment`) on a segment still referenced by a later
    /// segment in the stream or page.
    RetentionFlags,
    /// Exclusive (1-based) or leading-zero `EndOfStripe` row on a known-height
    /// striped page where a subsequent region starts at that exact row.
    EndOfStripeExclusiveRow,
    /// A page-associated non-drawing resource segment (`SymbolDictionary`,
    /// `PatternDictionary`, or `Tables`) appeared before its page's
    /// `PageInformation` segment and was re-associated to page 0.
    PrePageResourceAssociation,
}

/// One allowlisted metadata or complete-marker override.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(verus_keep_ghost, verus_verify)]
pub struct EmbeddedRecovery {
    /// Segment whose metadata or complete terminator was overridden.
    pub segment: u32,
    /// Affected page number.
    pub page: u32,
    /// Offset of the overridden byte in the supplied stream.
    pub byte_offset: usize,
    /// The specific, allowlisted recovery.
    pub kind: EmbeddedRecoveryKind,
}

/// Successful embedded output and explicit recovery diagnostics.
///
/// An empty `recoveries` list means no source metadata was overridden. Errors
/// never return a partial bitmap. The supplied source and globals are immutable.
#[derive(Debug)]
#[cfg_attr(verus_keep_ghost, verus_verify)]
pub struct EmbeddedResult<T> {
    /// Inspected metadata or completely decoded document.
    pub value: T,
    /// Every applied recovery, in source page-information order.
    pub recoveries: Vec<EmbeddedRecovery>,
}

#[cfg_attr(verus_keep_ghost, verus_verify)]
pub(crate) struct PreparedEmbedded {
    bytes: Option<Vec<u8>>,
    recoveries: Vec<EmbeddedRecovery>,
    pub(crate) limits: Limits,
}

#[cfg(verus_keep_ghost)]
verus! {
    pub(crate) closed spec fn recovery_view(prepared: &PreparedEmbedded) -> Seq<EmbeddedRecovery> {
        prepared.recoveries@
    }

    pub(crate) closed spec fn limits_view(prepared: &PreparedEmbedded) -> Limits {
        prepared.limits
    }

    pub(crate) closed spec fn bytes_view(prepared: &PreparedEmbedded) -> Option<Seq<u8>> {
        match prepared.bytes {
            Some(ref bytes) => Some(bytes@),
            None => None,
        }
    }
}

impl PreparedEmbedded {
    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
        ensures out == limits_view(self),
    ))]
    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
    pub(crate) fn limits(&self) -> Limits {
        #[cfg(verus_keep_ghost)]
        proof! { reveal(limits_view); }
        self.limits
    }

    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
        ensures out@ == match bytes_view(self) {
            Some(bytes) => bytes,
            None => original@,
        },
    ))]
    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
    pub(crate) fn input<'a>(&'a self, original: &'a [u8]) -> &'a [u8] {
        #[cfg(verus_keep_ghost)]
        proof! { reveal(bytes_view); }
        match self.bytes.as_ref() {
            Some(bytes) => bytes,
            None => original,
        }
    }

    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
        ensures match result {
            Ok(value) => match out {
                Ok(output) => output.value == value && output.recoveries@ == recovery_view(&self),
                Err(_) => false,
            },
            Err(error) => out == Err(error),
        },
    ))]
    pub(crate) fn finish<T>(
        self,
        result: Result<T, DecodeError>,
    ) -> Result<EmbeddedResult<T>, DecodeError> {
        #[cfg(verus_keep_ghost)]
        proof! { reveal(recovery_view); }
        Ok(EmbeddedResult {
            value: result?,
            recoveries: self.recoveries,
        })
    }
}

#[cfg_attr(verus_keep_ghost, verus_spec(out =>
    ensures out.is_ok() == (actual <= limit),
))]
pub(super) fn budget(kind: LimitKind, actual: u64, limit: u64) -> Result<(), DecodeError> {
    if actual > limit {
        return Err(LimitExceeded {
            kind,
            limit,
            actual,
        }
        .into());
    }
    Ok(())
}

#[cfg_attr(verus_keep_ghost, verus_spec(out =>
    ensures match out {
        Ok(()) => final(recoveries)@ == old(recoveries)@.push(recovery),
        Err(_) => final(recoveries)@ == old(recoveries)@,
    },
))]
pub(super) fn record(
    recoveries: &mut Vec<EmbeddedRecovery>,
    recovery: EmbeddedRecovery,
    input_bytes: u64,
    limits: &Limits,
) -> Result<(), DecodeError> {
    let count = recoveries
        .len()
        .checked_add(1)
        .ok_or(MalformedError::IntegerOverflow)?;
    let bytes = allocation_size::<EmbeddedRecovery>(count)?;
    let total = input_bytes
        .checked_add(bytes)
        .ok_or(MalformedError::IntegerOverflow)?;
    budget(
        LimitKind::RetainedState,
        total,
        limits.max_retained_state_bytes,
    )?;
    budget(
        LimitKind::Memory,
        total,
        limits.max_decoder_managed_memory_bytes,
    )?;
    recoveries
        .try_reserve(1)
        .map_err(|_| DecodeError::Allocation {
            requested_bytes: bytes,
        })?;
    recoveries.push(recovery);
    Ok(())
}

#[cfg_attr(verus_keep_ghost, verus_spec(out =>
    ensures match out {
        Ok((prepared, parsed)) =>
            (policy == EmbeddedPolicy::Strict ==> (
                bytes_view(&prepared).is_none()
                && recovery_view(&prepared).len() == 0
                && limits_view(&prepared) == *limits
                && parsed.is_none()
            ))
            && limits_view(&prepared).max_work_units <= limits.max_work_units
            && limits_view(&prepared).max_retained_state_bytes <= limits.max_retained_state_bytes
            && limits_view(&prepared).max_decoder_managed_memory_bytes
                <= limits.max_decoder_managed_memory_bytes
            && match bytes_view(&prepared) {
                Some(bytes) => bytes.len() <= input@.len() && parsed.is_none(),
                None => true,
            }
            && match parsed {
                Some((info, _)) => super::document_spec::embedded_metadata(&info),
                None => true,
            },
        Err(_) => true,
    },
))]
#[allow(clippy::too_many_lines, clippy::type_complexity)]
pub(crate) fn prepare_for_decode<'a>(
    input: &'a [u8],
    globals: Option<&GlobalSegments>,
    policy: EmbeddedPolicy,
    limits: &Limits,
) -> Result<
    (
        PreparedEmbedded,
        Option<(DocumentInfo, Vec<ParsedSegment<'a>>)>,
    ),
    DecodeError,
> {
    if let EmbeddedPolicy::Strict = policy {
        let prepared = PreparedEmbedded {
            bytes: None,
            recoveries: Vec::new(),
            limits: *limits,
        };
        #[cfg(verus_keep_ghost)]
        proof! {
            reveal(bytes_view);
            reveal(recovery_view);
            reveal(limits_view);
        }
        return Ok((prepared, None));
    }
    enforce_stream_limit(input.len(), limits)?;
    enforce_input_work(input.len(), limits)?;
    let parsed_segments = parse_sequential(input, limits, false)?;
    enforce_work_limit(input.len(), &parsed_segments, limits)?;
    let windows = collect_segment_windows(&parsed_segments, input.len())?;

    let input_bytes = u64::try_from(input.len()).map_err(|_| MalformedError::IntegerOverflow)?;
    let count =
        u64::try_from(parsed_segments.len()).map_err(|_| MalformedError::IntegerOverflow)?;
    let mut page_count = 0_u64;
    let mut pc_idx = 0_usize;
    #[cfg_attr(verus_keep_ghost, verus_spec(
        invariant pc_idx <= parsed_segments@.len(),
        decreases parsed_segments@.len() - pc_idx,
    ))]
    while pc_idx < parsed_segments.len() {
        if matches!(
            parsed_segments[pc_idx].header.segment_type,
            SegmentType::PageInformation
        ) {
            page_count = page_count
                .checked_add(1)
                .ok_or(MalformedError::IntegerOverflow)?;
        }
        pc_idx += 1;
    }
    let references = super::references::count_total_references(&parsed_segments)?;
    let mut extra_work = count
        .checked_mul(page_count)
        .and_then(|work| work.checked_add(input_bytes))
        .and_then(|work| work.checked_add(count))
        .and_then(|work| work.checked_add(references))
        .ok_or(MalformedError::IntegerOverflow)?;
    budget(LimitKind::Work, extra_work, limits.max_work_units)?;

    let mut recoveries = Vec::new();
    let mut edits = Vec::new();

    plan_pre_page_resource_recoveries(
        input,
        &parsed_segments,
        &windows,
        &mut recoveries,
        &mut edits,
        input_bytes,
        limits,
    )?;
    plan_retention_recoveries(
        input,
        &parsed_segments,
        &windows,
        globals,
        &mut recoveries,
        &mut edits,
        input_bytes,
        limits,
    )?;
    plan_end_of_stripe_recoveries(
        input,
        &parsed_segments,
        &windows,
        &mut recoveries,
        &mut edits,
        input_bytes,
        limits,
    )?;

    let mut index = 0_usize;
    #[cfg_attr(verus_keep_ghost, verus_spec(
        invariant
            index <= parsed_segments@.len(),
            windows@.len() == parsed_segments@.len(),
        decreases parsed_segments@.len() - index,
    ))]
    while index < parsed_segments.len() {
        let segment = &parsed_segments[index];
        let payload_start = windows[index].payload_start;
        if let ParsedData::Page(_) = segment.data {
            let flag_offset = payload_start
                .checked_add(16)
                .ok_or(MalformedError::IntegerOverflow)?;
            let flags = *input
                .get(flag_offset)
                .ok_or(MalformedError::InvalidPageState(
                    "page-information flag offset is outside the stream",
                ))?;
            let required = required_flags(&parsed_segments, segment.header.page_association);
            record_page_flags(
                &mut recoveries,
                &mut edits,
                &segment.header,
                flag_offset,
                flags,
                required,
                input_bytes,
                limits,
            )?;
        } else {
            record_arithmetic_marker(
                &mut recoveries,
                &mut edits,
                segment,
                payload_start,
                input_bytes,
                limits,
            )?;
        }
        index += 1;
    }

    let retained = if recoveries.is_empty() {
        0
    } else {
        input_bytes
            .checked_add(allocation_size::<EmbeddedRecovery>(recoveries.len())?)
            .ok_or(MalformedError::IntegerOverflow)?
    };
    let (bytes, parsed) = if recoveries.is_empty() {
        let info = build_document_info(
            Organization::Sequential,
            None,
            &parsed_segments,
            limits,
            globals,
            true,
        )?;
        (None, Some((info, parsed_segments)))
    } else {
        extra_work = extra_work
            .checked_add(input_bytes)
            .ok_or(MalformedError::IntegerOverflow)?;
        budget(LimitKind::Work, extra_work, limits.max_work_units)?;
        (Some(apply_embedded_edits(input, &edits)?), None)
    };
    let mut remaining = *limits;
    remaining.max_work_units = remaining
        .max_work_units
        .checked_sub(extra_work)
        .ok_or(MalformedError::IntegerOverflow)?;
    remaining.max_retained_state_bytes = remaining
        .max_retained_state_bytes
        .checked_sub(retained)
        .ok_or(MalformedError::IntegerOverflow)?;
    remaining.max_decoder_managed_memory_bytes = remaining
        .max_decoder_managed_memory_bytes
        .checked_sub(retained)
        .ok_or(MalformedError::IntegerOverflow)?;
    let prepared = PreparedEmbedded {
        bytes,
        recoveries,
        limits: remaining,
    };
    #[cfg(verus_keep_ghost)]
    proof! {
        reveal(bytes_view);
        reveal(limits_view);
    }
    Ok((prepared, parsed))
}

#[cfg_attr(verus_keep_ghost, verus_spec(out =>
    ensures match out {
        Ok(prepared) =>
            (policy == EmbeddedPolicy::Strict ==> (
                bytes_view(&prepared).is_none()
                && recovery_view(&prepared).len() == 0
                && limits_view(&prepared) == *limits
            ))
            && limits_view(&prepared).max_work_units <= limits.max_work_units
            && limits_view(&prepared).max_retained_state_bytes <= limits.max_retained_state_bytes
            && limits_view(&prepared).max_decoder_managed_memory_bytes
                <= limits.max_decoder_managed_memory_bytes
            && match bytes_view(&prepared) {
                Some(bytes) => bytes.len() <= input@.len(),
                None => true,
            },
        Err(_) => true,
    },
))]
pub(crate) fn prepare(
    input: &[u8],
    globals: Option<&GlobalSegments>,
    policy: EmbeddedPolicy,
    limits: &Limits,
) -> Result<PreparedEmbedded, DecodeError> {
    let (prepared, _parsed) = prepare_for_decode(input, globals, policy, limits)?;
    Ok(prepared)
}

#[cfg_attr(verus_keep_ghost, verus_spec(out =>
    ensures match out {
        Ok(prepared) =>
            (policy == EmbeddedPolicy::Strict ==> (
                bytes_view(&prepared).is_none()
                && recovery_view(&prepared).len() == 0
                && limits_view(&prepared) == *limits
            ))
            && limits_view(&prepared).max_work_units <= limits.max_work_units
            && limits_view(&prepared).max_retained_state_bytes <= limits.max_retained_state_bytes
            && limits_view(&prepared).max_decoder_managed_memory_bytes
                <= limits.max_decoder_managed_memory_bytes
            && match bytes_view(&prepared) {
                Some(bytes) => bytes.len() <= input@.len(),
                None => true,
            },
        Err(_) => true,
    },
))]
pub(crate) fn prepare_globals(
    input: &[u8],
    policy: EmbeddedPolicy,
    limits: &Limits,
) -> Result<PreparedEmbedded, DecodeError> {
    if let EmbeddedPolicy::Strict = policy {
        let prepared = PreparedEmbedded {
            bytes: None,
            recoveries: Vec::new(),
            limits: *limits,
        };
        #[cfg(verus_keep_ghost)]
        proof! {
            reveal(bytes_view);
            reveal(recovery_view);
            reveal(limits_view);
        }
        return Ok(prepared);
    }
    enforce_stream_limit(input.len(), limits)?;
    enforce_input_work(input.len(), limits)?;
    let global_segments = parse_sequential(input, limits, false)?;
    let mut seg_idx = 0_usize;
    #[cfg_attr(verus_keep_ghost, verus_spec(
        invariant seg_idx <= global_segments@.len(),
        decreases global_segments@.len() - seg_idx,
    ))]
    while seg_idx < global_segments.len() {
        let seg = &global_segments[seg_idx];
        if seg.header.page_association != 0 {
            return Err(MalformedError::InvalidPageAssociation {
                segment: seg.header.number,
                page: seg.header.page_association,
            }
            .into());
        }
        seg_idx += 1;
    }
    enforce_work_limit(input.len(), &global_segments, limits)?;
    let windows = collect_segment_windows(&global_segments, input.len())?;

    let input_bytes = u64::try_from(input.len()).map_err(|_| MalformedError::IntegerOverflow)?;
    let count =
        u64::try_from(global_segments.len()).map_err(|_| MalformedError::IntegerOverflow)?;
    let references = super::references::count_total_references(&global_segments)?;
    let mut extra_work = input_bytes
        .checked_add(count)
        .and_then(|work| work.checked_add(references))
        .ok_or(MalformedError::IntegerOverflow)?;
    budget(LimitKind::Work, extra_work, limits.max_work_units)?;

    let mut recoveries = Vec::new();
    let mut edits = Vec::new();
    plan_retention_recoveries(
        input,
        &global_segments,
        &windows,
        None,
        &mut recoveries,
        &mut edits,
        input_bytes,
        limits,
    )?;

    let retained = if recoveries.is_empty() {
        0
    } else {
        input_bytes
            .checked_add(allocation_size::<EmbeddedRecovery>(recoveries.len())?)
            .ok_or(MalformedError::IntegerOverflow)?
    };
    let bytes = if recoveries.is_empty() {
        None
    } else {
        extra_work = extra_work
            .checked_add(input_bytes)
            .ok_or(MalformedError::IntegerOverflow)?;
        budget(LimitKind::Work, extra_work, limits.max_work_units)?;
        Some(apply_embedded_edits(input, &edits)?)
    };
    let mut remaining = *limits;
    remaining.max_work_units = remaining
        .max_work_units
        .checked_sub(extra_work)
        .ok_or(MalformedError::IntegerOverflow)?;
    remaining.max_retained_state_bytes = remaining
        .max_retained_state_bytes
        .checked_sub(retained)
        .ok_or(MalformedError::IntegerOverflow)?;
    remaining.max_decoder_managed_memory_bytes = remaining
        .max_decoder_managed_memory_bytes
        .checked_sub(retained)
        .ok_or(MalformedError::IntegerOverflow)?;
    let prepared = PreparedEmbedded {
        bytes,
        recoveries,
        limits: remaining,
    };
    #[cfg(verus_keep_ghost)]
    proof! {
        reveal(bytes_view);
        reveal(limits_view);
    }
    Ok(prepared)
}

impl Decoder {
    /// Inspects an embedded stream with an explicit, observable recovery policy.
    ///
    /// Best effort overrides inconsistent page auxiliary/refinement flags
    /// (T.88 7.4.8.5) and normalizes an existing FF D0 marker at the exact end of
    /// a known-length arithmetic generic region to FF AC (E.2.9, E.3.3).
    /// It never adds compressed data or repairs framing or dimensions.
    /// Preparation debits work and temporary storage from the existing budgets;
    /// any later resource error reports the remaining effective budget.
    ///
    /// # Errors
    ///
    /// Returns typed validation, resource or allocation errors. There is no retry.
    #[cfg_attr(verus_keep_ghost, verus_verify)]
    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
        ensures match out {
            Ok(output) => super::document_spec::embedded_metadata(&output.value),
            Err(_) => true,
        },
    ))]
    pub fn inspect_embedded_with_policy(
        &self,
        input: &[u8],
        globals: Option<&GlobalSegments>,
        policy: EmbeddedPolicy,
    ) -> Result<EmbeddedResult<DocumentInfo>, DecodeError> {
        let prepared = prepare(input, globals, policy, self.limits())?;
        let result =
            Decoder::new(prepared.limits).inspect_embedded_internal(prepared.input(input), globals);
        prepared.finish(result)
    }

    /// Parses and validates an immutable embedded global-segment stream with an
    /// explicit recovery policy.
    ///
    /// Under [`EmbeddedPolicy::BestEffort`], missing advisory retention flags
    /// on referenced global segments are normalized before running the strict
    /// [`Decoder::parse_globals`] validator.
    ///
    /// # Errors
    ///
    /// Returns the same typed errors as [`Decoder::parse_globals`].
    #[cfg_attr(verus_keep_ghost, verus_verify)]
    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
        ensures match out {
            Ok(output) => super::document_spec::global_segment_count(&output.value)
                == super::document_spec::global_depth_count(&output.value),
            Err(_) => true,
        },
    ))]
    pub fn parse_globals_with_policy(
        &self,
        input: &[u8],
        policy: EmbeddedPolicy,
    ) -> Result<EmbeddedResult<GlobalSegments>, DecodeError> {
        let prepared = prepare_globals(input, policy, self.limits())?;
        let result = Decoder::new(prepared.limits).parse_globals(prepared.input(input));
        prepared.finish(result)
    }
}

impl DecoderContext<'_> {
    /// Inspects with the explicit policy of [`Decoder::inspect_embedded_with_policy`].
    ///
    /// # Errors
    ///
    /// Returns the same typed errors and always performs normal context cleanup.
    #[cfg_attr(verus_keep_ghost, verus_verify)]
    #[cfg_attr(verus_keep_ghost, verus_spec(
        ensures super::document_spec::decoder_context_finished(old(self), final(self)),
    ))]
    pub fn inspect_embedded_with_policy(
        &mut self,
        input: &[u8],
        globals: Option<&GlobalSegments>,
        policy: EmbeddedPolicy,
    ) -> Result<EmbeddedResult<DocumentInfo>, DecodeError> {
        let result = self
            .decoder
            .inspect_embedded_with_policy(input, globals, policy);
        self.finish_call();
        result
    }

    /// Parses global segments with the explicit policy of
    /// [`Decoder::parse_globals_with_policy`].
    ///
    /// # Errors
    ///
    /// Returns the same typed errors and always performs normal context cleanup.
    #[cfg_attr(verus_keep_ghost, verus_verify)]
    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
        ensures
            super::document_spec::decoder_context_finished(old(self), final(self)),
            match out {
                Ok(output) => super::document_spec::global_segment_count(&output.value)
                    == super::document_spec::global_depth_count(&output.value),
                Err(_) => true,
            },
    ))]
    pub fn parse_globals_with_policy(
        &mut self,
        input: &[u8],
        policy: EmbeddedPolicy,
    ) -> Result<EmbeddedResult<GlobalSegments>, DecodeError> {
        let result = self.decoder.parse_globals_with_policy(input, policy);
        self.finish_call();
        result
    }
}