ttf-parser 0.2.0

A high-level, safe, zero-allocation TrueType font parser.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use std::ops::Range;

use crate::{Error, Result};

pub trait FromData: Sized {
    /// Parses an object from a raw data.
    ///
    /// This method **must** not panic and **must** not read past the bounds.
    fn parse(s: &mut SafeStream) -> Self;

    /// Returns an object size in raw data.
    ///
    /// `mem::size_of` by default.
    ///
    /// Reimplement when size of `Self` != size of a raw data.
    /// For example, when you parsing u16, but storing it as u8.
    /// In this case `size_of::<Self>()` == 1, but `FromData::raw_size()` == 2.
    fn raw_size() -> usize {
        std::mem::size_of::<Self>()
    }
}

impl FromData for u8 {
    #[inline]
    fn parse(s: &mut SafeStream) -> Self {
        s.data[s.offset]
    }
}

impl FromData for i8 {
    #[inline]
    fn parse(s: &mut SafeStream) -> Self {
        s.data[s.offset] as i8
    }
}

impl FromData for u16 {
    #[inline]
    fn parse(s: &mut SafeStream) -> Self {
        let d = s.data;
        let i = s.offset;
        (d[i + 0] as u16) << 8 | d[i + 1] as u16
    }
}

impl FromData for i16 {
    #[inline]
    fn parse(s: &mut SafeStream) -> Self {
        let d = s.data;
        let i = s.offset;
        ((d[i + 0] as u16) << 8 | d[i + 1] as u16) as i16
    }
}

impl FromData for u32 {
    #[inline]
    fn parse(s: &mut SafeStream) -> Self {
        let d = s.data;
        let i = s.offset;

          (d[i + 0] as u32) << 24
        | (d[i + 1] as u32) << 16
        | (d[i + 2] as u32) << 8
        |  d[i + 3] as u32
    }
}


pub trait TryFromData: Sized {
    /// Parses an object from a raw data.
    fn try_parse(s: &mut SafeStream) -> Result<Self>;

    /// Returns an object size in raw data.
    ///
    /// `mem::size_of` by default.
    ///
    /// Reimplement when size of `Self` != size of a raw data.
    /// For example, when you parsing u16, but storing it as u8.
    /// In this case `size_of::<Self>()` == 1, but `TryFromData::raw_size()` == 2.
    fn raw_size() -> usize {
        std::mem::size_of::<Self>()
    }
}


// Like `usize`, but for font.
pub trait FSize {
    fn to_usize(&self) -> usize;
}

impl FSize for u16 {
    #[inline]
    fn to_usize(&self) -> usize { *self as usize }
}

impl FSize for u32 {
    #[inline]
    fn to_usize(&self) -> usize { *self as usize }
}


#[derive(Clone, Copy)]
pub struct LazyArray<'a, T> {
    data: &'a [u8],
    phantom: std::marker::PhantomData<T>,
}

impl<'a, T: FromData> LazyArray<'a, T> {
    #[inline]
    pub fn new(data: &'a [u8]) -> Self {
        LazyArray {
            data,
            phantom: std::marker::PhantomData,
        }
    }

    pub fn at<L: FSize>(&self, index: L) -> T {
        let start = index.to_usize() * T::raw_size();
        let end = start + T::raw_size();
        let mut s = SafeStream::new(&self.data[start..end]);
        T::parse(&mut s)
    }

    pub fn get<L: FSize>(&self, index: L) -> Option<T> {
        if index.to_usize() < self.len() {
            let start = index.to_usize() * T::raw_size();
            let end = start + T::raw_size();
            let mut s = SafeStream::new(&self.data[start..end]);
            Some(T::parse(&mut s))
        } else {
            None
        }
    }

    #[inline]
    pub fn last(&self) -> Option<T> {
        if !self.is_empty() {
            self.get(self.len() as u32 - 1)
        } else {
            None
        }
    }

    #[inline]
    pub fn len(&self) -> usize {
        self.data.len() / T::raw_size()
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    #[inline]
    pub fn binary_search_by<F>(&self, mut f: F) -> Option<T>
        where F: FnMut(&T) -> std::cmp::Ordering
    {
        // Based on Rust std implementation.

        use std::cmp::Ordering;

        let mut size = self.len() as u32;
        if size == 0 {
            return None;
        }

        let mut base = 0;
        while size > 1 {
            let half = size / 2;
            let mid = base + half;
            // mid is always in [0, size), that means mid is >= 0 and < size.
            // mid >= 0: by definition
            // mid < size: mid = size / 2 + size / 4 + size / 8 ...
            let cmp = f(&self.at(mid));
            base = if cmp == Ordering::Greater { base } else { mid };
            size -= half;
        }

        // base is always in [0, size) because base <= mid.
        let value = self.at(base);
        let cmp = f(&value);
        if cmp == Ordering::Equal { Some(value) } else { None }
    }
}

impl<'a, T: FromData + std::fmt::Debug + Copy> std::fmt::Debug for LazyArray<'a, T> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.debug_list().entries(self.into_iter()).finish()
    }
}

impl<'a, T: FromData> IntoIterator for LazyArray<'a, T> {
    type Item = T;
    type IntoIter = LazyArrayIter<'a, T>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        LazyArrayIter {
            data: self,
            offset: 0,
        }
    }
}


pub struct LazyArrayIter<'a, T> {
    data: LazyArray<'a, T>,
    offset: u32,
}

impl<'a, T: FromData> Iterator for LazyArrayIter<'a, T> {
    type Item = T;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.offset as usize == self.data.len() {
            return None;
        }

