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