Skip to main content

fontoxide_ttlib/tables/
loca.rs

1//! `loca`: Index to Location table (`fontTools.ttLib.tables._l_o_c_a`).
2
3use fontoxide_misc::Tag;
4use fontoxide_misc::xml_reader::Element;
5use fontoxide_misc::xml_writer::XmlWriter;
6
7use crate::table::{Table, TableType, TableXml};
8use crate::tables::{Head, Maxp};
9use crate::{Error, Font, Result};
10
11/// Index to Location table (`table__l_o_c_a`): the offset of each glyph in
12/// `glyf`, plus the end of the last one. It is rebuilt when `glyf` is compiled.
13///
14/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/loca>.
15#[derive(Debug, Clone, Default, PartialEq, Eq)]
16pub struct Loca {
17	/// The glyph offsets (`locations`), if set.
18	pub locations: Option<Vec<u32>>,
19	/// Whether this is `LOCA`, the beyond-64k companion of the table.
20	pub extended: bool,
21}
22
23impl Loca {
24	/// Sets the glyph offsets (`set`).
25	pub fn set(&mut self, locations: Vec<u32>) {
26		self.locations = Some(locations);
27	}
28
29	/// The glyph offsets; empty if not set.
30	pub fn locations(&self) -> &[u32] {
31		self.locations.as_deref().unwrap_or_default()
32	}
33}
34
35impl TableType for Loca {
36	const TAG: Tag = Tag::new(b"loca");
37	const COMPANION: Option<Tag> = Some(Tag::new(b"LOCA"));
38
39	fn decompile(data: &[u8], font: &mut Font) -> Result<Self> {
40		Self::decompile_as(Self::TAG, data, font)
41	}
42
43	fn new_as(tag: Tag) -> Self {
44		Loca {
45			locations: None,
46			extended: tag == Tag::new(b"LOCA"),
47		}
48	}
49
50	fn decompile_as(tag: Tag, data: &[u8], font: &mut Font) -> Result<Self> {
51		let extended = tag == Tag::new(b"LOCA");
52		let long = font.require::<Head>()?.index_to_loc_format != 0;
53		let size = if long { 4 } else { 2 };
54		if !data.len().is_multiple_of(size) {
55			return Err(Error::value("bytes length not a multiple of item size"));
56		}
57		let locations: Vec<u32> = if long {
58			data.as_chunks::<4>()
59				.0
60				.iter()
61				.map(|&c| u32::from_be_bytes(c))
62				.collect()
63		} else {
64			data.as_chunks::<2>()
65				.0
66				.iter()
67				.map(|&c| 2 * u16::from_be_bytes(c) as u32)
68				.collect()
69		};
70		let num_glyphs = font.require_locked::<Maxp>(extended)?.num_glyphs as usize;
71		if locations.len() < num_glyphs + 1 {
72			log::warn!(
73				"corrupt 'loca' table, or wrong numGlyphs in 'maxp': {} {num_glyphs}",
74				locations.len() as i64 - 1
75			);
76		}
77		Ok(Loca {
78			locations: Some(locations),
79			extended,
80		})
81	}
82}
83
84impl Table for Loca {
85	/// The offsets are positional and rebuilt from `glyf` when compiling.
86	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
87		let _ = f;
88		Ok(())
89	}
90
91	fn tag(&self) -> Tag {
92		Font::locked_tag::<Self>(self.extended)
93	}
94
95	fn compile(&mut self, font: &mut Font) -> Result<Vec<u8>> {
96		// UPSTREAM-BUG(B13): only missing locations are handled (as none); an
97		// empty list fails in `max()`, e.g. a `loca` read from empty data.
98		let max = match &self.locations {
99			None => {
100				self.set(Vec::new());
101				0
102			}
103			Some(l) => *l
104				.iter()
105				.max()
106				.ok_or_else(|| Error::value("max() arg is an empty sequence"))?,
107		};
108		let locations = self.locations();
109		let short = max < 0x20000 && locations.iter().all(|l| l % 2 == 0);
110		let mut data = Vec::with_capacity(locations.len() * if short { 2 } else { 4 });
111		for &l in locations {
112			if short {
113				data.extend_from_slice(&((l / 2) as u16).to_be_bytes());
114			} else {
115				data.extend_from_slice(&l.to_be_bytes());
116			}
117		}
118		font.require::<Head>()?.index_to_loc_format = if short { 0 } else { 1 };
119		Ok(data)
120	}
121
122	fn clone_table(&self) -> Box<dyn Table> {
123		Box::new(self.clone())
124	}
125}
126
127impl TableXml for Loca {
128	fn to_xml(&self, writer: &mut XmlWriter, _font: &mut Font) -> Result<()> {
129		writer.comment("The 'loca' table will be calculated by the compiler");
130		writer.newline();
131		Ok(())
132	}
133
134	fn from_xml(&mut self, element: &Element, _font: &mut Font) -> Result<()> {
135		// `DefaultTable.fromXML`: raw data is accepted but unused.
136		if element.name == "hexdata" {
137			return Ok(());
138		}
139		Err(Error::ttlib(format!(
140			"can't handle '{}' element",
141			element.name
142		)))
143	}
144}