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
// Copyright 2018 Kyle Mayes
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A zero-allocation SFNT parser.
//!
//! # Example
//!
//! ```
//! # extern crate sfnt;
//! use std::fs::{File};
//! use std::io::{Read};
//!
//! use sfnt::{parse_sfnt};
//!
//! fn main() {
//!     // Read the font file into memory.
//!     let mut file = File::open("tests/resources/OpenSans-Italic.ttf").unwrap();
//!     let mut bytes = vec![];
//!     file.read_to_end(&mut bytes).unwrap();
//!
//!     // Parse the font file and find one of the tables in the font file.
//!     let sfnt = parse_sfnt(&bytes).unwrap();
//!     let (record, bytes) = sfnt.find("head").unwrap();
//!
//!     println!("{:?}", record);
//!     // Record { tag: "head", checksum: 4165466467, offset: 316, length: 54 }
//!
//!     println!("{:?}", bytes.len());
//!     // 54
//! }
//! ```

#![deny(missing_copy_implementations, missing_debug_implementations, missing_docs)]

#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
#![cfg_attr(feature="clippy", deny(clippy))]

#![no_std]

#[macro_use]
extern crate tarrasque;

use core::cmp::{Ordering};

use tarrasque::{Extract, ExtractError, ExtractResult, Stream, View, ViewIter, be_u32};

/// A `2.14` fixed point number.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Fixed2_14(pub u16);

impl<'a> Extract<'a, ()> for Fixed2_14 {
    fn extract(stream: &mut Stream<'a>, _: ()) -> ExtractResult<'a, Self> {
        stream.extract(()).map(Fixed2_14)
    }
}

impl Into<f32> for Fixed2_14 {
    fn into(self) -> f32 {
        f32::from(self.0) / 16384.0
    }
}

impl Into<f64> for Fixed2_14 {
    fn into(self) -> f64 {
        f64::from(self.0) / 16384.0
    }
}

/// A `16.16` fixed point number.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Fixed16_16(pub u32);

impl<'a> Extract<'a, ()> for Fixed16_16 {
    fn extract(stream: &mut Stream<'a>, _: ()) -> ExtractResult<'a, Self> {
        stream.extract(()).map(Fixed16_16)
    }
}

impl Into<f64> for Fixed16_16 {
    fn into(self) -> f64 {
        f64::from(self.0) / 65536.0
    }
}

/// A number of seconds that have elapsed since `1904-01-01T00:00:00Z`.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Timestamp(pub i64);

impl<'a> Extract<'a, ()> for Timestamp {
    fn extract(stream: &mut Stream<'a>, _: ()) -> ExtractResult<'a, Self> {
        stream.extract(()).map(Timestamp)
    }
}

extract! {
    /// An SFNT file header.
    #[derive(Copy, Clone, Debug, PartialEq, Eq)]
    pub Header[12] {
        /// The SFNT file version number.
        version: Fixed16_16 = ([extract]),
        /// The number of tables in the SFNT file.
        num_tables: u16 = ([extract]),
        /// The value of `(largest power of two <= num_tables) * 16`.
        search_range: u16 = ([extract]),
        /// The value of `log2(largest power of two <= num_tables)`.
        entry_selector: u16 = ([extract]),
        /// The value of `(num_tables * 16) - search_range`.
        range_shift: u16 = ([extract]),
    }
}

extract! {
    /// An SFNT file table record.
    #[derive(Copy, Clone, Debug, PartialEq, Eq)]
    pub Record<'a>[16] {
        /// The name of the table.
        tag: &'a str = ([extract(4)]),
        /// The checksum of the the table.
        checksum: u32 = ([extract]),
        /// The byte offset of the table in the SFNT file.
        offset: u32 = ([extract]),
        /// The byte length of the table.
        length: u32 = ([extract]),
    }
}

/// An SFNT file.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Sfnt<'a> {
    bytes: &'a [u8],
    header: Header,
    records: View<'a, Record<'a>, ()>,
}

impl<'a> Sfnt<'a> {
    /// Returns the bytes in this file.
    #[inline]
    pub fn bytes(&self) -> &'a [u8] {
        self.bytes
    }

    /// Returns the header in this file.
    #[inline]
    pub fn header(&self) -> Header {
        self.header
    }

    /// Returns the table records in this file.
    #[inline]
    pub fn records(&self) -> View<'a, Record<'a>, ()> {
        self.records
    }

    /// Returns the table in this file for the supplied table record.
    #[inline]
    pub fn get(&self, record: Record) -> &'a [u8] {
        let start = record.offset as usize;
        let end = start + record.length as usize;
        &self.bytes[start..end]
    }

    /// Returns the table in this file with the supplied tag.
    #[inline]
    pub fn find(&self, tag: &str) -> Option<(Record<'a>, &'a [u8])> {
        if self.header.num_tables == 0 {
            return None;
        }

        let mut low = 0;
        let mut high = self.header.num_tables as usize - 1;

        while low <= high {
            let middle = low + ((high - low) / 2);
            let record = self.records.get(middle).unwrap();

            match record[..4].cmp(tag.as_bytes()) {
                Ordering::Equal => {
                    let record = self.records.extract(middle).unwrap();
                    return Some((record, self.get(record)));
                },
                Ordering::Less => low = middle + 1,
                Ordering::Greater => high = middle - 1,
            }
        }

        None
    }

    /// Returns an iterator over the tables in this file.
    #[inline]
    pub fn iter(self) -> SfntIter<'a> {
        let records = self.records.iter();
        SfntIter(self, records)
    }
}

/// Parses the supplied SFNT file.
#[inline]
pub fn parse_sfnt(bytes: &[u8]) -> ExtractResult<Sfnt> {
    let mut stream = Stream(bytes);
    let header: Header = stream.extract(())?;
    let records: View<Record, _> = stream.extract((header.num_tables as usize, ()))?;
    let max = records.iter().map(|r| r.offset + r.length).max().unwrap_or(0) as usize;
    if bytes.len() >= max {
        Ok(Sfnt { bytes, header, records })
    } else {
        Err(ExtractError::Insufficient(max - bytes.len()))
    }
}

/// An iterator over the tables in an SFNT file.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct SfntIter<'a>(Sfnt<'a>, ViewIter<'a, Record<'a>, ()>);

impl<'a> Iterator for SfntIter<'a> {
    type Item = (Record<'a>, &'a [u8]);

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.1.size_hint()
    }

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.1.next().map(|r| (r, self.0.get(r)))
    }
}

impl<'a> DoubleEndedIterator for SfntIter<'a> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.1.next_back().map(|r| (r, self.0.get(r)))
    }
}

impl<'a> ExactSizeIterator for SfntIter<'a> { }

/// Returns the SFNT checksum for the supplied bytes.
pub fn checksum(bytes: &[u8]) -> u32 {
    let (prefix, suffix) = bytes.split_at(bytes.len() - (bytes.len() % 4));
    let prefix = prefix.chunks(4).map(be_u32).fold(0u32, |a, i| a.wrapping_add(i));
    match suffix.len() {
        0 => prefix,
        1 => prefix.wrapping_add(be_u32(&[suffix[0], 0, 0, 0])),
        2 => prefix.wrapping_add(be_u32(&[suffix[0], suffix[1], 0, 0])),
        3 => prefix.wrapping_add(be_u32(&[suffix[0], suffix[1], suffix[2], 0])),
        _ => unreachable!(),
    }
}