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
use Result;
use primitive::{Fixed, Tag};
use tape::{Tape, Value};
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct OffsetTable {
pub header: OffsetTableHeader,
pub records: Vec<OffsetTableRecord>,
}
table! {
#[doc = "The header of an offset table."]
#[derive(Copy)]
pub OffsetTableHeader {
version (Fixed),
numTables (u16 ),
searchRange (u16 ),
entrySelector (u16 ),
rangeShift (u16 ),
}
}
table! {
#[doc = "A record of an offset table."]
#[derive(Copy)]
pub OffsetTableRecord {
tag (u32),
checkSum (u32),
offset (u32),
length (u32),
}
}
impl Value for OffsetTable {
fn read<T: Tape>(tape: &mut T) -> Result<Self> {
if !is_known(try!(tape.peek::<Fixed>())) {
raise!("the font format is not supported");
}
let header = try!(OffsetTableHeader::read(tape));
let mut records = vec![];
for _ in 0..header.numTables {
records.push(try!(OffsetTableRecord::read(tape)));
}
Ok(OffsetTable { header: header, records: records })
}
}
impl OffsetTableRecord {
pub fn checksum<T, F>(&self, tape: &mut T, process: F) -> Result<bool>
where T: Tape, F: Fn(usize, u32) -> u32
{
let length = ((self.length as usize + 4 - 1) & !(4 - 1)) / 4;
tape.stay(|tape| {
try!(tape.jump(self.offset as u64));
let mut checksum: u64 = 0;
for i in 0..length {
checksum += process(i, try!(Value::read(tape))) as u64;
}
Ok(self.checkSum == checksum as u32)
})
}
}
#[inline]
fn is_known(version: Fixed) -> bool {
match version {
Fixed(0x00010000) => return true,
_ => {},
}
match &Tag::from(version).into() {
b"true" | b"typ1" | b"OTTO" => return true,
_ => {},
}
false
}
#[cfg(test)]
mod tests {
use std::io::Cursor;
use super::OffsetTableRecord;
#[test]
fn record_checksum() {
macro_rules! checksum(
($length:expr, $checksum:expr, $data:expr) => ({
let data: &[u8] = $data;
let mut reader = Cursor::new(data);
let table = OffsetTableRecord {
length: $length,
checkSum: $checksum,
.. OffsetTableRecord::default()
};
table.checksum(&mut reader, |_, chunk| chunk).unwrap()
})
);
assert!(!checksum!(3 * 4, 1 + 2 + 4, &[0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3]));
assert!( checksum!(3 * 4, 1 + 2 + 3, &[0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3]));
}
}