Skip to main content

jbig2_decoder/
document.rs

1use std::io::Read;
2
3use crate::file_header::{inspect_file_header, Organization};
4use crate::huffman::{HuffmanError, HuffmanTable};
5use crate::mmr::MmrScratch;
6use crate::reader::ByteReader;
7use crate::segment_data::{
8    parse_end_of_stripe, parse_extension, parse_page_information, parse_profiles, require_empty,
9    PageInformation,
10};
11use crate::segment_header::{parse_segment_header, SegmentHeader, SegmentType};
12use crate::{DecodeError, LimitExceeded, LimitKind, Limits, MalformedError, UnsupportedFeature};
13#[cfg(verus_keep_ghost)]
14use vstd::prelude::*;
15
16#[cfg(verus_keep_ghost)]
17#[rustfmt::skip]
18#[path = "../specs/document.rs"]
19mod document_spec;
20#[cfg(verus_keep_ghost)]
21pub(crate) use document_spec::{
22    declared_count_matches_pages, decoder_context_fields, decoder_context_finished,
23    decoder_context_state, embedded_metadata, standalone_metadata,
24};
25
26#[cfg(verus_keep_ghost)]
27#[rustfmt::skip]
28#[path = "../proofs/spec_properties/document.rs"]
29mod document_properties;
30
31#[cfg(verus_keep_ghost)]
32#[rustfmt::skip]
33#[path = "../proofs/shared/document.rs"]
34mod document_shared;
35
36pub(crate) mod embedded;
37mod embedded_recoveries;
38mod embedded_stripes;
39mod input;
40mod pages;
41mod parsing;
42mod references;
43pub(crate) mod standalone;
44
45use input::{
46    allocation_size, enforce_input_work, enforce_page_limit, enforce_segment_limit,
47    enforce_stream_limit, enforce_work_limit,
48};
49use pages::{build_document_info, validate_profiles};
50use parsing::parse_sequential;
51use references::validate_references;
52
53pub(crate) use input::read_bounded_input;
54pub(crate) use parsing::{parse_embedded_document, parse_standalone_document};
55
56type SegmentTypes = Vec<(u32, SegmentType)>;
57type SegmentDepths = Vec<(u32, u32)>;
58type SegmentIndexes = Vec<(u32, usize)>;
59type PageStates = Vec<(u32, PageState)>;
60
61#[cfg_attr(verus_keep_ghost, verus_spec(out =>
62    ensures match out {
63        Some(index) =>
64            index < entries@.len()
65            && entries@[index as int].0 == number
66            && forall|prior: int| 0 <= prior < index ==> entries@[prior].0 != number,
67        None =>
68            forall|index: int| 0 <= index < entries@.len() ==>
69                entries@[index].0 != number,
70    },
71))]
72fn keyed_index<T>(entries: &[(u32, T)], number: u32) -> Option<usize> {
73    let mut index = 0_usize;
74    #[cfg_attr(verus_keep_ghost, verus_spec(
75        invariant
76            index <= entries@.len(),
77            forall|completed: int| 0 <= completed < index ==>
78                entries@[completed].0 != number,
79        decreases entries@.len() - index,
80    ))]
81    while index < entries.len() {
82        if entries[index].0 == number {
83            return Some(index);
84        }
85        index += 1;
86    }
87    None
88}
89
90#[cfg_attr(verus_keep_ghost, verus_spec(out =>
91    ensures match out {
92        Some(value) => exists|index: int|
93            0 <= index < entries@.len()
94            && entries@[index].0 == number
95            && *value == entries@[index].1
96            && forall|prior: int| 0 <= prior < index ==> entries@[prior].0 != number,
97        None => forall|index: int| 0 <= index < entries@.len() ==> entries@[index].0 != number,
98    },
99))]
100fn keyed_get<T>(entries: &[(u32, T)], number: u32) -> Option<&T> {
101    let index = keyed_index(entries, number)?;
102    Some(&entries[index].1)
103}
104
105#[cfg_attr(verus_keep_ghost, verus_spec(
106    ensures final(entries)@.len() == old(entries)@.len(),
107))]
108fn keyed_get_mut<T>(entries: &mut [(u32, T)], number: u32) -> Option<&mut T> {
109    let index = keyed_index(entries, number)?;
110    Some(&mut entries[index].1)
111}
112
113#[cfg_attr(verus_keep_ghost, verus_spec(out =>
114    ensures if out {
115        final(entries)@ == old(entries)@.push((number, value))
116    } else {
117        final(entries)@ == old(entries)@
118    },
119))]
120fn keyed_insert<T>(entries: &mut Vec<(u32, T)>, number: u32, value: T) -> bool {
121    if keyed_index(entries, number).is_some() {
122        return false;
123    }
124    entries.push((number, value));
125    true
126}
127
128/// High-level decoder configuration.
129#[derive(Debug)]
130#[cfg_attr(verus_keep_ghost, verus_verify)]
131pub struct Decoder {
132    limits: Limits,
133}
134
135#[cfg_attr(verus_keep_ghost, verus_verify)]
136impl Clone for Decoder {
137    fn clone(&self) -> Self {
138        #[cfg(verus_keep_ghost)]
139        ensures(|out: Self| {
140            equal(
141                document_spec::decoder_limits(&out),
142                document_spec::decoder_limits(self),
143            )
144        });
145        let out = Self {
146            limits: self.limits,
147        };
148        #[cfg(verus_keep_ghost)]
149        {
150            production_decoder_fields!(self);
151            production_decoder_fields!(&out);
152        }
153        out
154    }
155}
156
157/// Reusable decoding state for repeated documents with one [`Decoder`].
158///
159/// The context retains only allocation capacity, never document semantics.
160/// Every operation clears scratch lengths after success or error. Call
161/// [`Self::reset`] to clear scratch while retaining capacity, or
162/// [`Self::release_scratch`] to return all retained allocations.
163#[derive(Debug)]
164#[cfg_attr(verus_keep_ghost, verus_verify)]
165pub struct DecoderContext<'a> {
166    pub(crate) decoder: &'a Decoder,
167    pub(crate) mmr: MmrScratch,
168}
169
170impl Decoder {
171    /// Creates reusable scratch state tied to this decoder's limits.
172    #[must_use]
173    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
174        ensures
175            document_spec::decoder_context_state(&out).0 == document_spec::decoder_limits(self),
176            document_spec::decoder_context_state(&out).1.len() == 0,
177            document_spec::decoder_context_state(&out).2.len() == 0,
178            document_spec::decoder_context_state(&out).3 == 0,
179    ))]
180    pub fn context(&self) -> DecoderContext<'_> {
181        let out = DecoderContext {
182            decoder: self,
183            mmr: MmrScratch::default(),
184        };
185        #[cfg(verus_keep_ghost)]
186        proof! {
187            crate::mmr::scratch_view_definition();
188            document_spec::decoder_context_fields();
189        }
190        out
191    }
192
193    /// Creates a decoder using the supplied resource limits.
194    #[must_use]
195    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
196        ensures document_spec::decoder_limits(&out) == limits,
197    ))]
198    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
199    pub const fn new(limits: Limits) -> Self {
200        #[cfg(verus_keep_ghost)]
201        production_document_policy_bundle!();
202        let out = Self { limits };
203        #[cfg(verus_keep_ghost)]
204        production_decoder_fields!(&out);
205        out
206    }
207}
208
209impl DecoderContext<'_> {
210    /// Returns the limits governing this context.
211    #[must_use]
212    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
213        ensures *out == document_spec::decoder_context_state(self).0,
214    ))]
215    pub const fn limits(&self) -> &Limits {
216        #[cfg(verus_keep_ghost)]
217        proof! { document_spec::decoder_context_fields(); }
218        self.decoder.limits()
219    }
220
221    /// Exact bytes currently retained by reusable allocation capacities.
222    #[must_use]
223    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
224        ensures out == document_spec::decoder_context_state(self).3,
225    ))]
226    pub fn retained_scratch_bytes(&self) -> u64 {
227        #[cfg(verus_keep_ghost)]
228        proof! { document_spec::decoder_context_fields(); }
229        self.mmr.retained_bytes()
230    }
231
232    /// Clears all per-document scratch contents while retaining capacity.
233    #[cfg_attr(verus_keep_ghost, verus_spec(
234        ensures
235            document_spec::decoder_context_state(final(self)).0 == document_spec::decoder_context_state(old(self)).0,
236            document_spec::decoder_context_state(final(self)).1.len() == 0,
237            document_spec::decoder_context_state(final(self)).2.len() == 0,
238            document_spec::decoder_context_state(final(self)).3 == document_spec::decoder_context_state(old(self)).3,
239    ))]
240    pub fn reset(&mut self) {
241        #[cfg(verus_keep_ghost)]
242        proof! { document_spec::decoder_context_fields(); }
243        self.mmr.clear();
244    }
245
246    /// Clears per-document state and releases every retained allocation.
247    #[cfg_attr(verus_keep_ghost, verus_spec(
248        ensures
249            document_spec::decoder_context_state(final(self)).0 == document_spec::decoder_context_state(old(self)).0,
250            document_spec::decoder_context_state(final(self)).1.len() == 0,
251            document_spec::decoder_context_state(final(self)).2.len() == 0,
252            document_spec::decoder_context_state(final(self)).3 == 0,
253    ))]
254    pub fn release_scratch(&mut self) {
255        #[cfg(verus_keep_ghost)]
256        proof! { document_spec::decoder_context_fields(); }
257        self.mmr.release();
258    }
259
260    #[cfg_attr(verus_keep_ghost, verus_spec(
261        ensures
262            document_spec::decoder_context_state(final(self)).0 == document_spec::decoder_context_state(old(self)).0,
263            document_spec::decoder_context_state(final(self)).1.len() == 0,
264            document_spec::decoder_context_state(final(self)).2.len() == 0,
265            document_spec::decoder_context_state(final(self)).3 ==
266                if document_spec::decoder_context_state(old(self)).3
267                    > document_spec::decoder_context_state(old(self)).0.max_retained_state_bytes {
268                    0u64
269                } else { document_spec::decoder_context_state(old(self)).3 },
270    ))]
271    pub(crate) fn finish_call(&mut self) {
272        #[cfg(verus_keep_ghost)]
273        proof! { document_spec::decoder_context_fields(); }
274        self.reset();
275        if self.retained_scratch_bytes() > self.limits().max_retained_state_bytes {
276            self.release_scratch();
277        }
278    }
279
280    /// Parses and validates one standalone document.
281    ///
282    /// # Errors
283    ///
284    /// Returns the same typed errors as [`Decoder::inspect`].
285    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
286        ensures
287            document_spec::decoder_context_finished(old(self), final(self)),
288            match out {
289                Ok(info) => document_spec::standalone_metadata(input@, &info),
290                Err(_) => true,
291            },
292    ))]
293    pub fn inspect(&mut self, input: &[u8]) -> Result<DocumentInfo, DecodeError> {
294        let result = self.decoder.inspect(input);
295        self.finish_call();
296        result
297    }
298
299    /// Parses one embedded page stream.
300    ///
301    /// # Errors
302    ///
303    /// Returns the same typed errors as [`Decoder::inspect_embedded`].
304    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
305        ensures
306            document_spec::decoder_context_finished(old(self), final(self)),
307            match out {
308                Ok(info) => document_spec::embedded_metadata(&info),
309                Err(_) => true,
310            },
311    ))]
312    pub fn inspect_embedded(&mut self, input: &[u8]) -> Result<DocumentInfo, DecodeError> {
313        let result = self.decoder.inspect_embedded(input);
314        self.finish_call();
315        result
316    }
317
318    /// Parses one embedded page stream with validated globals.
319    ///
320    /// # Errors
321    ///
322    /// Returns the same typed errors as [`Decoder::inspect_embedded_with_globals`].
323    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
324        ensures
325            document_spec::decoder_context_finished(old(self), final(self)),
326            match out {
327                Ok(info) => document_spec::embedded_metadata(&info),
328                Err(_) => true,
329            },
330    ))]
331    pub fn inspect_embedded_with_globals(
332        &mut self,
333        input: &[u8],
334        globals: &GlobalSegments,
335    ) -> Result<DocumentInfo, DecodeError> {
336        let result = self.decoder.inspect_embedded_with_globals(input, globals);
337        self.finish_call();
338        result
339    }
340
341    /// Parses and validates immutable embedded global segments.
342    ///
343    /// # Errors
344    ///
345    /// Returns the same typed errors as [`Decoder::parse_globals`].
346    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
347        ensures document_spec::decoder_context_finished(old(self), final(self)),
348        document_spec::global_parse_result(
349            input@, document_spec::decoder_context_state(old(self)).0, out,
350        ),
351        match out {
352            Ok(globals) => document_spec::global_segment_count(&globals)
353                == document_spec::global_depth_count(&globals),
354            Err(_) => true,
355        },
356    ))]
357    pub fn parse_globals(&mut self, input: &[u8]) -> Result<GlobalSegments, DecodeError> {
358        #[cfg(verus_keep_ghost)]
359        proof! { document_spec::decoder_context_fields(); }
360        let result = self.decoder.parse_globals(input);
361        self.finish_call();
362        result
363    }
364}
365
366impl Decoder {
367    /// Returns the active resource limits.
368    #[must_use]
369    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
370        ensures *out == document_spec::decoder_limits(self),
371    ))]
372    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
373    pub const fn limits(&self) -> &Limits {
374        #[cfg(verus_keep_ghost)]
375        production_decoder_fields!(self);
376        &self.limits
377    }
378
379    /// Parses and validates a standalone sequential or random-access stream.
380    ///
381    /// This method validates the document envelope and page lifecycle without
382    /// decoding compressed region payloads.
383    /// On success, organization and the optional declared count match the
384    /// standalone header; a known count equals the returned page count.
385    ///
386    /// # Errors
387    ///
388    /// Returns a typed error for malformed, unsupported, over-limit, or
389    /// allocation-failing input.
390    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
391        ensures match out {
392            Ok(info) => document_spec::standalone_metadata(input@, &info),
393            Err(_) => true,
394        },
395    ))]
396    pub fn inspect(&self, input: &[u8]) -> Result<DocumentInfo, DecodeError> {
397        let (info, _segments) = parse_standalone_document(input, &self.limits)?;
398        Ok(info)
399    }
400
401    /// Reads a bounded standalone stream and validates its document envelope.
402    ///
403    /// # Errors
404    ///
405    /// Returns a typed I/O, malformed, unsupported, resource-limit, or
406    /// allocation error.
407    pub fn inspect_reader<R: Read>(&self, reader: &mut R) -> Result<DocumentInfo, DecodeError> {
408        let bytes = read_bounded_input(reader, &self.limits)?;
409        self.inspect(&bytes)
410    }
411
412    /// Parses a contiguous embedded segment stream such as PDF page data.
413    ///
414    /// For PDF integration, including [PDFium](https://pdfium.googlesource.com/pdfium/),
415    /// the end of the complete input may terminate the final page without an
416    /// end-of-page segment. An initially unknown height still requires a final
417    /// completed stripe. Segment headers and payloads must not be truncated.
418    /// Standalone validation remains strict.
419    ///
420    /// # Errors
421    ///
422    /// Returns a typed error for malformed, unsupported, over-limit, or
423    /// allocation-failing input.
424    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
425        ensures match out {
426            Ok(info) => document_spec::embedded_metadata(&info),
427            Err(_) => true,
428        },
429    ))]
430    pub fn inspect_embedded(&self, input: &[u8]) -> Result<DocumentInfo, DecodeError> {
431        self.inspect_embedded_internal(input, None)
432    }
433
434    /// Parses an embedded page stream with reusable validated global segments.
435    ///
436    /// Final-page completion follows [`Decoder::inspect_embedded`].
437    ///
438    /// # Errors
439    ///
440    /// Returns a typed error for malformed, unsupported, over-limit,
441    /// allocation-failing, or unresolved input.
442    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
443        ensures match out {
444            Ok(info) => document_spec::embedded_metadata(&info),
445            Err(_) => true,
446        },
447    ))]
448    pub fn inspect_embedded_with_globals(
449        &self,
450        input: &[u8],
451        globals: &GlobalSegments,
452    ) -> Result<DocumentInfo, DecodeError> {
453        self.inspect_embedded_internal(input, Some(globals))
454    }
455
456    /// Parses and validates an immutable embedded global-segment stream.
457    ///
458    /// # Errors
459    ///
460    /// Returns a typed error if a global segment is malformed, associated with
461    /// a page, unresolved, unsupported, over-limit, or cannot be allocated.
462    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
463        ensures document_spec::global_parse_result(
464            input@, document_spec::decoder_limits(self), out,
465        ),
466        match out {
467            Ok(globals) => document_spec::global_segment_count(&globals)
468                == document_spec::global_depth_count(&globals),
469            Err(_) => true,
470        },
471    ))]
472    pub fn parse_globals(&self, input: &[u8]) -> Result<GlobalSegments, DecodeError> {
473        #[cfg(verus_keep_ghost)]
474        production_decoder_fields!(self);
475        enforce_stream_limit(input.len(), &self.limits)?;
476        enforce_input_work(input.len(), &self.limits)?;
477        let segments = parse_sequential(input, &self.limits, false)?;
478        let mut segment_index = 0_usize;
479        #[cfg_attr(verus_keep_ghost, verus_spec(
480            invariant
481                segment_index <= segments@.len(),
482                input@.len() <= self.limits.max_stream_bytes,
483                document_spec::decoder_limits(self) == self.limits,
484            decreases segments@.len() - segment_index,
485        ))]
486        while segment_index < segments.len() {
487            let segment = &segments[segment_index];
488            if segment.header.page_association != 0 {
489                return Err(MalformedError::InvalidPageAssociation {
490                    segment: segment.header.number,
491                    page: segment.header.page_association,
492                }
493                .into());
494            }
495            segment_index += 1;
496        }
497        validate_profiles(&segments)?;
498        enforce_work_limit(input.len(), &segments, &self.limits)?;
499        let (types, depths) = validate_references(&segments, None, &self.limits)?;
500        let Ok(input_bytes) = u64::try_from(input.len()) else {
501            return Err(MalformedError::IntegerOverflow.into());
502        };
503        if input_bytes > self.limits.max_retained_state_bytes {
504            return Err(LimitExceeded {
505                kind: LimitKind::RetainedState,
506                limit: self.limits.max_retained_state_bytes,
507                actual: input_bytes,
508            }
509            .into());
510        }
511        let mut bytes = Vec::new();
512        if bytes.try_reserve(input.len()).is_err() {
513            return Err(DecodeError::Allocation {
514                requested_bytes: input_bytes,
515            });
516        }
517        let mut byte_index = 0_usize;
518        #[cfg_attr(verus_keep_ghost, verus_spec(
519            invariant
520                byte_index <= input@.len(),
521                bytes@ == input@.subrange(0, byte_index as int),
522                types@.len() == depths@.len(),
523                input@.len() <= self.limits.max_stream_bytes,
524                input@.len() <= self.limits.max_retained_state_bytes,
525                document_spec::decoder_limits(self) == self.limits,
526            decreases input@.len() - byte_index,
527        ))]
528        while byte_index < input.len() {
529            bytes.push(input[byte_index]);
530            byte_index += 1;
531        }
532        #[cfg(verus_keep_ghost)]
533        proof! { vstd::assert_seqs_equal!(input@.subrange(0, input@.len() as int), input@); }
534        let out = GlobalSegments {
535            types,
536            depths,
537            bytes,
538        };
539        #[cfg(verus_keep_ghost)]
540        production_global_fields!(&out);
541        Ok(out)
542    }
543
544    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
545        ensures match out {
546            Ok(info) => document_spec::embedded_metadata(&info),
547            Err(_) => true,
548        },
549    ))]
550    fn inspect_embedded_internal(
551        &self,
552        input: &[u8],
553        globals: Option<&GlobalSegments>,
554    ) -> Result<DocumentInfo, DecodeError> {
555        let (info, _segments) = parse_embedded_document(input, &self.limits, globals)?;
556        Ok(info)
557    }
558
559    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
560        ensures document_spec::default_limits(
561            document_spec::decoder_limits(&out),
562        ),
563    ))]
564    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
565    fn project_default() -> Self {
566        Self::new(Limits::project_default())
567    }
568}
569
570#[cfg_attr(verus_keep_ghost, verifier::verify)]
571impl Default for Decoder {
572    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
573        ensures document_spec::default_limits(
574            document_spec::decoder_limits(&out),
575        ),
576    ))]
577    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
578    fn default() -> Self {
579        Self::project_default()
580    }
581}
582
583/// Immutable validated metadata for reusable embedded global segments.
584#[derive(Debug)]
585#[cfg_attr(verus_keep_ghost, verus_verify)]
586pub struct GlobalSegments {
587    types: SegmentTypes,
588    depths: SegmentDepths,
589    bytes: Vec<u8>,
590}
591
592impl GlobalSegments {
593    /// Number of global segments.
594    #[must_use]
595    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
596        ensures out as nat == document_spec::global_segment_count(self),
597    ))]
598    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
599    pub fn segment_count(&self) -> usize {
600        #[cfg(verus_keep_ghost)]
601        production_global_fields!(self);
602        self.types.len()
603    }
604
605    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
606        ensures out@ == document_spec::global_bytes(self),
607    ))]
608    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
609    pub(crate) fn bytes(&self) -> &[u8] {
610        #[cfg(verus_keep_ghost)]
611        production_global_fields!(self);
612        &self.bytes
613    }
614}
615
616/// Validated document-level metadata.
617#[derive(Debug, PartialEq, Eq)]
618#[cfg_attr(verus_keep_ghost, verus_verify)]
619pub struct DocumentInfo {
620    organization: Organization,
621    declared_page_count: Option<u32>,
622    segment_count: u32,
623    pages: Vec<PageInfo>,
624}
625
626impl DocumentInfo {
627    /// Standalone organization, or sequential envelope semantics for embedded
628    /// streams.
629    #[must_use]
630    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
631        ensures out == document_spec::document_organization(self),
632    ))]
633    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
634    pub const fn organization(&self) -> Organization {
635        #[cfg(verus_keep_ghost)]
636        production_document_fields!(self);
637        self.organization
638    }
639
640    /// Page count declared by a standalone header.
641    #[must_use]
642    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
643        ensures out == document_spec::document_declared_page_count(self),
644    ))]
645    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
646    pub const fn declared_page_count(&self) -> Option<u32> {
647        #[cfg(verus_keep_ghost)]
648        production_document_fields!(self);
649        self.declared_page_count
650    }
651
652    /// Number of parsed segments.
653    #[must_use]
654    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
655        ensures out == document_spec::document_segment_count(self),
656    ))]
657    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
658    pub const fn segment_count(&self) -> u32 {
659        #[cfg(verus_keep_ghost)]
660        production_document_fields!(self);
661        self.segment_count
662    }
663
664    /// Validated pages in ascending page-number order.
665    #[must_use]
666    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
667        ensures out@ == document_spec::document_pages(self),
668    ))]
669    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
670    pub fn pages(&self) -> &[PageInfo] {
671        #[cfg(verus_keep_ghost)]
672        production_document_fields!(self);
673        &self.pages
674    }
675}
676
677/// Public page metadata established by page and stripe boundary segments.
678#[derive(Debug, Clone, Copy, PartialEq, Eq)]
679#[cfg_attr(verus_keep_ghost, verus_verify)]
680pub struct PageInfo {
681    pub(crate) number: u32,
682    pub(crate) width: u32,
683    pub(crate) height: u32,
684    pub(crate) x_resolution: u32,
685    pub(crate) y_resolution: u32,
686    pub(crate) striped: bool,
687}
688
689impl PageInfo {
690    /// One-based page number.
691    #[must_use]
692    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
693        ensures out == crate::views::page_number(self),
694    ))]
695    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
696    pub const fn number(&self) -> u32 {
697        #[cfg(verus_keep_ghost)]
698        production_page_info_fields!(self);
699        self.number
700    }
701
702    /// Page width in pixels.
703    #[must_use]
704    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
705        ensures out == crate::views::page_width(self),
706    ))]
707    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
708    pub const fn width(&self) -> u32 {
709        #[cfg(verus_keep_ghost)]
710        production_page_info_fields!(self);
711        self.width
712    }
713
714    /// Final page height in pixels.
715    #[must_use]
716    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
717        ensures out == crate::views::page_height(self),
718    ))]
719    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
720    pub const fn height(&self) -> u32 {
721        #[cfg(verus_keep_ghost)]
722        production_page_info_fields!(self);
723        self.height
724    }
725
726    /// Horizontal resolution in pixels per metre, or zero when unknown.
727    #[must_use]
728    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
729        ensures out == crate::views::page_x_resolution(self),
730    ))]
731    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
732    pub const fn x_resolution(&self) -> u32 {
733        #[cfg(verus_keep_ghost)]
734        production_page_info_fields!(self);
735        self.x_resolution
736    }
737
738    /// Vertical resolution in pixels per metre, or zero when unknown.
739    #[must_use]
740    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
741        ensures out == crate::views::page_y_resolution(self),
742    ))]
743    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
744    pub const fn y_resolution(&self) -> u32 {
745        #[cfg(verus_keep_ghost)]
746        production_page_info_fields!(self);
747        self.y_resolution
748    }
749
750    /// Whether the page uses stripe boundaries.
751    #[must_use]
752    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
753        ensures out == crate::views::page_is_striped(self),
754    ))]
755    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
756    pub const fn is_striped(&self) -> bool {
757        #[cfg(verus_keep_ghost)]
758        production_page_info_fields!(self);
759        self.striped
760    }
761}
762
763#[derive(Debug)]
764#[cfg_attr(verus_keep_ghost, verus_verify)]
765pub(crate) struct ParsedSegment<'a> {
766    pub(crate) header: SegmentHeader,
767    #[allow(dead_code)]
768    pub(crate) payload: &'a [u8],
769    pub(crate) data: ParsedData,
770}
771
772#[derive(Debug)]
773#[cfg_attr(verus_keep_ghost, verus_verify)]
774pub(crate) enum ParsedData {
775    Page(PageInformation),
776    EndOfStripe(u32),
777    Profiles(Vec<u32>),
778    Other,
779}
780
781#[derive(Debug)]
782#[cfg_attr(verus_keep_ghost, verus_verify)]
783struct PageState {
784    info: PageInformation,
785    last_stripe: Option<u32>,
786    ended: bool,
787}
788
789#[cfg(test)]
790mod tests;