read_fonts/tables/
loca.rs

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
//! The [loca (Index to Location)][loca] table
//!
//! [loca]: https://docs.microsoft.com/en-us/typography/opentype/spec/loca

use crate::{
    read::{FontRead, FontReadWithArgs, ReadArgs, ReadError},
    table_provider::TopLevelTable,
    FontData,
};
use types::{BigEndian, GlyphId, Tag};

#[cfg(feature = "experimental_traverse")]
use crate::traversal;

/// The [loca] table.
///
/// [loca]: https://docs.microsoft.com/en-us/typography/opentype/spec/loca
#[derive(Clone)]
pub enum Loca<'a> {
    Short(&'a [BigEndian<u16>]),
    Long(&'a [BigEndian<u32>]),
}

impl TopLevelTable for Loca<'_> {
    const TAG: Tag = Tag::new(b"loca");
}

impl<'a> Loca<'a> {
    pub fn read(data: FontData<'a>, is_long: bool) -> Result<Self, crate::ReadError> {
        Self::read_with_args(data, &is_long)
    }

    pub fn len(&self) -> usize {
        match self {
            Loca::Short(data) => data.len().saturating_sub(1),
            Loca::Long(data) => data.len().saturating_sub(1),
        }
    }

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

    pub fn all_offsets_are_ascending(&self) -> bool {
        match self {
            Loca::Short(data) => !data
                .iter()
                .zip(data.iter().skip(1))
                .any(|(start, end)| start > end),
            Loca::Long(data) => !data
                .iter()
                .zip(data.iter().skip(1))
                .any(|(start, end)| start > end),
        }
    }

    /// Attempt to return the offset for a given glyph id.
    pub fn get_raw(&self, idx: usize) -> Option<u32> {
        match self {
            Loca::Short(data) => data.get(idx).map(|x| x.get() as u32 * 2),
            Loca::Long(data) => data.get(idx).map(|x| x.get()),
        }
    }

    pub fn get_glyf(
        &self,
        gid: GlyphId,
        glyf: &super::glyf::Glyf<'a>,
    ) -> Result<Option<super::glyf::Glyph<'a>>, ReadError> {
        let idx = gid.to_u32() as usize;
        let start = self.get_raw(idx).ok_or(ReadError::OutOfBounds)?;
        let end = self.get_raw(idx + 1).ok_or(ReadError::OutOfBounds)?;
        if start == end {
            return Ok(None);
        }
        let data = glyf
            .offset_data()
            .slice(start as usize..end as usize)
            .ok_or(ReadError::OutOfBounds)?;
        match super::glyf::Glyph::read(data) {
            Ok(glyph) => Ok(Some(glyph)),
            Err(e) => Err(e),
        }
    }
}

impl ReadArgs for Loca<'_> {
    type Args = bool;
}

impl<'a> FontReadWithArgs<'a> for Loca<'a> {
    fn read_with_args(data: FontData<'a>, args: &Self::Args) -> Result<Self, crate::ReadError> {
        let is_long = *args;
        if is_long {
            data.read_array(0..data.len()).map(Loca::Long)
        } else {
            data.read_array(0..data.len()).map(Loca::Short)
        }
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> traversal::SomeTable<'a> for Loca<'a> {
    fn type_name(&self) -> &str {
        "loca"
    }

    fn get_field(&self, idx: usize) -> Option<traversal::Field<'a>> {
        match idx {
            0usize => Some(traversal::Field::new("offsets", self.clone())),
            _ => None,
        }
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> traversal::SomeArray<'a> for Loca<'a> {
    fn len(&self) -> usize {
        self.len()
    }

    fn get(&self, idx: usize) -> Option<traversal::FieldType<'a>> {
        self.get_raw(idx).map(|off| off.into())
    }

    fn type_name(&self) -> &str {
        "Offset32"
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> std::fmt::Debug for Loca<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        (self as &dyn traversal::SomeTable<'a>).fmt(f)
    }
}

#[cfg(test)]
mod tests {
    use types::Scalar;

    use crate::test_helpers::BeBuffer;

    use super::Loca;

    fn to_loca_bytes<T: Scalar + Copy>(values: &[T]) -> (BeBuffer, bool) {
        let value_num_bytes = std::mem::size_of::<T>();
        let is_long = if value_num_bytes == 2 {
            false
        } else if value_num_bytes == 4 {
            true
        } else {
            panic!("invalid integer type must be u32 or u16")
        };
        let mut buffer = BeBuffer::default();

        for v in values {
            buffer = buffer.push(*v);
        }

        (buffer, is_long)
    }

    fn check_loca_sorting(values: &[u16], is_sorted: bool) {
        let (bytes, is_long) = to_loca_bytes(values);
        let loca = Loca::read(bytes.font_data(), is_long).unwrap();
        assert_eq!(loca.all_offsets_are_ascending(), is_sorted);

        let u32_values: Vec<u32> = values.iter().map(|v| *v as u32).collect();
        let (bytes, is_long) = to_loca_bytes(&u32_values);
        let loca = Loca::read(bytes.font_data(), is_long).unwrap();
        assert_eq!(loca.all_offsets_are_ascending(), is_sorted);
    }

    #[test]
    fn all_offsets_are_ascending() {
        // Sorted
        let empty: &[u16] = &[];
        check_loca_sorting(empty, true);
        check_loca_sorting(&[0], true);
        check_loca_sorting(&[0, 0], true);
        check_loca_sorting(&[0, 1], true);
        check_loca_sorting(&[1, 2, 2, 3, 7], true);

        // Unsorted
        check_loca_sorting(&[1, 0], false);
        check_loca_sorting(&[1, 3, 2], false);
        check_loca_sorting(&[2, 1, 3], false);
        check_loca_sorting(&[1, 2, 3, 2, 7], false);
    }
}