Skip to main content

jbig2_decoder/document/
embedded.rs

1//! Explicit, bounded recovery of supported embedded metadata inconsistencies.
2
3use super::embedded_recoveries::{
4    apply_embedded_edits, collect_segment_windows, plan_pre_page_resource_recoveries,
5    plan_retention_recoveries,
6};
7use super::embedded_stripes::{
8    plan_end_of_stripe_recoveries, record_arithmetic_marker, record_page_flags, required_flags,
9};
10use super::{
11    allocation_size, build_document_info, enforce_input_work, enforce_stream_limit,
12    enforce_work_limit, parse_sequential, DecodeError, Decoder, DecoderContext, DocumentInfo,
13    GlobalSegments, LimitExceeded, LimitKind, Limits, MalformedError, Organization, ParsedData,
14    ParsedSegment, SegmentType,
15};
16#[cfg(verus_keep_ghost)]
17use vstd::prelude::*;
18
19/// Caller-selected policy for embedded JBIG2 streams. Existing APIs stay strict.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21#[cfg_attr(verus_keep_ghost, verus_verify)]
22pub enum EmbeddedPolicy {
23    /// Apply the same validation as the existing embedded entry points.
24    Strict,
25    /// Allow only the documented metadata, flag, stripe, and complete-marker recoveries.
26    BestEffort,
27}
28
29/// A metadata inconsistency explicitly recovered by the embedded policy.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31#[cfg_attr(verus_keep_ghost, verus_verify)]
32pub enum EmbeddedRecoveryKind {
33    /// A page used an intermediate region despite its auxiliary-buffer flag.
34    AuxiliaryBuffersFlag,
35    /// A page used a refinement region despite its refinement-capability flag.
36    RefinementsFlag,
37    /// A complete known-length arithmetic generic region ended in FF D0.
38    ///
39    /// BYTEIN treats this existing marker identically to FF AC; only its
40    /// nonstandard terminator code is normalized. Missing bytes are never added.
41    ArithmeticTerminatorCode,
42    /// Missing advisory retention flag (`retain_this_segment` or
43    /// `retain_referred_segment`) on a segment still referenced by a later
44    /// segment in the stream or page.
45    RetentionFlags,
46    /// Exclusive (1-based) or leading-zero `EndOfStripe` row on a known-height
47    /// striped page where a subsequent region starts at that exact row.
48    EndOfStripeExclusiveRow,
49    /// A page-associated non-drawing resource segment (`SymbolDictionary`,
50    /// `PatternDictionary`, or `Tables`) appeared before its page's
51    /// `PageInformation` segment and was re-associated to page 0.
52    PrePageResourceAssociation,
53}
54
55/// One allowlisted metadata or complete-marker override.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57#[cfg_attr(verus_keep_ghost, verus_verify)]
58pub struct EmbeddedRecovery {
59    /// Segment whose metadata or complete terminator was overridden.
60    pub segment: u32,
61    /// Affected page number.
62    pub page: u32,
63    /// Offset of the overridden byte in the supplied stream.
64    pub byte_offset: usize,
65    /// The specific, allowlisted recovery.
66    pub kind: EmbeddedRecoveryKind,
67}
68
69/// Successful embedded output and explicit recovery diagnostics.
70///
71/// An empty `recoveries` list means no source metadata was overridden. Errors
72/// never return a partial bitmap. The supplied source and globals are immutable.
73#[derive(Debug)]
74#[cfg_attr(verus_keep_ghost, verus_verify)]
75pub struct EmbeddedResult<T> {
76    /// Inspected metadata or completely decoded document.
77    pub value: T,
78    /// Every applied recovery, in source page-information order.
79    pub recoveries: Vec<EmbeddedRecovery>,
80}
81
82#[cfg_attr(verus_keep_ghost, verus_verify)]
83pub(crate) struct PreparedEmbedded {
84    bytes: Option<Vec<u8>>,
85    recoveries: Vec<EmbeddedRecovery>,
86    pub(crate) limits: Limits,
87}
88
89#[cfg(verus_keep_ghost)]
90verus! {
91    pub(crate) closed spec fn recovery_view(prepared: &PreparedEmbedded) -> Seq<EmbeddedRecovery> {
92        prepared.recoveries@
93    }
94
95    pub(crate) closed spec fn limits_view(prepared: &PreparedEmbedded) -> Limits {
96        prepared.limits
97    }
98
99    pub(crate) closed spec fn bytes_view(prepared: &PreparedEmbedded) -> Option<Seq<u8>> {
100        match prepared.bytes {
101            Some(ref bytes) => Some(bytes@),
102            None => None,
103        }
104    }
105}
106
107impl PreparedEmbedded {
108    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
109        ensures out == limits_view(self),
110    ))]
111    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
112    pub(crate) fn limits(&self) -> Limits {
113        #[cfg(verus_keep_ghost)]
114        proof! { reveal(limits_view); }
115        self.limits
116    }
117
118    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
119        ensures out@ == match bytes_view(self) {
120            Some(bytes) => bytes,
121            None => original@,
122        },
123    ))]
124    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
125    pub(crate) fn input<'a>(&'a self, original: &'a [u8]) -> &'a [u8] {
126        #[cfg(verus_keep_ghost)]
127        proof! { reveal(bytes_view); }
128        match self.bytes.as_ref() {
129            Some(bytes) => bytes,
130            None => original,
131        }
132    }
133
134    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
135        ensures match result {
136            Ok(value) => match out {
137                Ok(output) => output.value == value && output.recoveries@ == recovery_view(&self),
138                Err(_) => false,
139            },
140            Err(error) => out == Err(error),
141        },
142    ))]
143    pub(crate) fn finish<T>(
144        self,
145        result: Result<T, DecodeError>,
146    ) -> Result<EmbeddedResult<T>, DecodeError> {
147        #[cfg(verus_keep_ghost)]
148        proof! { reveal(recovery_view); }
149        Ok(EmbeddedResult {
150            value: result?,
151            recoveries: self.recoveries,
152        })
153    }
154}
155
156#[cfg_attr(verus_keep_ghost, verus_spec(out =>
157    ensures out.is_ok() == (actual <= limit),
158))]
159pub(super) fn budget(kind: LimitKind, actual: u64, limit: u64) -> Result<(), DecodeError> {
160    if actual > limit {
161        return Err(LimitExceeded {
162            kind,
163            limit,
164            actual,
165        }
166        .into());
167    }
168    Ok(())
169}
170
171#[cfg_attr(verus_keep_ghost, verus_spec(out =>
172    ensures match out {
173        Ok(()) => final(recoveries)@ == old(recoveries)@.push(recovery),
174        Err(_) => final(recoveries)@ == old(recoveries)@,
175    },
176))]
177pub(super) fn record(
178    recoveries: &mut Vec<EmbeddedRecovery>,
179    recovery: EmbeddedRecovery,
180    input_bytes: u64,
181    limits: &Limits,
182) -> Result<(), DecodeError> {
183    let count = recoveries
184        .len()
185        .checked_add(1)
186        .ok_or(MalformedError::IntegerOverflow)?;
187    let bytes = allocation_size::<EmbeddedRecovery>(count)?;
188    let total = input_bytes
189        .checked_add(bytes)
190        .ok_or(MalformedError::IntegerOverflow)?;
191    budget(
192        LimitKind::RetainedState,
193        total,
194        limits.max_retained_state_bytes,
195    )?;
196    budget(
197        LimitKind::Memory,
198        total,
199        limits.max_decoder_managed_memory_bytes,
200    )?;
201    recoveries
202        .try_reserve(1)
203        .map_err(|_| DecodeError::Allocation {
204            requested_bytes: bytes,
205        })?;
206    recoveries.push(recovery);
207    Ok(())
208}
209
210#[cfg_attr(verus_keep_ghost, verus_spec(out =>
211    ensures match out {
212        Ok((prepared, parsed)) =>
213            (policy == EmbeddedPolicy::Strict ==> (
214                bytes_view(&prepared).is_none()
215                && recovery_view(&prepared).len() == 0
216                && limits_view(&prepared) == *limits
217                && parsed.is_none()
218            ))
219            && limits_view(&prepared).max_work_units <= limits.max_work_units
220            && limits_view(&prepared).max_retained_state_bytes <= limits.max_retained_state_bytes
221            && limits_view(&prepared).max_decoder_managed_memory_bytes
222                <= limits.max_decoder_managed_memory_bytes
223            && match bytes_view(&prepared) {
224                Some(bytes) => bytes.len() <= input@.len() && parsed.is_none(),
225                None => true,
226            }
227            && match parsed {
228                Some((info, _)) => super::document_spec::embedded_metadata(&info),
229                None => true,
230            },
231        Err(_) => true,
232    },
233))]
234#[allow(clippy::too_many_lines, clippy::type_complexity)]
235pub(crate) fn prepare_for_decode<'a>(
236    input: &'a [u8],
237    globals: Option<&GlobalSegments>,
238    policy: EmbeddedPolicy,
239    limits: &Limits,
240) -> Result<
241    (
242        PreparedEmbedded,
243        Option<(DocumentInfo, Vec<ParsedSegment<'a>>)>,
244    ),
245    DecodeError,
246> {
247    if let EmbeddedPolicy::Strict = policy {
248        let prepared = PreparedEmbedded {
249            bytes: None,
250            recoveries: Vec::new(),
251            limits: *limits,
252        };
253        #[cfg(verus_keep_ghost)]
254        proof! {
255            reveal(bytes_view);
256            reveal(recovery_view);
257            reveal(limits_view);
258        }
259        return Ok((prepared, None));
260    }
261    enforce_stream_limit(input.len(), limits)?;
262    enforce_input_work(input.len(), limits)?;
263    let parsed_segments = parse_sequential(input, limits, false)?;
264    enforce_work_limit(input.len(), &parsed_segments, limits)?;
265    let windows = collect_segment_windows(&parsed_segments, input.len())?;
266
267    let input_bytes = u64::try_from(input.len()).map_err(|_| MalformedError::IntegerOverflow)?;
268    let count =
269        u64::try_from(parsed_segments.len()).map_err(|_| MalformedError::IntegerOverflow)?;
270    let mut page_count = 0_u64;
271    let mut pc_idx = 0_usize;
272    #[cfg_attr(verus_keep_ghost, verus_spec(
273        invariant pc_idx <= parsed_segments@.len(),
274        decreases parsed_segments@.len() - pc_idx,
275    ))]
276    while pc_idx < parsed_segments.len() {
277        if matches!(
278            parsed_segments[pc_idx].header.segment_type,
279            SegmentType::PageInformation
280        ) {
281            page_count = page_count
282                .checked_add(1)
283                .ok_or(MalformedError::IntegerOverflow)?;
284        }
285        pc_idx += 1;
286    }
287    let references = super::references::count_total_references(&parsed_segments)?;
288    let mut extra_work = count
289        .checked_mul(page_count)
290        .and_then(|work| work.checked_add(input_bytes))
291        .and_then(|work| work.checked_add(count))
292        .and_then(|work| work.checked_add(references))
293        .ok_or(MalformedError::IntegerOverflow)?;
294    budget(LimitKind::Work, extra_work, limits.max_work_units)?;
295
296    let mut recoveries = Vec::new();
297    let mut edits = Vec::new();
298
299    plan_pre_page_resource_recoveries(
300        input,
301        &parsed_segments,
302        &windows,
303        &mut recoveries,
304        &mut edits,
305        input_bytes,
306        limits,
307    )?;
308    plan_retention_recoveries(
309        input,
310        &parsed_segments,
311        &windows,
312        globals,
313        &mut recoveries,
314        &mut edits,
315        input_bytes,
316        limits,
317    )?;
318    plan_end_of_stripe_recoveries(
319        input,
320        &parsed_segments,
321        &windows,
322        &mut recoveries,
323        &mut edits,
324        input_bytes,
325        limits,
326    )?;
327
328    let mut index = 0_usize;
329    #[cfg_attr(verus_keep_ghost, verus_spec(
330        invariant
331            index <= parsed_segments@.len(),
332            windows@.len() == parsed_segments@.len(),
333        decreases parsed_segments@.len() - index,
334    ))]
335    while index < parsed_segments.len() {
336        let segment = &parsed_segments[index];
337        let payload_start = windows[index].payload_start;
338        if let ParsedData::Page(_) = segment.data {
339            let flag_offset = payload_start
340                .checked_add(16)
341                .ok_or(MalformedError::IntegerOverflow)?;
342            let flags = *input
343                .get(flag_offset)
344                .ok_or(MalformedError::InvalidPageState(
345                    "page-information flag offset is outside the stream",
346                ))?;
347            let required = required_flags(&parsed_segments, segment.header.page_association);
348            record_page_flags(
349                &mut recoveries,
350                &mut edits,
351                &segment.header,
352                flag_offset,
353                flags,
354                required,
355                input_bytes,
356                limits,
357            )?;
358        } else {
359            record_arithmetic_marker(
360                &mut recoveries,
361                &mut edits,
362                segment,
363                payload_start,
364                input_bytes,
365                limits,
366            )?;
367        }
368        index += 1;
369    }
370
371    let retained = if recoveries.is_empty() {
372        0
373    } else {
374        input_bytes
375            .checked_add(allocation_size::<EmbeddedRecovery>(recoveries.len())?)
376            .ok_or(MalformedError::IntegerOverflow)?
377    };
378    let (bytes, parsed) = if recoveries.is_empty() {
379        let info = build_document_info(
380            Organization::Sequential,
381            None,
382            &parsed_segments,
383            limits,
384            globals,
385            true,
386        )?;
387        (None, Some((info, parsed_segments)))
388    } else {
389        extra_work = extra_work
390            .checked_add(input_bytes)
391            .ok_or(MalformedError::IntegerOverflow)?;
392        budget(LimitKind::Work, extra_work, limits.max_work_units)?;
393        (Some(apply_embedded_edits(input, &edits)?), None)
394    };
395    let mut remaining = *limits;
396    remaining.max_work_units = remaining
397        .max_work_units
398        .checked_sub(extra_work)
399        .ok_or(MalformedError::IntegerOverflow)?;
400    remaining.max_retained_state_bytes = remaining
401        .max_retained_state_bytes
402        .checked_sub(retained)
403        .ok_or(MalformedError::IntegerOverflow)?;
404    remaining.max_decoder_managed_memory_bytes = remaining
405        .max_decoder_managed_memory_bytes
406        .checked_sub(retained)
407        .ok_or(MalformedError::IntegerOverflow)?;
408    let prepared = PreparedEmbedded {
409        bytes,
410        recoveries,
411        limits: remaining,
412    };
413    #[cfg(verus_keep_ghost)]
414    proof! {
415        reveal(bytes_view);
416        reveal(limits_view);
417    }
418    Ok((prepared, parsed))
419}
420
421#[cfg_attr(verus_keep_ghost, verus_spec(out =>
422    ensures match out {
423        Ok(prepared) =>
424            (policy == EmbeddedPolicy::Strict ==> (
425                bytes_view(&prepared).is_none()
426                && recovery_view(&prepared).len() == 0
427                && limits_view(&prepared) == *limits
428            ))
429            && limits_view(&prepared).max_work_units <= limits.max_work_units
430            && limits_view(&prepared).max_retained_state_bytes <= limits.max_retained_state_bytes
431            && limits_view(&prepared).max_decoder_managed_memory_bytes
432                <= limits.max_decoder_managed_memory_bytes
433            && match bytes_view(&prepared) {
434                Some(bytes) => bytes.len() <= input@.len(),
435                None => true,
436            },
437        Err(_) => true,
438    },
439))]
440pub(crate) fn prepare(
441    input: &[u8],
442    globals: Option<&GlobalSegments>,
443    policy: EmbeddedPolicy,
444    limits: &Limits,
445) -> Result<PreparedEmbedded, DecodeError> {
446    let (prepared, _parsed) = prepare_for_decode(input, globals, policy, limits)?;
447    Ok(prepared)
448}
449
450#[cfg_attr(verus_keep_ghost, verus_spec(out =>
451    ensures match out {
452        Ok(prepared) =>
453            (policy == EmbeddedPolicy::Strict ==> (
454                bytes_view(&prepared).is_none()
455                && recovery_view(&prepared).len() == 0
456                && limits_view(&prepared) == *limits
457            ))
458            && limits_view(&prepared).max_work_units <= limits.max_work_units
459            && limits_view(&prepared).max_retained_state_bytes <= limits.max_retained_state_bytes
460            && limits_view(&prepared).max_decoder_managed_memory_bytes
461                <= limits.max_decoder_managed_memory_bytes
462            && match bytes_view(&prepared) {
463                Some(bytes) => bytes.len() <= input@.len(),
464                None => true,
465            },
466        Err(_) => true,
467    },
468))]
469pub(crate) fn prepare_globals(
470    input: &[u8],
471    policy: EmbeddedPolicy,
472    limits: &Limits,
473) -> Result<PreparedEmbedded, DecodeError> {
474    if let EmbeddedPolicy::Strict = policy {
475        let prepared = PreparedEmbedded {
476            bytes: None,
477            recoveries: Vec::new(),
478            limits: *limits,
479        };
480        #[cfg(verus_keep_ghost)]
481        proof! {
482            reveal(bytes_view);
483            reveal(recovery_view);
484            reveal(limits_view);
485        }
486        return Ok(prepared);
487    }
488    enforce_stream_limit(input.len(), limits)?;
489    enforce_input_work(input.len(), limits)?;
490    let global_segments = parse_sequential(input, limits, false)?;
491    let mut seg_idx = 0_usize;
492    #[cfg_attr(verus_keep_ghost, verus_spec(
493        invariant seg_idx <= global_segments@.len(),
494        decreases global_segments@.len() - seg_idx,
495    ))]
496    while seg_idx < global_segments.len() {
497        let seg = &global_segments[seg_idx];
498        if seg.header.page_association != 0 {
499            return Err(MalformedError::InvalidPageAssociation {
500                segment: seg.header.number,
501                page: seg.header.page_association,
502            }
503            .into());
504        }
505        seg_idx += 1;
506    }
507    enforce_work_limit(input.len(), &global_segments, limits)?;
508    let windows = collect_segment_windows(&global_segments, input.len())?;
509
510    let input_bytes = u64::try_from(input.len()).map_err(|_| MalformedError::IntegerOverflow)?;
511    let count =
512        u64::try_from(global_segments.len()).map_err(|_| MalformedError::IntegerOverflow)?;
513    let references = super::references::count_total_references(&global_segments)?;
514    let mut extra_work = input_bytes
515        .checked_add(count)
516        .and_then(|work| work.checked_add(references))
517        .ok_or(MalformedError::IntegerOverflow)?;
518    budget(LimitKind::Work, extra_work, limits.max_work_units)?;
519
520    let mut recoveries = Vec::new();
521    let mut edits = Vec::new();
522    plan_retention_recoveries(
523        input,
524        &global_segments,
525        &windows,
526        None,
527        &mut recoveries,
528        &mut edits,
529        input_bytes,
530        limits,
531    )?;
532
533    let retained = if recoveries.is_empty() {
534        0
535    } else {
536        input_bytes
537            .checked_add(allocation_size::<EmbeddedRecovery>(recoveries.len())?)
538            .ok_or(MalformedError::IntegerOverflow)?
539    };
540    let bytes = if recoveries.is_empty() {
541        None
542    } else {
543        extra_work = extra_work
544            .checked_add(input_bytes)
545            .ok_or(MalformedError::IntegerOverflow)?;
546        budget(LimitKind::Work, extra_work, limits.max_work_units)?;
547        Some(apply_embedded_edits(input, &edits)?)
548    };
549    let mut remaining = *limits;
550    remaining.max_work_units = remaining
551        .max_work_units
552        .checked_sub(extra_work)
553        .ok_or(MalformedError::IntegerOverflow)?;
554    remaining.max_retained_state_bytes = remaining
555        .max_retained_state_bytes
556        .checked_sub(retained)
557        .ok_or(MalformedError::IntegerOverflow)?;
558    remaining.max_decoder_managed_memory_bytes = remaining
559        .max_decoder_managed_memory_bytes
560        .checked_sub(retained)
561        .ok_or(MalformedError::IntegerOverflow)?;
562    let prepared = PreparedEmbedded {
563        bytes,
564        recoveries,
565        limits: remaining,
566    };
567    #[cfg(verus_keep_ghost)]
568    proof! {
569        reveal(bytes_view);
570        reveal(limits_view);
571    }
572    Ok(prepared)
573}
574
575impl Decoder {
576    /// Inspects an embedded stream with an explicit, observable recovery policy.
577    ///
578    /// Best effort overrides inconsistent page auxiliary/refinement flags
579    /// (T.88 7.4.8.5) and normalizes an existing FF D0 marker at the exact end of
580    /// a known-length arithmetic generic region to FF AC (E.2.9, E.3.3).
581    /// It never adds compressed data or repairs framing or dimensions.
582    /// Preparation debits work and temporary storage from the existing budgets;
583    /// any later resource error reports the remaining effective budget.
584    ///
585    /// # Errors
586    ///
587    /// Returns typed validation, resource or allocation errors. There is no retry.
588    #[cfg_attr(verus_keep_ghost, verus_verify)]
589    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
590        ensures match out {
591            Ok(output) => super::document_spec::embedded_metadata(&output.value),
592            Err(_) => true,
593        },
594    ))]
595    pub fn inspect_embedded_with_policy(
596        &self,
597        input: &[u8],
598        globals: Option<&GlobalSegments>,
599        policy: EmbeddedPolicy,
600    ) -> Result<EmbeddedResult<DocumentInfo>, DecodeError> {
601        let prepared = prepare(input, globals, policy, self.limits())?;
602        let result =
603            Decoder::new(prepared.limits).inspect_embedded_internal(prepared.input(input), globals);
604        prepared.finish(result)
605    }
606
607    /// Parses and validates an immutable embedded global-segment stream with an
608    /// explicit recovery policy.
609    ///
610    /// Under [`EmbeddedPolicy::BestEffort`], missing advisory retention flags
611    /// on referenced global segments are normalized before running the strict
612    /// [`Decoder::parse_globals`] validator.
613    ///
614    /// # Errors
615    ///
616    /// Returns the same typed errors as [`Decoder::parse_globals`].
617    #[cfg_attr(verus_keep_ghost, verus_verify)]
618    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
619        ensures match out {
620            Ok(output) => super::document_spec::global_segment_count(&output.value)
621                == super::document_spec::global_depth_count(&output.value),
622            Err(_) => true,
623        },
624    ))]
625    pub fn parse_globals_with_policy(
626        &self,
627        input: &[u8],
628        policy: EmbeddedPolicy,
629    ) -> Result<EmbeddedResult<GlobalSegments>, DecodeError> {
630        let prepared = prepare_globals(input, policy, self.limits())?;
631        let result = Decoder::new(prepared.limits).parse_globals(prepared.input(input));
632        prepared.finish(result)
633    }
634}
635
636impl DecoderContext<'_> {
637    /// Inspects with the explicit policy of [`Decoder::inspect_embedded_with_policy`].
638    ///
639    /// # Errors
640    ///
641    /// Returns the same typed errors and always performs normal context cleanup.
642    #[cfg_attr(verus_keep_ghost, verus_verify)]
643    #[cfg_attr(verus_keep_ghost, verus_spec(
644        ensures super::document_spec::decoder_context_finished(old(self), final(self)),
645    ))]
646    pub fn inspect_embedded_with_policy(
647        &mut self,
648        input: &[u8],
649        globals: Option<&GlobalSegments>,
650        policy: EmbeddedPolicy,
651    ) -> Result<EmbeddedResult<DocumentInfo>, DecodeError> {
652        let result = self
653            .decoder
654            .inspect_embedded_with_policy(input, globals, policy);
655        self.finish_call();
656        result
657    }
658
659    /// Parses global segments with the explicit policy of
660    /// [`Decoder::parse_globals_with_policy`].
661    ///
662    /// # Errors
663    ///
664    /// Returns the same typed errors and always performs normal context cleanup.
665    #[cfg_attr(verus_keep_ghost, verus_verify)]
666    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
667        ensures
668            super::document_spec::decoder_context_finished(old(self), final(self)),
669            match out {
670                Ok(output) => super::document_spec::global_segment_count(&output.value)
671                    == super::document_spec::global_depth_count(&output.value),
672                Err(_) => true,
673            },
674    ))]
675    pub fn parse_globals_with_policy(
676        &mut self,
677        input: &[u8],
678        policy: EmbeddedPolicy,
679    ) -> Result<EmbeddedResult<GlobalSegments>, DecodeError> {
680        let result = self.decoder.parse_globals_with_policy(input, policy);
681        self.finish_call();
682        result
683    }
684}