        let index = self.offset;
        self.offset += 1;
        self.data.get(index)
    }
}


pub trait TrySlice<'a> {
    fn try_slice(&self, range: Range<usize>) -> Result<&'a [u8]>;
}

impl<'a> TrySlice<'a> for &'a [u8] {
    #[inline]
    fn try_slice(&self, range: Range<usize>) -> Result<&'a [u8]> {
        self.get(range.clone())
            .ok_or_else(|| Error::SliceOutOfBounds {
                start: range.start as u32,
                end: range.end as u32,
                data_len: self.len() as u32,
            })
    }
}


#[derive(Clone, Copy)]
pub struct Stream<'a> {
    data: &'a [u8],
    offset: usize,
}

impl<'a> Stream<'a> {
    #[inline]
    pub fn new(data: &'a [u8]) -> Self {
        Stream {
            data,
            offset: 0,
        }
    }

    #[inline]
    pub fn new_at(data: &'a [u8], offset: usize) -> Self {
        Stream {
            data,
            offset,
        }
    }

    #[inline]
    pub fn at_end(&self) -> bool {
        self.offset == self.data.len()
    }

    #[inline]
    pub fn offset(&self) -> usize {
        self.offset
    }

    #[inline]
    pub fn tail(&self) -> Result<&'a [u8]> {
        self.data.try_slice(self.offset..self.data.len())
    }

    #[inline]
    pub fn skip<T: FromData>(&mut self) {
        self.offset += T::raw_size();
    }

    #[inline]
    pub fn skip_len<L: FSize>(&mut self, len: L) {
        self.offset += len.to_usize();
    }

    #[inline]
    pub fn read<T: FromData>(&mut self) -> Result<T> {
        let start = self.offset;
        self.offset += T::raw_size();
        let end = self.offset;

        let data = self.data.try_slice(start..end)?;
        let mut s = SafeStream::new(data);
        Ok(T::parse(&mut s))
    }

    #[inline]
    pub fn try_read<T: TryFromData>(&mut self) -> Result<T> {
        let start = self.offset;
        self.offset += T::raw_size();
        let end = self.offset;

        let data = self.data.try_slice(start..end)?;
        let mut s = SafeStream::new(data);
        T::try_parse(&mut s)
    }

    #[inline]
    pub fn read_at<T: FromData>(data: &[u8], mut offset: usize) -> Result<T> {
        let start = offset;
        offset += T::raw_size();
        let end = offset;

        let data = data.try_slice(start..end)?;
        let mut s = SafeStream::new(data);
        Ok(T::parse(&mut s))
    }

    #[inline]
    pub fn read_bytes<L: FSize>(&mut self, len: L) -> Result<&'a [u8]> {
        let offset = self.offset;
        self.offset += len.to_usize();
        self.data.try_slice(offset..(offset + len.to_usize()))
    }

    #[inline]
    pub fn read_array<T: FromData, L: FSize>(&mut self, len: L) -> Result<LazyArray<'a, T>> {
        let len = len.to_usize() * T::raw_size();
        let data = self.read_bytes(len as u32)?;
        Ok(LazyArray::new(data))
    }

    pub fn read_f2_14(&mut self) -> Result<f32> {
        Ok(self.read::<i16>()? as f32 / 16384.0)
    }
}


/// A "safe" stream.
///
/// Unlike `Stream`, `SafeStream` doesn't perform bounds checking on each read.
/// It leverages the type system, so we can sort of guarantee that
/// we do not read past the bounds.
///
/// For example, if we are iterating a `LazyArray` we already checked it's size
/// and we can't read past the bounds, so we can remove useless checks.
///
/// It's still not 100% guarantee, but it makes code easier to read and a bit faster.
/// And we still backed by the Rust's bounds checking.
#[derive(Clone, Copy)]
pub struct SafeStream<'a> {
    data: &'a [u8],
    offset: usize,
}

impl<'a> SafeStream<'a> {
    #[inline]
    pub fn new(data: &'a [u8]) -> Self {
        SafeStream {
            data,
            offset: 0,
        }
    }

    #[inline]
    pub fn new_at(data: &'a [u8], offset: usize) -> Self {
        SafeStream {
            data,
            offset,
        }
    }

    #[inline]
    pub fn skip<T: FromData>(&mut self) {
        self.offset += T::raw_size();
    }

    #[inline]
    pub fn read<T: FromData>(&mut self) -> T {
        let start = self.offset;
        let v = T::parse(self);
        self.offset = start + T::raw_size();
        v
    }

    #[inline]
    pub fn read_u24(&mut self) -> u32 {
        let d = self.data;
        let i = self.offset;
        let n = 0 << 24 | (d[i + 0] as u32) << 16 | (d[i + 1] as u32) << 8 | d[i + 2] as u32;
        self.offset += 3;
        n
    }

    #[inline]
    pub fn read_at<T: FromData>(data: &[u8], offset: usize) -> T {
        let mut s = SafeStream { data, offset };
        T::parse(&mut s)
    }
}


#[derive(Clone, Copy, Debug)]
pub struct Offset32(pub u32);

impl FromData for Offset32 {
    #[inline]
    fn parse(s: &mut SafeStream) -> Self {
        Offset32(s.read())
    }
}

impl FromData for Option<Offset32> {
    #[inline]
    fn parse(s: &mut SafeStream) -> Self {
        let offset: Offset32 = s.read();
        if offset.0 != 0 { Some(offset) } else { None }
    }

    fn raw_size() -> usize {
        Offset32::raw_size()
    }
}