Skip to main content

read_fonts/generated/
generated_dsig.rs

1// THIS FILE IS AUTOGENERATED.
2// Any changes to this file will be overwritten.
3// For more information about how codegen works, see font-codegen/README.md
4
5#[allow(unused_imports)]
6use crate::codegen_prelude::*;
7
8impl<'a> MinByteRange<'a> for Dsig<'a> {
9    fn min_byte_range(&self) -> Range<usize> {
10        0..self.signature_records_byte_range().end
11    }
12    fn min_table_bytes(&self) -> &'a [u8] {
13        let range = self.min_byte_range();
14        self.offset_data().as_bytes().get(range).unwrap_or_default()
15    }
16}
17
18impl TopLevelTable for Dsig<'_> {
19    /// `DSIG`
20    const TAG: Tag = Tag::new(b"DSIG");
21}
22
23impl ReadArgs for Dsig<'_> {
24    type Args = ();
25}
26
27impl<'a> FontRead<'a> for Dsig<'a> {
28    fn read_with_args(data: FontData<'a>, _: ()) -> Result<Self, ReadError> {
29        #[allow(clippy::absurd_extreme_comparisons)]
30        if data.len() < Self::MIN_SIZE {
31            return Err(ReadError::OutOfBounds);
32        }
33        let Some(data) = TableDataRef::new(data.as_bytes()) else {
34            return Err(ReadError::OutOfBounds);
35        };
36        Ok(Self { data })
37    }
38}
39
40/// The fields at the start of the table, which are read directly.
41#[derive(Clone, Copy, bytemuck :: AnyBitPattern)]
42#[repr(C, packed)]
43#[doc(hidden)]
44pub struct DsigFixedHeader {
45    pub version: BigEndian<u32>,
46    pub num_signatures: BigEndian<u16>,
47    pub flags: BigEndian<PermissionFlags>,
48}
49
50#[allow(clippy::absurd_extreme_comparisons)]
51const _: () = assert!(std::mem::size_of::<DsigFixedHeader>() <= Dsig::MIN_SIZE);
52
53/// [DSIG (Digital Signature Table)](https://docs.microsoft.com/en-us/typography/opentype/spec/dsig#table-structure) table
54#[derive(Clone)]
55pub struct Dsig<'a> {
56    data: TableDataRef<'a, DsigFixedHeader>,
57}
58
59#[allow(clippy::needless_lifetimes)]
60impl<'a> Dsig<'a> {
61    pub const MIN_SIZE: usize =
62        (u32::RAW_BYTE_LEN + u16::RAW_BYTE_LEN + PermissionFlags::RAW_BYTE_LEN);
63    basic_table_impls!(impl_the_methods);
64
65    /// Version number of the DSIG table (0x00000001)
66    pub fn version(&self) -> u32 {
67        self.data.header().version.get()
68    }
69
70    /// Number of signatures in the table
71    pub fn num_signatures(&self) -> u16 {
72        self.data.header().num_signatures.get()
73    }
74
75    /// Permission flags
76    pub fn flags(&self) -> PermissionFlags {
77        self.data.header().flags.get()
78    }
79
80    /// Array of signature records
81    pub fn signature_records(&self) -> &'a [SignatureRecord] {
82        let range = self.signature_records_byte_range();
83        self.offset_data()
84            .read_array(range)
85            .ok()
86            .unwrap_or_default()
87    }
88
89    pub fn version_byte_range(&self) -> Range<usize> {
90        let start = 0;
91        let end = start + u32::RAW_BYTE_LEN;
92        start..end
93    }
94
95    pub fn num_signatures_byte_range(&self) -> Range<usize> {
96        let start = self.version_byte_range().end;
97        let end = start + u16::RAW_BYTE_LEN;
98        start..end
99    }
100
101    pub fn flags_byte_range(&self) -> Range<usize> {
102        let start = self.num_signatures_byte_range().end;
103        let end = start + PermissionFlags::RAW_BYTE_LEN;
104        start..end
105    }
106
107    pub fn signature_records_byte_range(&self) -> Range<usize> {
108        let num_signatures = self.num_signatures();
109        let start = self.flags_byte_range().end;
110        let end = start
111            + (transforms::to_usize(num_signatures)).saturating_mul(SignatureRecord::RAW_BYTE_LEN);
112        start..end
113    }
114}
115
116const _: () = assert!(FontData::default_data_long_enough(Dsig::MIN_SIZE));
117
118impl Default for Dsig<'_> {
119    fn default() -> Self {
120        Self {
121            data: TableDataRef::new(FontData::default_table_data().as_bytes())
122                .unwrap_or_else(|| unreachable!("the default data covers MIN_SIZE")),
123        }
124    }
125}
126
127/// [Permission flags](https://learn.microsoft.com/en-us/typography/opentype/spec/dsig#table-structure)
128#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, bytemuck :: AnyBitPattern)]
129#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
130#[repr(transparent)]
131pub struct PermissionFlags {
132    bits: u16,
133}
134
135impl PermissionFlags {
136    /// Bit 0: Cannot be resigned
137    pub const CANNOT_BE_RESIGNED: Self = Self {
138        bits: 0b0000_0000_0000_0001,
139    };
140}
141
142impl PermissionFlags {
143    ///  Returns an empty set of flags.
144    #[inline]
145    pub const fn empty() -> Self {
146        Self { bits: 0 }
147    }
148
149    /// Returns the set containing all flags.
150    #[inline]
151    pub const fn all() -> Self {
152        Self {
153            bits: Self::CANNOT_BE_RESIGNED.bits,
154        }
155    }
156
157    /// Returns the raw value of the flags currently stored.
158    #[inline]
159    pub const fn bits(&self) -> u16 {
160        self.bits
161    }
162
163    /// Convert from underlying bit representation, unless that
164    /// representation contains bits that do not correspond to a flag.
165    #[inline]
166    pub const fn from_bits(bits: u16) -> Option<Self> {
167        if (bits & !Self::all().bits()) == 0 {
168            Some(Self { bits })
169        } else {
170            None
171        }
172    }
173
174    /// Convert from underlying bit representation, dropping any bits
175    /// that do not correspond to flags.
176    #[inline]
177    pub const fn from_bits_truncate(bits: u16) -> Self {
178        Self {
179            bits: bits & Self::all().bits,
180        }
181    }
182
183    /// Returns `true` if no flags are currently stored.
184    #[inline]
185    pub const fn is_empty(&self) -> bool {
186        self.bits() == Self::empty().bits()
187    }
188
189    /// Returns `true` if there are flags common to both `self` and `other`.
190    #[inline]
191    pub const fn intersects(&self, other: Self) -> bool {
192        !(Self {
193            bits: self.bits & other.bits,
194        })
195        .is_empty()
196    }
197
198    /// Returns `true` if all of the flags in `other` are contained within `self`.
199    #[inline]
200    pub const fn contains(&self, other: Self) -> bool {
201        (self.bits & other.bits) == other.bits
202    }
203
204    /// Inserts the specified flags in-place.
205    #[inline]
206    pub fn insert(&mut self, other: Self) {
207        self.bits |= other.bits;
208    }
209
210    /// Removes the specified flags in-place.
211    #[inline]
212    pub fn remove(&mut self, other: Self) {
213        self.bits &= !other.bits;
214    }
215
216    /// Toggles the specified flags in-place.
217    #[inline]
218    pub fn toggle(&mut self, other: Self) {
219        self.bits ^= other.bits;
220    }
221
222    /// Returns the intersection between the flags in `self` and
223    /// `other`.
224    ///
225    /// Specifically, the returned set contains only the flags which are
226    /// present in *both* `self` *and* `other`.
227    ///
228    /// This is equivalent to using the `&` operator (e.g.
229    /// [`ops::BitAnd`]), as in `flags & other`.
230    ///
231    /// [`ops::BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html
232    #[inline]
233    #[must_use]
234    pub const fn intersection(self, other: Self) -> Self {
235        Self {
236            bits: self.bits & other.bits,
237        }
238    }
239
240    /// Returns the union of between the flags in `self` and `other`.
241    ///
242    /// Specifically, the returned set contains all flags which are
243    /// present in *either* `self` *or* `other`, including any which are
244    /// present in both.
245    ///
246    /// This is equivalent to using the `|` operator (e.g.
247    /// [`ops::BitOr`]), as in `flags | other`.
248    ///
249    /// [`ops::BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html
250    #[inline]
251    #[must_use]
252    pub const fn union(self, other: Self) -> Self {
253        Self {
254            bits: self.bits | other.bits,
255        }
256    }
257
258    /// Returns the difference between the flags in `self` and `other`.
259    ///
260    /// Specifically, the returned set contains all flags present in
261    /// `self`, except for the ones present in `other`.
262    ///
263    /// It is also conceptually equivalent to the "bit-clear" operation:
264    /// `flags & !other` (and this syntax is also supported).
265    ///
266    /// This is equivalent to using the `-` operator (e.g.
267    /// [`ops::Sub`]), as in `flags - other`.
268    ///
269    /// [`ops::Sub`]: https://doc.rust-lang.org/std/ops/trait.Sub.html
270    #[inline]
271    #[must_use]
272    pub const fn difference(self, other: Self) -> Self {
273        Self {
274            bits: self.bits & !other.bits,
275        }
276    }
277}
278
279impl std::ops::BitOr for PermissionFlags {
280    type Output = Self;
281
282    /// Returns the union of the two sets of flags.
283    #[inline]
284    fn bitor(self, other: PermissionFlags) -> Self {
285        Self {
286            bits: self.bits | other.bits,
287        }
288    }
289}
290
291impl std::ops::BitOrAssign for PermissionFlags {
292    /// Adds the set of flags.
293    #[inline]
294    fn bitor_assign(&mut self, other: Self) {
295        self.bits |= other.bits;
296    }
297}
298
299impl std::ops::BitXor for PermissionFlags {
300    type Output = Self;
301
302    /// Returns the left flags, but with all the right flags toggled.
303    #[inline]
304    fn bitxor(self, other: Self) -> Self {
305        Self {
306            bits: self.bits ^ other.bits,
307        }
308    }
309}
310
311impl std::ops::BitXorAssign for PermissionFlags {
312    /// Toggles the set of flags.
313    #[inline]
314    fn bitxor_assign(&mut self, other: Self) {
315        self.bits ^= other.bits;
316    }
317}
318
319impl std::ops::BitAnd for PermissionFlags {
320    type Output = Self;
321
322    /// Returns the intersection between the two sets of flags.
323    #[inline]
324    fn bitand(self, other: Self) -> Self {
325        Self {
326            bits: self.bits & other.bits,
327        }
328    }
329}
330
331impl std::ops::BitAndAssign for PermissionFlags {
332    /// Disables all flags disabled in the set.
333    #[inline]
334    fn bitand_assign(&mut self, other: Self) {
335        self.bits &= other.bits;
336    }
337}
338
339impl std::ops::Sub for PermissionFlags {
340    type Output = Self;
341
342    /// Returns the set difference of the two sets of flags.
343    #[inline]
344    fn sub(self, other: Self) -> Self {
345        Self {
346            bits: self.bits & !other.bits,
347        }
348    }
349}
350
351impl std::ops::SubAssign for PermissionFlags {
352    /// Disables all flags enabled in the set.
353    #[inline]
354    fn sub_assign(&mut self, other: Self) {
355        self.bits &= !other.bits;
356    }
357}
358
359impl std::ops::Not for PermissionFlags {
360    type Output = Self;
361
362    /// Returns the complement of this set of flags.
363    #[inline]
364    fn not(self) -> Self {
365        Self { bits: !self.bits } & Self::all()
366    }
367}
368
369impl std::fmt::Debug for PermissionFlags {
370    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
371        let members: &[(&str, Self)] = &[("CANNOT_BE_RESIGNED", Self::CANNOT_BE_RESIGNED)];
372        let mut first = true;
373        for (name, value) in members {
374            if self.contains(*value) {
375                if !first {
376                    f.write_str(" | ")?;
377                }
378                first = false;
379                f.write_str(name)?;
380            }
381        }
382        if first {
383            f.write_str("(empty)")?;
384        }
385        Ok(())
386    }
387}
388
389impl std::fmt::Binary for PermissionFlags {
390    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
391        std::fmt::Binary::fmt(&self.bits, f)
392    }
393}
394
395impl std::fmt::Octal for PermissionFlags {
396    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
397        std::fmt::Octal::fmt(&self.bits, f)
398    }
399}
400
401impl std::fmt::LowerHex for PermissionFlags {
402    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
403        std::fmt::LowerHex::fmt(&self.bits, f)
404    }
405}
406
407impl std::fmt::UpperHex for PermissionFlags {
408    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
409        std::fmt::UpperHex::fmt(&self.bits, f)
410    }
411}
412
413impl font_types::Scalar for PermissionFlags {
414    type Raw = <u16 as font_types::Scalar>::Raw;
415    fn to_raw(self) -> Self::Raw {
416        self.bits().to_raw()
417    }
418    fn from_raw(raw: Self::Raw) -> Self {
419        let t = <u16>::from_raw(raw);
420        Self::from_bits_truncate(t)
421    }
422}
423
424/// [Signature Record](https://learn.microsoft.com/en-us/typography/opentype/spec/dsig#table-structure)
425#[derive(Clone, Debug, Copy, bytemuck :: AnyBitPattern)]
426#[repr(C)]
427#[repr(packed)]
428pub struct SignatureRecord {
429    /// Format of the signature
430    pub format: BigEndian<u32>,
431    /// Length of signature in bytes
432    pub length: BigEndian<u32>,
433    /// Offset to the signature block from the beginning of the table
434    pub signature_block_offset: BigEndian<Offset32>,
435}
436
437impl SignatureRecord {
438    /// Format of the signature
439    pub fn format(&self) -> u32 {
440        self.format.get()
441    }
442
443    /// Length of signature in bytes
444    pub fn length(&self) -> u32 {
445        self.length.get()
446    }
447
448    /// Offset to the signature block from the beginning of the table
449    pub fn signature_block_offset(&self) -> Offset32 {
450        self.signature_block_offset.get()
451    }
452}
453
454impl FixedSize for SignatureRecord {
455    const RAW_BYTE_LEN: usize = u32::RAW_BYTE_LEN + u32::RAW_BYTE_LEN + Offset32::RAW_BYTE_LEN;
456}
457
458impl<'a> MinByteRange<'a> for SignatureBlockFormat1<'a> {
459    fn min_byte_range(&self) -> Range<usize> {
460        0..self.signature_byte_range().end
461    }
462    fn min_table_bytes(&self) -> &'a [u8] {
463        let range = self.min_byte_range();
464        self.offset_data().as_bytes().get(range).unwrap_or_default()
465    }
466}
467
468impl ReadArgs for SignatureBlockFormat1<'_> {
469    type Args = ();
470}
471
472impl<'a> FontRead<'a> for SignatureBlockFormat1<'a> {
473    fn read_with_args(data: FontData<'a>, _: ()) -> Result<Self, ReadError> {
474        #[allow(clippy::absurd_extreme_comparisons)]
475        if data.len() < Self::MIN_SIZE {
476            return Err(ReadError::OutOfBounds);
477        }
478        let Some(data) = TableDataRef::new(data.as_bytes()) else {
479            return Err(ReadError::OutOfBounds);
480        };
481        Ok(Self { data })
482    }
483}
484
485/// The fields at the start of the table, which are read directly.
486#[derive(Clone, Copy, bytemuck :: AnyBitPattern)]
487#[repr(C, packed)]
488#[doc(hidden)]
489pub struct SignatureBlockFormat1FixedHeader {
490    pub _reserved1: BigEndian<u16>,
491    pub _reserved2: BigEndian<u16>,
492    pub signature_length: BigEndian<u32>,
493}
494
495#[allow(clippy::absurd_extreme_comparisons)]
496const _: () = assert!(
497    std::mem::size_of::<SignatureBlockFormat1FixedHeader>() <= SignatureBlockFormat1::MIN_SIZE
498);
499
500/// [Signature Block Format 1](https://learn.microsoft.com/en-us/typography/opentype/spec/dsig#table-structure)
501#[derive(Clone)]
502pub struct SignatureBlockFormat1<'a> {
503    data: TableDataRef<'a, SignatureBlockFormat1FixedHeader>,
504}
505
506#[allow(clippy::needless_lifetimes)]
507impl<'a> SignatureBlockFormat1<'a> {
508    pub const MIN_SIZE: usize = (u16::RAW_BYTE_LEN + u16::RAW_BYTE_LEN + u32::RAW_BYTE_LEN);
509    basic_table_impls!(impl_the_methods);
510
511    /// Length (in bytes) of the PKCS#7 packet in the signature field.
512    pub fn signature_length(&self) -> u32 {
513        self.data.header().signature_length.get()
514    }
515
516    /// PKCS#7 packet
517    pub fn signature(&self) -> &'a [u8] {
518        let range = self.signature_byte_range();
519        self.offset_data()
520            .read_array(range)
521            .ok()
522            .unwrap_or_default()
523    }
524
525    pub fn _reserved1_byte_range(&self) -> Range<usize> {
526        let start = 0;
527        let end = start + u16::RAW_BYTE_LEN;
528        start..end
529    }
530
531    pub fn _reserved2_byte_range(&self) -> Range<usize> {
532        let start = self._reserved1_byte_range().end;
533        let end = start + u16::RAW_BYTE_LEN;
534        start..end
535    }
536
537    pub fn signature_length_byte_range(&self) -> Range<usize> {
538        let start = self._reserved2_byte_range().end;
539        let end = start + u32::RAW_BYTE_LEN;
540        start..end
541    }
542
543    pub fn signature_byte_range(&self) -> Range<usize> {
544        let signature_length = self.signature_length();
545        let start = self.signature_length_byte_range().end;
546        let end = start + (transforms::to_usize(signature_length)).saturating_mul(u8::RAW_BYTE_LEN);
547        start..end
548    }
549}
550
551const _: () = assert!(FontData::default_data_long_enough(
552    SignatureBlockFormat1::MIN_SIZE
553));
554
555impl Default for SignatureBlockFormat1<'_> {
556    fn default() -> Self {
557        Self {
558            data: TableDataRef::new(FontData::default_table_data().as_bytes())
559                .unwrap_or_else(|| unreachable!("the default data covers MIN_SIZE")),
560        }
561    }
562}