Skip to main content

read_fonts/ps/cff/
index.rs

1//! Parsing for PostScript INDEX objects.
2//!
3//! See <https://learn.microsoft.com/en-us/typography/opentype/spec/cff2#5-index-data>
4
5use crate::codegen_prelude::*;
6use crate::model::Error;
7
8#[doc(inline)]
9pub use super::{v1::Index as Index1, v2::Index as Index2};
10
11/// Common type for uniform access to CFF and CFF2 index formats.
12#[derive(Clone)]
13pub enum Index<'a> {
14    Empty,
15    Format1(Index1<'a>),
16    Format2(Index2<'a>),
17}
18
19impl<'a> Index<'a> {
20    /// Creates a new index from the given data.
21    ///
22    /// The caller must specify whether the data comes from a `CFF2` table.
23    pub fn new(data: &'a [u8], is_cff2: bool) -> Result<Self, Error> {
24        let data = FontData::new(data);
25        Ok(if is_cff2 {
26            if data.len() == 4 && data.read_at::<u32>(0)? == 0 {
27                return Ok(Self::Empty);
28            }
29            Index2::read(data).map(|ix| ix.into())?
30        } else {
31            if data.len() == 2 && data.read_at::<u16>(0)? == 0 {
32                return Ok(Self::Empty);
33            }
34            Index1::read(data).map(|ix| ix.into())?
35        })
36    }
37
38    /// Returns the number of objects in the index.
39    pub fn count(&self) -> u32 {
40        match self {
41            Self::Empty => 0,
42            Self::Format1(ix) => ix.count() as u32,
43            Self::Format2(ix) => ix.count(),
44        }
45    }
46
47    /// Computes a bias that is added to a subroutine operator in a
48    /// charstring.
49    ///
50    /// See <https://learn.microsoft.com/en-us/typography/opentype/spec/cff2#9-local-and-global-subr-indexes>
51    pub fn subr_bias(&self) -> i32 {
52        let count = self.count();
53        if count < 1240 {
54            107
55        } else if count < 33900 {
56            1131
57        } else {
58            32768
59        }
60    }
61
62    /// Returns the total size in bytes of the index table.
63    pub fn size_in_bytes(&self) -> Option<usize> {
64        match self {
65            Self::Empty => Some(0),
66            Self::Format1(ix) => ix.size_in_bytes(),
67            Self::Format2(ix) => ix.size_in_bytes(),
68        }
69    }
70
71    /// Returns the offset at the given index.
72    pub fn get_offset(&self, index: usize) -> Option<usize> {
73        match self {
74            Self::Empty => None,
75            Self::Format1(ix) => ix.get_offset(index),
76            Self::Format2(ix) => ix.get_offset(index),
77        }
78    }
79
80    /// Returns the data for the object at the given index.
81    pub fn get(&self, index: usize) -> Option<&'a [u8]> {
82        match self {
83            Self::Empty => None,
84            Self::Format1(ix) => ix.get(index),
85            Self::Format2(ix) => ix.get(index),
86        }
87    }
88
89    pub fn off_size(&self) -> u8 {
90        match self {
91            Self::Empty => 0,
92            Self::Format1(ix) => ix.off_size(),
93            Self::Format2(ix) => ix.off_size(),
94        }
95    }
96}
97
98impl<'a> From<Index1<'a>> for Index<'a> {
99    fn from(value: Index1<'a>) -> Self {
100        Self::Format1(value)
101    }
102}
103
104impl<'a> From<Index2<'a>> for Index<'a> {
105    fn from(value: Index2<'a>) -> Self {
106        Self::Format2(value)
107    }
108}
109
110impl Default for Index<'_> {
111    fn default() -> Self {
112        Self::Empty
113    }
114}
115
116impl<'a> Index1<'a> {
117    /// Returns the total size in bytes of the index table.
118    pub fn size_in_bytes(&self) -> Option<usize> {
119        // 2 byte count + 1 byte off_size
120        const HEADER_SIZE: usize = 3;
121        // An empty CFF index contains only a 2 byte count field
122        const EMPTY_SIZE: usize = 2;
123        let count = self.count() as usize;
124        Some(match count {
125            0 => EMPTY_SIZE,
126            _ => HEADER_SIZE + self.offsets().len() + self.get_offset(count)?,
127        })
128    }
129
130    /// Returns the offset of the object at the given index.
131    pub fn get_offset(&self, index: usize) -> Option<usize> {
132        read_offset(
133            index,
134            self.count() as usize,
135            self.off_size(),
136            self.offsets(),
137        )
138    }
139
140    /// Returns the data for the object at the given index.
141    pub fn get(&self, index: usize) -> Option<&'a [u8]> {
142        self.data()
143            .get(self.get_offset(index)?..self.get_offset(index + 1)?)
144    }
145}
146
147impl<'a> Index2<'a> {
148    /// Returns the total size in bytes of the index table.
149    pub fn size_in_bytes(&self) -> Option<usize> {
150        // 4 byte count + 1 byte off_size
151        const HEADER_SIZE: usize = 5;
152        // An empty CFF2 index contains only a 4 byte count field
153        const EMPTY_SIZE: usize = 4;
154        let count = self.count() as usize;
155        Some(match count {
156            0 => EMPTY_SIZE,
157            _ => HEADER_SIZE + self.offsets().len() + self.get_offset(count)?,
158        })
159    }
160
161    /// Returns the offset of the object at the given index.
162    pub fn get_offset(&self, index: usize) -> Option<usize> {
163        read_offset(
164            index,
165            self.count() as usize,
166            self.off_size(),
167            self.offsets(),
168        )
169    }
170
171    /// Returns the data for the object at the given index.
172    pub fn get(&self, index: usize) -> Option<&'a [u8]> {
173        self.data()
174            .get(self.get_offset(index)?..self.get_offset(index + 1)?)
175    }
176}
177
178/// Reads an offset which is encoded as a variable sized integer.
179fn read_offset(index: usize, count: usize, offset_size: u8, offset_data: &[u8]) -> Option<usize> {
180    // There are actually count + 1 entries in the offset array.
181    //
182    // "Offsets in the offset array are relative to the byte that precedes
183    // the object data. Therefore the first element of the offset array is
184    // always 1. (This ensures that every object has a corresponding offset
185    // which is always nonzero and permits the efficient implementation of
186    // dynamic object loading.)"
187    //
188    // See <https://learn.microsoft.com/en-us/typography/opentype/spec/cff2#table-7-index-format>
189    if index > count {
190        return None;
191    }
192    let data_offset = index * offset_size as usize;
193    let offset_data = FontData::new(offset_data);
194    match offset_size {
195        1 => offset_data.read_at::<u8>(data_offset).ok()? as usize,
196        2 => offset_data.read_at::<u16>(data_offset).ok()? as usize,
197        3 => offset_data.read_at::<Uint24>(data_offset).ok()?.to_u32() as usize,
198        4 => offset_data.read_at::<u32>(data_offset).ok()? as usize,
199        // the spec allows only 1 through 4
200        _ => return None,
201    }
202    // As above, subtract one to get the actual offset. A zero is malformed:
203    // the spec says the first entry is always 1.
204    .checked_sub(1)
205}
206
207#[cfg(test)]
208mod tests {
209    use font_test_data::bebuffer::BeBuffer;
210
211    use super::*;
212
213    enum IndexParams {
214        Format1 { off_size: u8, count: usize },
215        Format2 { off_size: u8, count: usize },
216    }
217
218    #[test]
219    fn index_format1_offsize1_count4() {
220        test_index(IndexParams::Format1 {
221            off_size: 1,
222            count: 4,
223        });
224    }
225
226    #[test]
227    fn index_format1_offsize2_count64() {
228        test_index(IndexParams::Format1 {
229            off_size: 2,
230            count: 64,
231        });
232    }
233
234    #[test]
235    fn index_format1_offsize3_count128() {
236        test_index(IndexParams::Format1 {
237            off_size: 3,
238            count: 128,
239        });
240    }
241
242    #[test]
243    fn index_format1_offsize4_count256() {
244        test_index(IndexParams::Format1 {
245            off_size: 4,
246            count: 256,
247        });
248    }
249
250    #[test]
251    fn index_format2_offsize1_count4() {
252        test_index(IndexParams::Format2 {
253            off_size: 4,
254            count: 256,
255        });
256    }
257
258    #[test]
259    fn index_format2_offsize2_count64() {
260        test_index(IndexParams::Format2 {
261            off_size: 2,
262            count: 64,
263        });
264    }
265
266    #[test]
267    fn index_format2_offsize3_count128() {
268        test_index(IndexParams::Format2 {
269            off_size: 3,
270            count: 128,
271        });
272    }
273
274    #[test]
275    fn index_format2_offsize4_count256() {
276        test_index(IndexParams::Format2 {
277            off_size: 4,
278            count: 256,
279        });
280    }
281
282    fn test_index(params: IndexParams) {
283        let (fmt, off_size, count) = match params {
284            IndexParams::Format1 { off_size, count } => (1, off_size, count),
285            IndexParams::Format2 { off_size, count } => (2, off_size, count),
286        };
287        let buf = make_index(fmt, off_size, count);
288        let index = Index::new(buf.data(), fmt == 2).unwrap();
289        let built_off_size = match &index {
290            Index::Empty => 0,
291            Index::Format1(v1) => v1.off_size(),
292            Index::Format2(v2) => v2.off_size(),
293        };
294        assert_eq!(built_off_size, off_size);
295        assert_eq!(index.count(), count as u32);
296        for i in 0..count {
297            let object = index.get(i).unwrap();
298            let expected_len = (i + 1) * 10;
299            let expected_bytes = vec![i as u8; expected_len];
300            assert_eq!(object, expected_bytes);
301        }
302    }
303
304    fn make_index(fmt: u8, off_size: u8, count: usize) -> BeBuffer {
305        // We'll add `count` objects to the INDEX, each containing
306        // `(i + 1) * 10` bytes of the value `i`.
307        let mut buf = BeBuffer::new();
308        match fmt {
309            1 => buf = buf.push(count as u16),
310            2 => buf = buf.push(count as u32),
311            _ => panic!("INDEX fmt should be 1 or 2"),
312        }
313        if count == 0 {
314            return buf;
315        }
316        buf = buf.push(off_size);
317        // Offsets start at 1.
318        let mut offset = 1usize;
319        for i in 0..count + 1 {
320            buf = match off_size {
321                1 => buf.push(offset as u8),
322                2 => buf.push(offset as u16),
323                3 => buf.push(Uint24::checked_new(offset as u32).unwrap()),
324                4 => buf.push(offset as u32),
325                _ => panic!("off_size should be 1-4"),
326            };
327            offset += (i + 1) * 10;
328        }
329        // Now the data
330        for i in 0..count {
331            buf = buf.extend(std::iter::repeat_n(i as u8, (i + 1) * 10));
332        }
333        buf
334    }
335}