Skip to main content

jbig2_decoder/
file_header.rs

1use crate::reader::ByteReader;
2use crate::{DecodeError, MalformedError};
3#[cfg(verus_keep_ghost)]
4use vstd::prelude::*;
5
6#[cfg(verus_keep_ghost)]
7#[rustfmt::skip]
8#[path = "../specs/file_header.rs"]
9pub(crate) mod file_header_spec;
10
11/// Segment and payload organization for a standalone JBIG2 file.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13#[cfg_attr(verus_keep_ghost, verus_verify)]
14pub enum Organization {
15    /// All segment headers precede all segment payloads.
16    RandomAccess,
17    /// Every segment header is immediately followed by its payload.
18    Sequential,
19}
20
21/// Parsed standalone JBIG2 file-header metadata.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23#[cfg_attr(verus_keep_ghost, verus_verify)]
24pub struct FileHeader {
25    pub(crate) organization: Organization,
26    pub(crate) page_count: Option<u32>,
27    pub(crate) extended_templates: bool,
28    pub(crate) colour_regions: bool,
29    pub(crate) byte_length: usize,
30}
31
32impl FileHeader {
33    /// Standalone segment organization.
34    #[must_use]
35    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
36        ensures out == crate::views::file_header_organization(self),
37    ))]
38    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
39    pub const fn organization(self) -> Organization {
40        #[cfg(verus_keep_ghost)]
41        production_file_header_organization!(self);
42        self.organization
43    }
44
45    /// Declared page count, or `None` if the header marks it unknown.
46    #[must_use]
47    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
48        ensures out == crate::views::file_header_page_count(self),
49    ))]
50    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
51    pub const fn page_count(self) -> Option<u32> {
52        #[cfg(verus_keep_ghost)]
53        production_file_header_page_count!(self);
54        self.page_count
55    }
56
57    /// Whether the stream may use generic templates with 12 adaptive pixels.
58    #[must_use]
59    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
60        ensures out == crate::views::file_header_extended_templates(self),
61    ))]
62    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
63    pub const fn uses_extended_templates(self) -> bool {
64        #[cfg(verus_keep_ghost)]
65        production_file_header_extended_templates!(self);
66        self.extended_templates
67    }
68
69    /// Whether the stream declares coloured regions.
70    #[must_use]
71    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
72        ensures out == crate::views::file_header_colour_regions(self),
73    ))]
74    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
75    pub const fn uses_colour_regions(self) -> bool {
76        #[cfg(verus_keep_ghost)]
77        production_file_header_colour_regions!(self);
78        self.colour_regions
79    }
80
81    /// Number of bytes occupied by the file header.
82    #[must_use]
83    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
84        ensures out == crate::views::file_header_byte_length(self),
85    ))]
86    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
87    pub const fn byte_length(self) -> usize {
88        #[cfg(verus_keep_ghost)]
89        production_file_header_byte_length!(self);
90        self.byte_length
91    }
92}
93
94/// Parses a standalone JBIG2 file header without decoding its segments.
95///
96/// On failure, no successful metadata is fabricated. Embedded streams do not
97/// contain this header and must not be passed to this function.
98///
99/// # Errors
100///
101/// Returns [`DecodeError::Malformed`] if the signature, reserved flags, or
102/// required page-count field is invalid or truncated.
103#[cfg_attr(verus_keep_ghost, verus_spec(out =>
104    ensures match out {
105        Ok(header) =>
106            file_header_spec::valid(input@)
107            && crate::views::file_header_organization(header)
108                == file_header_spec::organization(input@)
109            && crate::views::file_header_page_count(header)
110                == file_header_spec::page_count(input@)
111            && crate::views::file_header_extended_templates(header)
112                == file_header_spec::extended_templates(input@)
113            && crate::views::file_header_colour_regions(header)
114                == file_header_spec::colour_regions(input@)
115            && crate::views::file_header_byte_length(header)
116                == file_header_spec::byte_length(input@),
117        Err(_) => !file_header_spec::valid(input@),
118    },
119))]
120pub fn inspect_file_header(input: &[u8]) -> Result<FileHeader, DecodeError> {
121    let mut reader = ByteReader::new(input);
122    let signature = match reader.read_bytes(8) {
123        Ok(value) => value,
124        Err(error) => return Err(DecodeError::Malformed(error)),
125    };
126    if signature[0] != 0x97
127        || signature[1] != 0x4A
128        || signature[2] != 0x42
129        || signature[3] != 0x32
130        || signature[4] != 0x0D
131        || signature[5] != 0x0A
132        || signature[6] != 0x1A
133        || signature[7] != 0x0A
134    {
135        return Err(DecodeError::Malformed(MalformedError::InvalidFileSignature));
136    }
137
138    let flags = match reader.read_u8() {
139        Ok(value) => value,
140        Err(error) => return Err(DecodeError::Malformed(error)),
141    };
142    let reserved = flags & 0xF0;
143    if reserved != 0 {
144        return Err(DecodeError::Malformed(
145            MalformedError::ReservedFileHeaderFlags(reserved),
146        ));
147    }
148
149    let colour_regions = flags & 0x08 != 0;
150    let extended_templates = flags & 0x04 != 0;
151    let unknown_page_count = flags & 0x02 != 0;
152    let organization = if flags & 0x01 == 0 {
153        Organization::RandomAccess
154    } else {
155        Organization::Sequential
156    };
157    let page_count = if unknown_page_count {
158        None
159    } else {
160        let value = match reader.read_u32() {
161            Ok(value) => value,
162            Err(error) => return Err(DecodeError::Malformed(error)),
163        };
164        Some(value)
165    };
166
167    let header = FileHeader {
168        organization,
169        page_count,
170        extended_templates,
171        colour_regions,
172        byte_length: reader.position(),
173    };
174    #[cfg(verus_keep_ghost)]
175    production_file_header_result!(header);
176    Ok(header)
177}
178
179#[cfg(test)]
180mod tests;