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