read_fonts/tables/
loca.rs

1//! The [loca (Index to Location)][loca] table
2//!
3//! [loca]: https://docs.microsoft.com/en-us/typography/opentype/spec/loca
4
5use crate::{
6    read::{FontRead, FontReadWithArgs, ReadArgs, ReadError},
7    table_provider::TopLevelTable,
8    FontData,
9};
10use types::{BigEndian, GlyphId, Tag};
11
12#[cfg(feature = "experimental_traverse")]
13use crate::traversal;
14
15/// The [loca] table.
16///
17/// [loca]: https://docs.microsoft.com/en-us/typography/opentype/spec/loca
18#[derive(Clone)]
19pub enum Loca<'a> {
20    Short(&'a [BigEndian<u16>]),
21    Long(&'a [BigEndian<u32>]),
22}
23
24impl TopLevelTable for Loca<'_> {
25    const TAG: Tag = Tag::new(b"loca");
26}
27
28impl<'a> Loca<'a> {
29    pub fn read(data: FontData<'a>, is_long: bool) -> Result<Self, crate::ReadError> {
30        Self::read_with_args(data, &is_long)
31    }
32
33    pub fn len(&self) -> usize {
34        match self {
35            Loca::Short(data) => data.len().saturating_sub(1),
36            Loca::Long(data) => data.len().saturating_sub(1),
37        }
38    }
39
40    pub fn is_empty(&self) -> bool {
41        self.len() == 0
42    }
43
44    pub fn all_offsets_are_ascending(&self) -> bool {
45        match self {
46            Loca::Short(data) => !data
47                .iter()
48                .zip(data.iter().skip(1))
49                .any(|(start, end)| start > end),
50            Loca::Long(data) => !data
51                .iter()
52                .zip(data.iter().skip(1))
53                .any(|(start, end)| start > end),
54        }
55    }
56
57    /// Attempt to return the offset for a given glyph id.
58    pub fn get_raw(&self, idx: usize) -> Option<u32> {
59        match self {
60            Loca::Short(data) => data.get(idx).map(|x| x.get() as u32 * 2),
61            Loca::Long(data) => data.get(idx).map(|x| x.get()),
62        }
63    }
64
65    pub fn get_glyf(
66        &self,
67        gid: GlyphId,
68        glyf: &super::glyf::Glyf<'a>,
69    ) -> Result<Option<super::glyf::Glyph<'a>>, ReadError> {
70        let idx = gid.to_u32() as usize;
71        let start = self.get_raw(idx).ok_or(ReadError::OutOfBounds)?;
72        let end = self.get_raw(idx + 1).ok_or(ReadError::OutOfBounds)?;
73        if start == end {
74            return Ok(None);
75        }
76        let data = glyf
77            .offset_data()
78            .slice(start as usize..end as usize)
79            .ok_or(ReadError::OutOfBounds)?;
80        match super::glyf::Glyph::read(data) {
81            Ok(glyph) => Ok(Some(glyph)),
82            Err(e) => Err(e),
83        }
84    }
85}
86
87impl ReadArgs for Loca<'_> {
88    type Args = bool;
89}
90
91impl<'a> FontReadWithArgs<'a> for Loca<'a> {
92    fn read_with_args(data: FontData<'a>, args: &Self::Args) -> Result<Self, crate::ReadError> {
93        let is_long = *args;
94        if is_long {
95            data.read_array(0..data.len()).map(Loca::Long)
96        } else {
97            data.read_array(0..data.len()).map(Loca::Short)
98        }
99    }
100}
101
102#[cfg(feature = "experimental_traverse")]
103impl<'a> traversal::SomeTable<'a> for Loca<'a> {
104    fn type_name(&self) -> &str {
105        "loca"
106    }
107
108    fn get_field(&self, idx: usize) -> Option<traversal::Field<'a>> {
109        match idx {
110            0usize => Some(traversal::Field::new("offsets", self.clone())),
111            _ => None,
112        }
113    }
114}
115
116#[cfg(feature = "experimental_traverse")]
117impl<'a> traversal::SomeArray<'a> for Loca<'a> {
118    fn len(&self) -> usize {
119        self.len()
120    }
121
122    fn get(&self, idx: usize) -> Option<traversal::FieldType<'a>> {
123        self.get_raw(idx).map(|off| off.into())
124    }
125
126    fn type_name(&self) -> &str {
127        "Offset32"
128    }
129}
130
131#[cfg(feature = "experimental_traverse")]
132impl<'a> std::fmt::Debug for Loca<'a> {
133    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134        (self as &dyn traversal::SomeTable<'a>).fmt(f)
135    }
136}
137
138#[cfg(test)]
139mod tests {
140    use font_test_data::bebuffer::BeBuffer;
141    use types::Scalar;
142
143    use super::Loca;
144
145    fn to_loca_bytes<T: Scalar + Copy>(values: &[T]) -> (BeBuffer, bool) {
146        let value_num_bytes = std::mem::size_of::<T>();
147        let is_long = if value_num_bytes == 2 {
148            false
149        } else if value_num_bytes == 4 {
150            true
151        } else {
152            panic!("invalid integer type must be u32 or u16")
153        };
154        let mut buffer = BeBuffer::default();
155
156        for v in values {
157            buffer = buffer.push(*v);
158        }
159
160        (buffer, is_long)
161    }
162
163    fn check_loca_sorting(values: &[u16], is_sorted: bool) {
164        let (bytes, is_long) = to_loca_bytes(values);
165        let loca = Loca::read(bytes.data().into(), is_long).unwrap();
166        assert_eq!(loca.all_offsets_are_ascending(), is_sorted);
167
168        let u32_values: Vec<u32> = values.iter().map(|v| *v as u32).collect();
169        let (bytes, is_long) = to_loca_bytes(&u32_values);
170        let loca = Loca::read(bytes.data().into(), is_long).unwrap();
171        assert_eq!(loca.all_offsets_are_ascending(), is_sorted);
172    }
173
174    #[test]
175    fn all_offsets_are_ascending() {
176        // Sorted
177        let empty: &[u16] = &[];
178        check_loca_sorting(empty, true);
179        check_loca_sorting(&[0], true);
180        check_loca_sorting(&[0, 0], true);
181        check_loca_sorting(&[0, 1], true);
182        check_loca_sorting(&[1, 2, 2, 3, 7], true);
183
184        // Unsorted
185        check_loca_sorting(&[1, 0], false);
186        check_loca_sorting(&[1, 3, 2], false);
187        check_loca_sorting(&[2, 1, 3], false);
188        check_loca_sorting(&[1, 2, 3, 2, 7], false);
189    }
190}