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
use std::collections::HashMap;

use Result;
use tape::{Tape, Value};

/// A char-to-glyph mapping.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct CharMapping {
    pub header: CharMappingHeader,
    pub records: Vec<CharMappingRecord>,
    pub encodings: Vec<CharMappingEncoding>,
}

/// An encoding of a char-to-glyph mapping.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CharMappingEncoding {
    /// Format 4.
    Format4(CharMappingEncoding4),
    /// Format 6.
    Format6(CharMappingEncoding6),
}

macro_rules! read_version(
    ($tape:ident) => ({
        let value = try!(Value::read($tape));
        if value != 0 {
            raise!("the version of the char-to-glyph mapping header is not supported");
        }
        Ok(value)
    });
);

table! {
    #[doc = "The header of a char-to-glyph mapping."]
    #[derive(Copy)]
    pub CharMappingHeader {
        version   (u16) |tape, this| { read_version!(tape) },
        numTables (u16),
    }
}

table! {
    #[doc = "A record of a char-to-glyph mapping."]
    #[derive(Copy)]
    pub CharMappingRecord {
        platformID (u16),
        encodingID (u16),
        offset     (u32),
    }
}

table! {
    #[doc = "A char-to-glyph encoding of format 4."]
    pub CharMappingEncoding4 {
        format        (u16     ),
        length        (u16     ),
        language      (u16     ),
        segCountX2    (u16     ),
        searchRange   (u16     ),
        entrySelector (u16     ),
        rangeShift    (u16     ),
        endCode       (Vec<u16>) |tape, this| { read_vector!(tape, this.segments()) },
        reservedPad   (u16     ),
        startCode     (Vec<u16>) |tape, this| { read_vector!(tape, this.segments()) },
        idDelta       (Vec<i16>) |tape, this| { read_vector!(tape, this.segments()) },
        idRangeOffset (Vec<u16>) |tape, this| { read_vector!(tape, this.segments()) },
        glyphIdArray  (Vec<u16>) |tape, this| { read_vector!(tape, try!(this.array_length())) },
    }
}

table! {
    #[doc = "A char-to-glyph encoding of format 6."]
    pub CharMappingEncoding6 {
        format       (u16     ),
        length       (u16     ),
        language     (u16     ),
        firstCode    (u16     ),
        entryCount   (u16     ),
        glyphIdArray (Vec<u16>) |tape, this| { read_vector!(tape, this.entryCount) },
    }
}

impl Value for CharMapping {
    fn read<T: Tape>(tape: &mut T) -> Result<CharMapping> {
        let position = try!(tape.position());
        let header = match try!(tape.peek::<u16>()) {
            0 => try!(CharMappingHeader::read(tape)),
            _ => raise!("the format of the char-to-glyph mapping header is not supported"),
        };
        let mut records = vec![];
        for _ in 0..header.numTables {
            records.push(try!(CharMappingRecord::read(tape)));
        }
        let mut encodings = vec![];
        for encoding in records.iter() {
            try!(tape.jump(position + encoding.offset as u64));
            encodings.push(match try!(tape.peek::<u16>()) {
                4 => CharMappingEncoding::Format4(try!(Value::read(tape))),
                6 => CharMappingEncoding::Format6(try!(Value::read(tape))),
                _ => unimplemented!(),
            });
        }
        Ok(CharMapping { header: header, records: records, encodings: encodings })
    }
}

impl CharMappingEncoding4 {
    /// Return the mapping.
    pub fn mapping(&self) -> HashMap<u16, u16> {
        let segments = self.segments();
        let mut map = HashMap::new();
        for i in 0..(segments - 1) {
            let startCode = self.startCode[i];
            let idDelta = self.idDelta[i];
            let idRangeOffset = self.idRangeOffset[i];
            for j in startCode..(self.endCode[i] + 1) {
                let index = if idRangeOffset > 0 {
                    let offset = (idRangeOffset / 2 + (j - startCode)) - (segments - i) as u16;
                    self.glyphIdArray[offset as usize]
                } else {
                    (idDelta + j as i16) as u16
                };
                map.insert(j, index);
            }
        }
        map
    }

    fn array_length(&self) -> Result<usize> {
        let segments = self.segments();
        if segments == 0 {
            raise!("found a char-to-glyph mapping with no segments");
        }
        if self.startCode[segments - 1] != 0xffff || self.endCode[segments - 1] != 0xffff {
            raise!("found a malformed char-to-glyph mapping");
        }
        let mut length = 0;
        for i in 0..(segments - 1) {
            let startCode = self.startCode[i];
            let idRangeOffset = self.idRangeOffset[i];
            for j in startCode..(self.endCode[i] + 1) {
                if idRangeOffset > 0 {
                    let end = (idRangeOffset / 2 + (j - startCode)) - (segments - i) as u16 + 1;
                    if end > length {
                        length = end;
                    }
                }
            }
        }
        Ok(length as usize)
    }

    #[inline]
    fn segments(&self) -> usize {
        self.segCountX2 as usize / 2
    }
}