Skip to main content

font_parse/tables/
dsig.rs

1//! `DSIG` — digital signature table (header + signature records only).
2
3use crate::error::{ParseError, RawTag};
4use crate::reader::{be_u16_at, be_u32_at};
5use alloc::vec::Vec;
6
7pub(crate) const TAG: RawTag = *b"DSIG";
8
9/// One signature record.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub struct SignatureRecord {
12    /// Signature format (1 = PKCS#7 blobs).
13    pub format: u32,
14    /// Signature length in bytes.
15    pub length: u32,
16    /// Signature offset from the start of the `DSIG` table.
17    pub offset: u32,
18}
19
20/// Zero-copy view over the `DSIG` table (header + records; the PKCS#7
21/// payloads are exposed as raw bytes).
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub struct DsigTable<'a> {
24    data: &'a [u8],
25}
26
27impl<'a> DsigTable<'a> {
28    /// Parse and validate the `DSIG` header.
29    ///
30    /// # Errors
31    /// [`ParseError::TruncatedTable`] / [`ParseError::InvalidGlyphFormat`]
32    /// for short or inconsistent tables.
33    pub fn parse(data: &'a [u8]) -> Result<Self, ParseError> {
34        if data.len() < 8 {
35            return Err(ParseError::TruncatedTable {
36                tag: TAG,
37                expected: 8,
38                got: data.len(),
39            });
40        }
41        let count = usize::from(be_u16_at(data, 4, TAG)?);
42        let end = 8usize
43            .checked_add(count * 12)
44            .ok_or(ParseError::InvalidGlyphFormat)?;
45        if end > data.len() {
46            return Err(ParseError::TruncatedTable {
47                tag: TAG,
48                expected: end,
49                got: data.len(),
50            });
51        }
52        Ok(Self { data })
53    }
54
55    /// Raw table bytes.
56    #[must_use]
57    pub fn as_bytes(&self) -> &'a [u8] {
58        self.data
59    }
60
61    /// Version (1).
62    ///
63    /// # Errors
64    /// Truncation (impossible post-[`parse`](Self::parse)).
65    pub fn version(&self) -> Result<u32, ParseError> {
66        be_u32_at(self.data, 0, TAG)
67    }
68
69    /// Permission flags (bit 0 = cannot be resigned).
70    ///
71    /// # Errors
72    /// Truncation (impossible post-[`parse`](Self::parse)).
73    pub fn flags(&self) -> Result<u16, ParseError> {
74        be_u16_at(self.data, 2, TAG)
75    }
76
77    /// Signature records, in table order.
78    ///
79    /// # Errors
80    /// [`ParseError::InvalidGlyphFormat`] when a record's byte range falls
81    /// outside the table.
82    pub fn signatures(&self) -> Result<Vec<(&'a [u8], SignatureRecord)>, ParseError> {
83        let count = usize::from(be_u16_at(self.data, 4, TAG)?);
84        let mut out = Vec::with_capacity(count);
85        for i in 0..count {
86            let at = 8 + i * 12;
87            let rec = SignatureRecord {
88                format: be_u32_at(self.data, at, TAG)?,
89                length: be_u32_at(self.data, at + 4, TAG)?,
90                offset: be_u32_at(self.data, at + 8, TAG)?,
91            };
92            let len = usize::try_from(rec.length).map_err(|_| ParseError::InvalidGlyphFormat)?;
93            let off = usize::try_from(rec.offset).map_err(|_| ParseError::InvalidGlyphFormat)?;
94            out.push((crate::reader::slice_at(self.data, off, len, TAG)?, rec));
95        }
96        Ok(out)
97    }
98}
99
100#[cfg(test)]
101mod tests {
102    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
103
104    use super::DsigTable;
105    use crate::error::ParseError;
106    use alloc::vec::Vec;
107
108    // Test harness: assertions legitimately panic; the lib target stays
109    // lint-clean.
110
111    fn sample() -> Vec<u8> {
112        let mut d = Vec::new();
113        d.extend_from_slice(&1u32.to_be_bytes()); // version
114        d.extend_from_slice(&1u16.to_be_bytes()); // flags
115        d.extend_from_slice(&1u16.to_be_bytes()); // numSignatures
116        d.extend_from_slice(&1u32.to_be_bytes()); // format
117        d.extend_from_slice(&4u32.to_be_bytes()); // length
118        d.extend_from_slice(&20u32.to_be_bytes()); // offset
119        d.extend_from_slice(&[0xDE, 0xAD, 0xBE, 0xEF]);
120        d
121    }
122
123    #[test]
124    fn parses_header_and_records() {
125        let d = sample();
126        let t = DsigTable::parse(&d).unwrap();
127        assert_eq!(t.version().unwrap(), 1);
128        assert_eq!(t.flags().unwrap(), 1);
129        let sigs = t.signatures().unwrap();
130        assert_eq!(sigs.len(), 1);
131        assert_eq!(sigs[0].1.format, 1);
132        assert_eq!(sigs[0].0, &[0xDE, 0xAD, 0xBE, 0xEF]);
133    }
134
135    #[test]
136    fn errors() {
137        assert_eq!(
138            DsigTable::parse(&[0u8; 7]),
139            Err(ParseError::TruncatedTable {
140                tag: *b"DSIG",
141                expected: 8,
142                got: 7
143            })
144        );
145        // Record array truncated.
146        let mut d = sample();
147        d.truncate(15);
148        assert!(DsigTable::parse(&d).is_err());
149        // Signature bytes outside the table.
150        let mut d = sample();
151        d.truncate(22);
152        let t = DsigTable::parse(&d).unwrap();
153        assert!(matches!(
154            t.signatures(),
155            Err(ParseError::TruncatedTable { .. })
156        ));
157    }
158}