Skip to main content

fontoxide_misc/
text_tools.rs

1//! Port of `fontTools.misc.textTools`: tags, hex dumps, binary strings, and the
2//! literal parsing that fontTools does with `safeEval` (`ast.literal_eval`).
3
4use std::fmt;
5
6/// A four-byte OpenType tag (`Tag`).
7///
8/// fontTools represents tags as `str` decoded from Latin-1; here they are the raw
9/// bytes. Ordering is bytewise, which matches sorting the Latin-1 strings.
10#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
11pub struct Tag(pub [u8; 4]);
12
13impl Tag {
14	/// Creates a tag from four bytes.
15	pub const fn new(bytes: &[u8; 4]) -> Self {
16		Tag(*bytes)
17	}
18
19	/// Creates a tag from a string of up to four Latin-1 characters, padded with
20	/// spaces. Returns `None` if the string is too long or not Latin-1.
21	pub fn from_str_padded(s: &str) -> Option<Self> {
22		let bytes = crate::py::latin1_encode(s)?;
23		if bytes.len() > 4 {
24			return None;
25		}
26		let mut tag = [b' '; 4];
27		tag[..bytes.len()].copy_from_slice(&bytes);
28		Some(Tag(tag))
29	}
30
31	/// Creates a tag from a string of exactly four Latin-1 characters.
32	pub fn from_str_exact(s: &str) -> Option<Self> {
33		let bytes = crate::py::latin1_encode(s)?;
34		Some(Tag(bytes.try_into().ok()?))
35	}
36
37	/// The tag bytes.
38	pub const fn to_bytes(self) -> [u8; 4] {
39		self.0
40	}
41
42	/// The tag as a Latin-1 decoded string, as fontTools holds it.
43	pub fn as_string(&self) -> String {
44		crate::py::latin1_decode(&self.0)
45	}
46}
47
48impl fmt::Display for Tag {
49	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50		for &b in &self.0 {
51			fmt::Write::write_char(f, b as char)?;
52		}
53		Ok(())
54	}
55}
56
57impl fmt::Debug for Tag {
58	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59		write!(f, "Tag({})", crate::py::str_repr(&self.as_string()))
60	}
61}
62
63impl From<[u8; 4]> for Tag {
64	fn from(bytes: [u8; 4]) -> Self {
65		Tag(bytes)
66	}
67}
68
69impl From<&[u8; 4]> for Tag {
70	fn from(bytes: &[u8; 4]) -> Self {
71		Tag(*bytes)
72	}
73}
74
75impl PartialEq<&str> for Tag {
76	fn eq(&self, other: &&str) -> bool {
77		Tag::from_str_exact(other).is_some_and(|t| t == *self)
78	}
79}
80
81impl PartialEq<[u8; 4]> for Tag {
82	fn eq(&self, other: &[u8; 4]) -> bool {
83		self.0 == *other
84	}
85}
86
87/// Converts a list of hex chunks to binary data (`readHex`). Whitespace inside the
88/// chunks is ignored; an odd number of digits is padded with a trailing `0`.
89pub fn read_hex<S: AsRef<str>>(content: impl IntoIterator<Item = S>) -> Option<Vec<u8>> {
90	let mut joined = String::new();
91	for chunk in content {
92		joined.push_str(chunk.as_ref());
93	}
94	de_hex_str(&joined)
95}
96
97/// Converts a hex string to binary data (`deHexStr`).
98pub fn de_hex_str(hexdata: &str) -> Option<Vec<u8>> {
99	let digits: Vec<u8> = hexdata.split_whitespace().flat_map(|s| s.bytes()).collect();
100	let mut out = Vec::with_capacity(digits.len().div_ceil(2));
101	for pair in digits.chunks(2) {
102		let hi = hex_value(pair[0])?;
103		let lo = match pair.get(1) {
104			Some(&c) => hex_value(c)?,
105			None => 0,
106		};
107		out.push(hi << 4 | lo);
108	}
109	Some(out)
110}
111
112fn hex_value(c: u8) -> Option<u8> {
113	(c as char).to_digit(16).map(|d| d as u8)
114}
115
116/// Converts binary data to a lowercase hex string (`hexStr`).
117pub fn hex_str(data: &[u8]) -> String {
118	const DIGITS: &[u8; 16] = b"0123456789abcdef";
119	let mut out = String::with_capacity(data.len() * 2);
120	for &b in data {
121		out.push(DIGITS[(b >> 4) as usize] as char);
122		out.push(DIGITS[(b & 0xF) as usize] as char);
123	}
124	out
125}
126
127/// Formats the low `bits` bits of `value` as binary digits in groups of eight
128/// (`num2binary`), e.g. `"00000000 00001011"`.
129pub fn num2binary(value: i64, bits: u32) -> String {
130	let mut groups = Vec::new();
131	let mut group = String::new();
132	let mut l = value;
133	for i in 0..bits {
134		group.insert(0, if l & 1 != 0 { '1' } else { '0' });
135		l >>= 1;
136		if (i + 1) % 8 == 0 {
137			groups.push(std::mem::take(&mut group));
138		}
139	}
140	if !group.is_empty() {
141		groups.push(group);
142	}
143	groups.reverse();
144	groups.join(" ")
145}
146
147/// Parses binary digits, ignoring whitespace (`binary2num`). Any digit other than
148/// `0` counts as `1`, as in fontTools.
149pub fn binary2num(bin: &str) -> i64 {
150	let mut l: i64 = 0;
151	for c in bin.chars().filter(|c| !c.is_whitespace()) {
152		l <<= 1;
153		if c != '0' {
154			l |= 1;
155		}
156	}
157	l
158}
159
160/// Sorts strings ignoring case, with ties broken by the original string
161/// (`caselessSort`).
162pub fn caseless_sort<S: AsRef<str> + Clone>(list: &[S]) -> Vec<S> {
163	let mut sorted = list.to_vec();
164	sorted.sort_by(|a, b| {
165		let (a, b) = (a.as_ref(), b.as_ref());
166		a.to_lowercase()
167			.cmp(&b.to_lowercase())
168			.then_with(|| a.cmp(b))
169	});
170	sorted
171}
172
173/// Pads `data` with NUL bytes to a multiple of `size` (`pad`).
174pub fn pad(data: &[u8], size: usize) -> Vec<u8> {
175	let mut out = data.to_vec();
176	if size > 1 {
177		let remainder = out.len() % size;
178		if remainder != 0 {
179			out.resize(out.len() + size - remainder, 0);
180		}
181	}
182	out
183}
184
185/// A Python literal, as produced by `safeEval` (`ast.literal_eval`).
186#[derive(Debug, Clone, PartialEq)]
187pub enum Literal {
188	/// `int`
189	Int(i128),
190	/// `float`
191	Float(f64),
192	/// `True` / `False`
193	Bool(bool),
194	/// `None`
195	None,
196	/// `str`
197	Str(String),
198	/// `bytes`
199	Bytes(Vec<u8>),
200	/// `tuple`
201	Tuple(Vec<Literal>),
202	/// `list`
203	List(Vec<Literal>),
204}
205
206impl Literal {
207	/// The value as an integer, if it is an `int` or a `bool` (which is an `int`
208	/// subclass in Python).
209	pub fn as_int(&self) -> Option<i128> {
210		match *self {
211			Literal::Int(i) => Some(i),
212			Literal::Bool(b) => Some(b as i128),
213			_ => None,
214		}
215	}
216
217	/// The value as a float, if it is numeric.
218	pub fn as_float(&self) -> Option<f64> {
219		match *self {
220			Literal::Float(f) => Some(f),
221			Literal::Int(i) => Some(i as f64),
222			Literal::Bool(b) => Some(b as i64 as f64),
223			_ => None,
224		}
225	}
226
227	/// Python truthiness.
228	pub fn is_truthy(&self) -> bool {
229		match self {
230			Literal::Int(i) => *i != 0,
231			Literal::Float(f) => *f != 0.0,
232			Literal::Bool(b) => *b,
233			Literal::None => false,
234			Literal::Str(s) => !s.is_empty(),
235			Literal::Bytes(b) => !b.is_empty(),
236			Literal::Tuple(v) | Literal::List(v) => !v.is_empty(),
237		}
238	}
239}
240
241/// Evaluates a Python literal (`safeEval`, i.e. `ast.literal_eval`).
242///
243/// Supports numbers (with unary signs), `True`/`False`/`None`, single- and
244/// double-quoted strings and bytes with common escapes, tuples and lists. Returns
245/// `None` where Python would raise.
246pub fn safe_eval(s: &str) -> Option<Literal> {
247	let mut p = LiteralParser {
248		s: s.trim_start_matches([' ', '\t']).as_bytes(),
249		pos: 0,
250	};
251	let value = p.expr()?;
252	p.skip_ws();
253	(p.pos == p.s.len()).then_some(value)
254}
255
256/// `safeEval` for a value that must be an integer.
257pub fn safe_eval_int(s: &str) -> Option<i128> {
258	safe_eval(s)?.as_int()
259}
260
261/// `safeEval` for a value that must be numeric.
262pub fn safe_eval_float(s: &str) -> Option<f64> {
263	safe_eval(s)?.as_float()
264}
265
266/// `int(s, 0)`: an integer literal with an optional base prefix and sign.
267pub fn parse_int_literal(s: &str) -> Option<i128> {
268	let t = s.trim();
269	let (negative, t) = match t.as_bytes().first() {
270		Some(b'-') => (true, &t[1..]),
271		Some(b'+') => (false, &t[1..]),
272		_ => (false, t),
273	};
274	let v = parse_unsigned_int(t)?;
275	Some(if negative { -v } else { v })
276}
277
278/// `int(s, radix)` for radix 2 to 36: an optional sign, then digits that may be
279/// separated by single underscores; radix 2, 8 and 16 also allow their prefix.
280pub fn parse_int_radix(s: &str, radix: u32) -> Option<i128> {
281	let t = s.trim();
282	let (negative, t) = match t.as_bytes().first() {
283		Some(b'-') => (true, &t[1..]),
284		Some(b'+') => (false, &t[1..]),
285		_ => (false, t),
286	};
287	let lower = t.to_ascii_lowercase();
288	let prefix = match radix {
289		2 => Some("0b"),
290		8 => Some("0o"),
291		16 => Some("0x"),
292		_ => None,
293	};
294	let digits = match prefix.and_then(|p| lower.strip_prefix(p)) {
295		Some(d) => d.strip_prefix('_').unwrap_or(d),
296		None => lower.as_str(),
297	};
298	if digits.is_empty()
299		|| digits.starts_with('_')
300		|| digits.ends_with('_')
301		|| digits.contains("__")
302		|| !digits
303			.bytes()
304			.all(|b| b == b'_' || (b as char).is_digit(radix))
305	{
306		return None;
307	}
308	let v = i128::from_str_radix(&digits.replace('_', ""), radix).ok()?;
309	Some(if negative { -v } else { v })
310}
311
312fn parse_unsigned_int(t: &str) -> Option<i128> {
313	let lower = t.to_ascii_lowercase();
314	let (radix, digits) = if let Some(d) = lower.strip_prefix("0x") {
315		(16, d)
316	} else if let Some(d) = lower.strip_prefix("0o") {
317		(8, d)
318	} else if let Some(d) = lower.strip_prefix("0b") {
319		(2, d)
320	} else {
321		// Decimal literals may not have leading zeros, except for zero itself.
322		if lower.len() > 1
323			&& lower.starts_with('0')
324			&& lower.bytes().any(|b| b != b'0' && b != b'_')
325		{
326			return None;
327		}
328		(10, lower.as_str())
329	};
330	let digits = digits.strip_prefix('_').unwrap_or(digits);
331	if digits.is_empty()
332		|| digits.starts_with('_')
333		|| digits.ends_with('_')
334		|| digits.contains("__")
335	{
336		return None;
337	}
338	i128::from_str_radix(&digits.replace('_', ""), radix).ok()
339}
340
341struct LiteralParser<'a> {
342	s: &'a [u8],
343	pos: usize,
344}
345
346impl LiteralParser<'_> {
347	fn skip_ws(&mut self) {
348		while self
349			.s
350			.get(self.pos)
351			.is_some_and(|c| matches!(c, b' ' | b'\t' | b'\n' | b'\r'))
352		{
353			self.pos += 1;
354		}
355	}
356
357	fn peek(&self) -> Option<u8> {
358		self.s.get(self.pos).copied()
359	}
360
361	fn expr(&mut self) -> Option<Literal> {
362		self.skip_ws();
363		match self.peek()? {
364			b'-' | b'+' => {
365				let negative = self.peek() == Some(b'-');
366				self.pos += 1;
367				match self.expr()? {
368					Literal::Int(i) => Some(Literal::Int(if negative { -i } else { i })),
369					Literal::Float(f) => Some(Literal::Float(if negative { -f } else { f })),
370					Literal::Bool(b) => {
371						let i = b as i128;
372						Some(Literal::Int(if negative { -i } else { i }))
373					}
374					_ => None,
375				}
376			}
377			b'(' => {
378				self.pos += 1;
379				let (items, trailing_comma) = self.sequence(b')')?;
380				if items.len() == 1 && !trailing_comma {
381					items.into_iter().next()
382				} else {
383					Some(Literal::Tuple(items))
384				}
385			}
386			b'[' => {
387				self.pos += 1;
388				Some(Literal::List(self.sequence(b']')?.0))
389			}
390			b'\'' | b'"' => self.string(false).map(Literal::Str),
391			b'b' | b'B' if matches!(self.s.get(self.pos + 1), Some(b'\'' | b'"')) => {
392				self.pos += 1;
393				let s = self.string(true)?;
394				Some(Literal::Bytes(s.chars().map(|c| c as u8).collect()))
395			}
396			c if c.is_ascii_digit() || c == b'.' => self.number(),
397			c if c.is_ascii_alphabetic() || c == b'_' => {
398				let start = self.pos;
399				while self
400					.peek()
401					.is_some_and(|c| c.is_ascii_alphanumeric() || c == b'_')
402				{
403					self.pos += 1;
404				}
405				match &self.s[start..self.pos] {
406					b"True" => Some(Literal::Bool(true)),
407					b"False" => Some(Literal::Bool(false)),
408					b"None" => Some(Literal::None),
409					_ => None,
410				}
411			}
412			_ => None,
413		}
414	}
415
416	/// Parses comma-separated items up to `close`; returns whether the last item
417	/// was followed by a comma.
418	fn sequence(&mut self, close: u8) -> Option<(Vec<Literal>, bool)> {
419		let mut items = Vec::new();
420		let mut trailing_comma = false;
421		loop {
422			self.skip_ws();
423			if self.peek()? == close {
424				self.pos += 1;
425				return Some((items, trailing_comma));
426			}
427			items.push(self.expr()?);
428			self.skip_ws();
429			match self.peek()? {
430				b',' => {
431					self.pos += 1;
432					trailing_comma = true;
433				}
434				c if c == close => {
435					trailing_comma = false;
436				}
437				_ => return None,
438			}
439		}
440	}
441
442	fn number(&mut self) -> Option<Literal> {
443		let start = self.pos;
444		while self
445			.peek()
446			.is_some_and(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'.')
447		{
448			let c = self.peek()?;
449			self.pos += 1;
450			// Exponent sign, e.g. 1e-5 (not in hex literals).
451			if matches!(c, b'e' | b'E')
452				&& matches!(self.peek(), Some(b'+' | b'-'))
453				&& !self.s[start..].starts_with(b"0x")
454				&& !self.s[start..].starts_with(b"0X")
455			{
456				self.pos += 1;
457			}
458		}
459		let text = std::str::from_utf8(&self.s[start..self.pos]).ok()?;
460		if let Some(i) = parse_unsigned_int(text) {
461			return Some(Literal::Int(i));
462		}
463		let lower = text.to_ascii_lowercase();
464		if lower.bytes().all(|c| c.is_ascii_digit() || c == b'_') {
465			// An integer literal that parse_unsigned_int rejected, e.g. "012".
466			return None;
467		}
468		if lower.starts_with("0x") || lower.starts_with("0o") || lower.starts_with("0b") {
469			return None;
470		}
471		if lower.contains(|c: char| c.is_ascii_alphabetic() && c != 'e') {
472			return None;
473		}
474		crate::py::parse_float(text).map(Literal::Float)
475	}
476
477	fn string(&mut self, bytes: bool) -> Option<String> {
478		let quote = self.peek()? as char;
479		// Triple-quoted strings are not used in TTX.
480		self.pos += 1;
481		let rest = std::str::from_utf8(&self.s[self.pos..]).ok()?;
482		let (out, consumed) = unescape(rest, Some(quote), bytes)?;
483		self.pos += consumed;
484		Some(out)
485	}
486}
487
488/// Processes Python string escapes in `s` up to the closing `quote` (or to the end
489/// of `s` if `quote` is `None`). Returns the text and the number of bytes consumed,
490/// including the closing quote.
491fn unescape(s: &str, quote: Option<char>, bytes: bool) -> Option<(String, usize)> {
492	let mut out = String::new();
493	let mut chars = s.char_indices().peekable();
494	while let Some((i, c)) = chars.next() {
495		if Some(c) == quote {
496			return Some((out, i + 1));
497		}
498		if c != '\\' {
499			if bytes && !c.is_ascii() {
500				return None;
501			}
502			out.push(c);
503			continue;
504		}
505		let (_, e) = chars.next()?;
506		match e {
507			'\n' => {} // line continuation
508			'\\' => out.push('\\'),
509			'\'' => out.push('\''),
510			'"' => out.push('"'),
511			'a' => out.push('\x07'),
512			'b' => out.push('\x08'),
513			'f' => out.push('\x0c'),
514			'v' => out.push('\x0b'),
515			'n' => out.push('\n'),
516			'r' => out.push('\r'),
517			't' => out.push('\t'),
518			'0'..='7' => {
519				let mut n = e.to_digit(8)?;
520				for _ in 0..2 {
521					match chars.peek() {
522						Some(&(_, d)) if d.is_digit(8) => {
523							n = n * 8 + d.to_digit(8)?;
524							chars.next();
525						}
526						_ => break,
527					}
528				}
529				out.push(char::from_u32(n)?);
530			}
531			'x' => {
532				let h: String = (0..2)
533					.filter_map(|_| chars.next().map(|(_, c)| c))
534					.collect();
535				if h.len() != 2 {
536					return None;
537				}
538				out.push(char::from_u32(u32::from_str_radix(&h, 16).ok()?)?);
539			}
540			'u' | 'U' if !bytes => {
541				let len = if e == 'u' { 4 } else { 8 };
542				let h: String = (0..len)
543					.filter_map(|_| chars.next().map(|(_, c)| c))
544					.collect();
545				if h.len() != len {
546					return None;
547				}
548				out.push(char::from_u32(u32::from_str_radix(&h, 16).ok()?)?);
549			}
550			other => {
551				out.push('\\');
552				out.push(other);
553			}
554		}
555	}
556	match quote {
557		None => Some((out, s.len())),
558		Some(_) => None,
559	}
560}
561
562/// The value of a Python string literal with the given body, as in
563/// `safeEval("'''" + body + "'''")`: escapes are processed, quotes are kept.
564pub fn parse_string_body(body: &str) -> Option<String> {
565	if body.contains("'''") {
566		return None;
567	}
568	unescape(body, None, false).map(|(s, _)| s)
569}
570
571#[cfg(test)]
572mod tests {
573	//! Port of Tests/misc/textTools_test.py (the parts that apply to a byte-array
574	//! tag) and the doctests in Lib/fontTools/misc/textTools.py.
575
576	use super::*;
577
578	#[test]
579	fn test_tag_comparison() {
580		assert_eq!(Tag::new(b"head"), "head");
581		assert_eq!(Tag::new(b"head"), *b"head");
582		assert_ne!(Tag::new(b"head"), "name");
583		assert_eq!(Tag::from_str_exact("h\u{e9}ad"), Some(Tag::new(b"h\xe9ad")));
584		assert_ne!(Tag::new(b"h\xe9ad"), "head");
585	}
586
587	#[test]
588	fn test_pad() {
589		assert_eq!(pad(b"abcd", 4).len(), 4);
590		assert_eq!(pad(b"abcde", 2).len(), 6);
591		assert_eq!(pad(b"abcde", 4).len(), 8);
592		assert_eq!(pad(b"abcdef", 4), b"abcdef\x00\x00");
593		assert_eq!(pad(b"abcdef", 1), b"abcdef");
594	}
595
596	#[test]
597	fn binary_strings() {
598		assert_eq!(num2binary(11, 16), "00000000 00001011");
599		assert_eq!(num2binary(-1, 4), "1111");
600		assert_eq!(binary2num("00000000 00001011"), 11);
601	}
602
603	#[test]
604	fn hex() {
605		assert_eq!(hex_str(b"\x01\xab"), "01ab");
606		assert_eq!(de_hex_str("01 ab\nc"), Some(vec![0x01, 0xab, 0xc0]));
607		assert_eq!(read_hex(["0001", "02"]), Some(vec![0, 1, 2]));
608	}
609
610	#[test]
611	fn literals() {
612		assert_eq!(safe_eval("12"), Some(Literal::Int(12)));
613		assert_eq!(safe_eval(" -0x1F"), Some(Literal::Int(-31)));
614		assert_eq!(safe_eval("1.5"), Some(Literal::Float(1.5)));
615		assert_eq!(safe_eval("1e-5"), Some(Literal::Float(1e-5)));
616		assert_eq!(safe_eval("True"), Some(Literal::Bool(true)));
617		assert_eq!(safe_eval("012"), None);
618		assert_eq!(safe_eval("00"), Some(Literal::Int(0)));
619		assert_eq!(safe_eval("'a\\x41'"), Some(Literal::Str("aA".into())));
620		assert_eq!(
621			safe_eval("(1, 2)"),
622			Some(Literal::Tuple(vec![Literal::Int(1), Literal::Int(2)]))
623		);
624		assert_eq!(
625			safe_eval("(1,)"),
626			Some(Literal::Tuple(vec![Literal::Int(1)]))
627		);
628		assert_eq!(safe_eval("(1)"), Some(Literal::Int(1)));
629		assert_eq!(safe_eval("[]"), Some(Literal::List(vec![])));
630		assert_eq!(safe_eval("foo"), None);
631		assert_eq!(parse_int_literal("0x00010000"), Some(0x10000));
632		assert_eq!(parse_int_literal("010"), None);
633		assert_eq!(parse_string_body(r"\x00A'B").as_deref(), Some("\0A'B"));
634	}
635
636	#[test]
637	fn caseless() {
638		assert_eq!(caseless_sort(&["b", "A", "a", "B"]), ["A", "a", "B", "b"]);
639	}
640}