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