Skip to main content

fontoxide_misc/
py.rs

1//! Python formatting semantics that fontTools' output depends on.
2//!
3//! TTX files contain values formatted with `str()` and `repr()` of Python objects.
4//! To produce byte-identical output, those conversions are reproduced here.
5
6use std::fmt::Write as _;
7
8/// `repr(float)` (equivalently `str(float)`) in Python 3: the shortest string that
9/// round-trips, with Python's choice between positional and exponent notation.
10///
11/// ```
12/// use fontoxide_misc::py::float_repr;
13/// assert_eq!(float_repr(1.0), "1.0");
14/// assert_eq!(float_repr(0.1), "0.1");
15/// assert_eq!(float_repr(1e16), "1e+16");
16/// assert_eq!(float_repr(1e-5), "1e-05");
17/// assert_eq!(float_repr(-0.0), "-0.0");
18/// // Exactly halfway between two shortest strings: half to even, like CPython.
19/// assert_eq!(float_repr(1.11112213134765625), "1.1111221313476562");
20/// ```
21pub fn float_repr(value: f64) -> String {
22	if value.is_nan() {
23		return "nan".into();
24	}
25	if value.is_infinite() {
26		return if value > 0.0 { "inf" } else { "-inf" }.into();
27	}
28	if value == 0.0 {
29		return if value.is_sign_negative() {
30			"-0.0"
31		} else {
32			"0.0"
33		}
34		.into();
35	}
36
37	// Rust's `{:e}` gives the shortest round-tripping digits, e.g. "-1.2345e-7".
38	let sci = format!("{:e}", value.abs());
39	let (mantissa, exponent) = sci.split_once('e').unwrap_or((&sci, "0"));
40	let exponent: i32 = exponent.parse().unwrap_or(0);
41	let mut digits: String = mantissa.chars().filter(|c| *c != '.').collect();
42	if digits.len() >= 16
43		&& let Some(even) = shortest_tie_to_even(value.abs(), &digits, exponent)
44	{
45		digits = even;
46	}
47	// Position of the decimal point relative to the digits: value = 0.DIGITS * 10^decpt.
48	let decpt = exponent + 1;
49
50	let mut out = String::new();
51	if value < 0.0 {
52		out.push('-');
53	}
54	if decpt <= -4 || decpt > 16 {
55		out.push_str(&digits[..1]);
56		if digits.len() > 1 {
57			out.push('.');
58			out.push_str(&digits[1..]);
59		}
60		let _ = write!(
61			out,
62			"e{}{:02}",
63			if exponent < 0 { '-' } else { '+' },
64			exponent.abs()
65		);
66	} else if decpt <= 0 {
67		out.push_str("0.");
68		out.extend(std::iter::repeat_n('0', (-decpt) as usize));
69		out.push_str(&digits);
70	} else {
71		let decpt = decpt as usize;
72		if digits.len() <= decpt {
73			out.push_str(&digits);
74			out.extend(std::iter::repeat_n('0', decpt - digits.len()));
75			out.push_str(".0");
76		} else {
77			out.push_str(&digits[..decpt]);
78			out.push('.');
79			out.push_str(&digits[decpt..]);
80		}
81	}
82	out
83}
84
85/// When the value lies exactly halfway between two shortest round-tripping
86/// digit strings, Rust's `{:e}` takes the upper one, while CPython's `repr`
87/// (`_Py_dg_dtoa` mode 0) rounds half to even: e.g. 1.11112213134765625 is
88/// `1.1111221313476562` in Python. Returns the even digits in that case.
89fn shortest_tie_to_even(value: f64, digits: &str, exponent: i32) -> Option<String> {
90	let n = digits.len();
91	let last = *digits.as_bytes().last()?;
92	// A tie needs an odd upper candidate whose even lower neighbor also
93	// round-trips; check that cheaply first.
94	if (last - b'0').is_multiple_of(2) {
95		return None;
96	}
97	let lower = format!("{}{}", &digits[..n - 1], (last - 1) as char);
98	let candidate = format!("{}.{}e{exponent}", &lower[..1], &lower[1..]);
99	if candidate.parse::<f64>().ok()? != value {
100		return None;
101	}
102	// Exact formatting: a double has at most 767 significant digits.
103	let exact = format!("{:.800e}", value);
104	let (mantissa, exp) = exact.split_once('e')?;
105	if exp.parse::<i32>().ok()? != exponent {
106		return None;
107	}
108	let exact_digits: String = mantissa.chars().filter(|c| *c != '.').collect();
109	let exact_digits = exact_digits.trim_end_matches('0');
110	if exact_digits.len() != n + 1 || !exact_digits.ends_with('5') {
111		return None;
112	}
113	(exact_digits[..n] == lower).then_some(lower)
114}
115
116/// Python's `round(x)` for floats: round half to even.
117pub fn round(value: f64) -> f64 {
118	value.round_ties_even()
119}
120
121/// Whether `str.isprintable()` holds for a single character.
122///
123/// Exact for Latin-1 (which covers everything fontTools passes through `repr()` in
124/// TTX output: tags and sfnt versions are decoded as Latin-1). Above U+00FF only the
125/// common non-printable classes are recognized.
126fn is_printable(c: char) -> bool {
127	let n = c as u32;
128	match n {
129		0x00..=0x1F | 0x7F..=0xA0 | 0xAD => false,
130		0x20..=0x7E | 0xA1..=0xFF => true,
131		// Separators other than U+0020, format characters and private use.
132		0x2000..=0x200F | 0x2028..=0x202F | 0x205F..=0x206F | 0x3000 | 0xFEFF => false,
133		0x1680 | 0x180E | 0xFFF9..=0xFFFB => false,
134		0xE000..=0xF8FF | 0xF0000.. => false,
135		_ => true,
136	}
137}
138
139/// `repr(str)` in Python 3, including the surrounding quotes.
140///
141/// ```
142/// use fontoxide_misc::py::str_repr;
143/// assert_eq!(str_repr("OTTO"), "'OTTO'");
144/// assert_eq!(str_repr("\0\x01\0\0"), r"'\x00\x01\x00\x00'");
145/// assert_eq!(str_repr("it's"), "\"it's\"");
146/// ```
147pub fn str_repr(s: &str) -> String {
148	let quote = if s.contains('\'') && !s.contains('"') {
149		'"'
150	} else {
151		'\''
152	};
153	let mut out = String::with_capacity(s.len() + 2);
154	out.push(quote);
155	for c in s.chars() {
156		match c {
157			'\\' => out.push_str("\\\\"),
158			'\t' => out.push_str("\\t"),
159			'\n' => out.push_str("\\n"),
160			'\r' => out.push_str("\\r"),
161			c if c == quote => {
162				out.push('\\');
163				out.push(c);
164			}
165			c if is_printable(c) => out.push(c),
166			c => {
167				let n = c as u32;
168				let _ = if n < 0x100 {
169					write!(out, "\\x{n:02x}")
170				} else if n < 0x10000 {
171					write!(out, "\\u{n:04x}")
172				} else {
173					write!(out, "\\U{n:08x}")
174				};
175			}
176		}
177	}
178	out.push(quote);
179	out
180}
181
182/// `repr(bytes)` in Python 3, including the `b` prefix and quotes.
183///
184/// ```
185/// use fontoxide_misc::py::bytes_repr;
186/// assert_eq!(bytes_repr(b"ab\x00\xff"), r"b'ab\x00\xff'");
187/// ```
188pub fn bytes_repr(data: &[u8]) -> String {
189	let quote = if data.contains(&b'\'') && !data.contains(&b'"') {
190		'"'
191	} else {
192		'\''
193	};
194	let mut out = String::with_capacity(data.len() + 3);
195	out.push('b');
196	out.push(quote);
197	for &b in data {
198		match b {
199			b'\\' => out.push_str("\\\\"),
200			b'\t' => out.push_str("\\t"),
201			b'\n' => out.push_str("\\n"),
202			b'\r' => out.push_str("\\r"),
203			b if b as char == quote => {
204				out.push('\\');
205				out.push(b as char);
206			}
207			0x20..=0x7E => out.push(b as char),
208			_ => {
209				let _ = write!(out, "\\x{b:02x}");
210			}
211		}
212	}
213	out.push(quote);
214	out
215}
216
217/// `str.isspace()` for a single character.
218pub fn is_space(c: char) -> bool {
219	matches!(
220		c,
221		'\t' | '\n'
222			| '\x0b' | '\x0c'
223			| '\r' | '\x1c'..='\x1f'
224			| ' ' | '\u{85}'
225			| '\u{a0}' | '\u{1680}'
226			| '\u{2000}'..='\u{200a}'
227			| '\u{2028}' | '\u{2029}'
228			| '\u{202f}' | '\u{205f}'
229			| '\u{3000}'
230	)
231}
232
233/// `str.strip()`: removes leading and trailing whitespace as Python defines it
234/// (which differs from [`str::trim`], e.g. for U+001C–U+001F).
235pub fn strip(s: &str) -> &str {
236	s.trim_matches(is_space)
237}
238
239/// Decodes bytes as Latin-1, as `bytes.decode("latin-1")` does.
240pub fn latin1_decode(data: &[u8]) -> String {
241	data.iter().map(|&b| b as char).collect()
242}
243
244/// `"%.{precision}G" % value`: `precision` significant digits, in positional
245/// notation unless the exponent is below -4 or not below `precision`, without
246/// trailing zeros.
247///
248/// ```
249/// use fontoxide_misc::py::format_g;
250/// assert_eq!(format_g(0.001, 8), "0.001");
251/// assert_eq!(format_g(123456789.0, 8), "1.2345679E+08");
252/// assert_eq!(format_g(1e-5, 8), "1E-05");
253/// assert_eq!(format_g(-2.5, 8), "-2.5");
254/// ```
255pub fn format_g(value: f64, precision: usize) -> String {
256	if value.is_nan() {
257		return "NAN".into();
258	}
259	if value.is_infinite() {
260		return if value > 0.0 { "INF" } else { "-INF" }.into();
261	}
262	let p = precision.max(1);
263	let e = format!("{:.*e}", p - 1, value);
264	let (mantissa, exponent) = e.split_once('e').unwrap_or((&e, "0"));
265	let exponent: i64 = exponent.parse().unwrap_or(0);
266	let strip = |s: &str| -> String {
267		if s.contains('.') {
268			s.trim_end_matches('0').trim_end_matches('.').to_owned()
269		} else {
270			s.to_owned()
271		}
272	};
273	if -4 <= exponent && exponent < p as i64 {
274		strip(&format!("{:.*}", (p as i64 - 1 - exponent) as usize, value))
275	} else {
276		let sign = if exponent < 0 { '-' } else { '+' };
277		format!("{}E{sign}{:02}", strip(mantissa), exponent.abs())
278	}
279}
280
281/// `"%g" % value` (`"%.{precision}g"`): like [`format_g`], in lower case.
282pub fn format_g_lower(value: f64, precision: usize) -> String {
283	format_g(value, precision).to_ascii_lowercase()
284}
285
286/// `round(value, ndigits)`: the float closest to the value rounded to
287/// `ndigits` decimal digits, ties to even on the exact binary value (CPython's
288/// `double_round` through `_Py_dg_dtoa`). NaNs and infinities pass through.
289///
290/// ```
291/// use fontoxide_misc::py::round_digits;
292/// assert_eq!(round_digits(2.675, 2), 2.67); // 2.675 is 2.67499999…
293/// assert_eq!(round_digits(0.125, 2), 0.12);
294/// assert!(round_digits(-1e-9, 6).is_sign_negative());
295/// ```
296pub fn round_digits(value: f64, ndigits: i32) -> f64 {
297	// `NDIGITS_MAX` and `NDIGITS_MIN` of CPython: past them, the value is
298	// already exact, or rounds to a zero of its sign.
299	if ndigits > 323 {
300		return value;
301	}
302	if ndigits < -308 {
303		return 0.0 * value;
304	}
305	if !value.is_finite() || value == 0.0 {
306		return value;
307	}
308	if ndigits >= 0 {
309		// Rust formats with the exact decimal expansion, rounded half to even.
310		let s = format!("{:.*}", ndigits as usize, value);
311		s.parse().unwrap_or(value)
312	} else {
313		let pow = 10f64.powi(-ndigits);
314		let y = value / pow;
315		let z = y.round_ties_even();
316		let r = z * pow;
317		if r == 0.0 { 0.0f64.copysign(value) } else { r }
318	}
319}
320
321/// `math.isclose(a, b)` with the default tolerances (`rel_tol=1e-09`,
322/// `abs_tol=0.0`).
323pub fn is_close(a: f64, b: f64) -> bool {
324	is_close_tol(a, b, 1e-9, 0.0)
325}
326
327/// `math.isclose(a, b, rel_tol=rel_tol, abs_tol=abs_tol)`.
328pub fn is_close_tol(a: f64, b: f64, rel_tol: f64, abs_tol: f64) -> bool {
329	if a == b {
330		return true;
331	}
332	if a.is_infinite() || b.is_infinite() {
333		return false;
334	}
335	let diff = (b - a).abs();
336	diff <= (rel_tol * b).abs() || diff <= (rel_tol * a).abs() || diff <= abs_tol
337}
338
339/// `math.hypot(*coordinates)`: CPython's `vector_norm`, which is more accurate
340/// than C's `hypot` (and differs from it, and from `f64::hypot`, in about one
341/// case out of six). `abs(complex)` uses C's `hypot` instead.
342///
343/// ```
344/// use fontoxide_misc::py::hypot;
345/// assert_eq!(hypot(&[3.0, 4.0]), 5.0);
346/// assert_eq!(hypot(&[-2.0]), 2.0);
347/// assert_eq!(hypot(&[]), 0.0);
348/// ```
349pub fn hypot(coordinates: &[f64]) -> f64 {
350	let mut found_nan = false;
351	let mut max = 0.0f64;
352	let mut vec: Vec<f64> = coordinates
353		.iter()
354		.map(|&x| {
355			let x = x.abs();
356			found_nan |= x.is_nan();
357			if x > max {
358				max = x;
359			}
360			x
361		})
362		.collect();
363	vector_norm(&mut vec, max, found_nan)
364}
365
366/// `dl_fast_sum`: error-free addition, with `|a| >= |b|`.
367fn dl_fast_sum(a: f64, b: f64) -> (f64, f64) {
368	let x = a + b;
369	let y = (a - x) + b;
370	(x, y)
371}
372
373/// `dl_mul`: error-free multiplication.
374fn dl_mul(x: f64, y: f64) -> (f64, f64) {
375	let z = x * y;
376	let zz = x.mul_add(y, -z);
377	(z, zz)
378}
379
380/// `vector_norm` of CPython's `mathmodule.c`.
381fn vector_norm(vec: &mut [f64], max: f64, found_nan: bool) -> f64 {
382	if max.is_infinite() {
383		return max;
384	}
385	if found_nan {
386		return f64::NAN;
387	}
388	if max == 0.0 || vec.len() <= 1 {
389		return max;
390	}
391	let max_e = frexp_exponent(max);
392	if max_e < -1023 {
393		// ldexp(1.0, -max_e) would overflow: subnormals become normals.
394		for v in vec.iter_mut() {
395			*v /= f64::MIN_POSITIVE;
396		}
397		return f64::MIN_POSITIVE * vector_norm(vec, max / f64::MIN_POSITIVE, found_nan);
398	}
399	let scale = 2f64.powi(-max_e);
400	let (mut csum, mut frac1, mut frac2) = (1.0f64, 0.0f64, 0.0f64);
401	for &v in vec.iter() {
402		// Lossless scaling and squaring, lossless and lossy additions.
403		let x = v * scale;
404		let (hi, lo) = dl_mul(x, x);
405		let (s, sl) = dl_fast_sum(csum, hi);
406		csum = s;
407		frac1 += lo;
408		frac2 += sl;
409	}
410	let mut h = (csum - 1.0 + (frac1 + frac2)).sqrt();
411	let (hi, lo) = dl_mul(-h, h);
412	let (s, sl) = dl_fast_sum(csum, hi);
413	csum = s;
414	frac1 += lo;
415	frac2 += sl;
416	let x = csum - 1.0 + (frac1 + frac2);
417	// Differential correction.
418	h += x / (2.0 * h);
419	h / scale
420}
421
422/// The exponent of C's `frexp`: `x == m * 2**e` with `0.5 <= |m| < 1`.
423fn frexp_exponent(x: f64) -> i32 {
424	let bits = x.to_bits();
425	let exp = ((bits >> 52) & 0x7ff) as i32;
426	if exp == 0 {
427		// A subnormal: normalize it first.
428		let m = x * 2f64.powi(54);
429		return frexp_exponent(m) - 54;
430	}
431	exp - 1022
432}
433
434/// `sum(values)` of floats in CPython 3.12+: Neumaier's compensated
435/// summation, starting with the integer 0.
436///
437/// ```
438/// use fontoxide_misc::py::sum_floats;
439/// assert_eq!(sum_floats([0.1; 10]), 1.0); // A plain loop gives 0.9999999999999999.
440/// assert_eq!(sum_floats([1e100, 1.0, -1e100]), 1.0);
441/// assert_eq!(sum_floats([]), 0.0);
442/// ```
443pub fn sum_floats(values: impl IntoIterator<Item = f64>) -> f64 {
444	let mut it = values.into_iter();
445	let Some(first) = it.next() else {
446		return 0.0;
447	};
448	// `0 + first`, then the float loop of `builtin_sum_impl`.
449	let mut f = 0.0 + first;
450	let mut c = 0.0;
451	for x in it {
452		let t = f + x;
453		if f.abs() >= x.abs() {
454			c += (f - t) + x;
455		} else {
456			c += (x - t) + f;
457		}
458		f = t;
459	}
460	// Adding the compensation must not lose the sign of a negative result,
461	// nor turn an infinite sum into a NaN.
462	if c != 0.0 && c.is_finite() {
463		f += c;
464	}
465	f
466}
467
468/// `list.sort()` of floats: a stable sort with `<`, so that equal values such
469/// as `-0.0` and `0.0` keep their order. NaNs compare as equal to everything.
470pub fn sort_floats(values: &mut [f64]) {
471	values.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
472}
473
474/// Encodes a string as Latin-1, as `str.encode("latin-1")` does. Returns `None` if
475/// a character is outside Latin-1.
476pub fn latin1_encode(s: &str) -> Option<Vec<u8>> {
477	s.chars().map(|c| u8::try_from(c as u32).ok()).collect()
478}
479
480/// Python's `float(str)`: accepts surrounding whitespace, underscores between
481/// digits, `inf`/`nan` spellings, and everything Rust's parser accepts.
482pub fn parse_float(s: &str) -> Option<f64> {
483	let t = s.trim();
484	if t.is_empty() {
485		return None;
486	}
487	let cleaned;
488	let t = if t.contains('_') {
489		cleaned = remove_digit_underscores(t)?;
490		cleaned.as_str()
491	} else {
492		t
493	};
494	let lower = t.to_ascii_lowercase();
495	let unsigned = lower.trim_start_matches(['+', '-']);
496	if matches!(unsigned, "inf" | "infinity" | "nan") {
497		let negative = lower.starts_with('-');
498		let v = if unsigned == "nan" {
499			f64::NAN
500		} else {
501			f64::INFINITY
502		};
503		return Some(if negative { -v } else { v });
504	}
505	t.parse().ok()
506}
507
508/// Python's `int(str)` (base 10): accepts surrounding whitespace, a sign and
509/// underscores between digits.
510pub fn parse_int(s: &str) -> Option<i128> {
511	let t = s.trim();
512	let cleaned;
513	let t = if t.contains('_') {
514		cleaned = remove_digit_underscores(t)?;
515		cleaned.as_str()
516	} else {
517		t
518	};
519	t.parse().ok()
520}
521
522fn remove_digit_underscores(s: &str) -> Option<String> {
523	let bytes = s.as_bytes();
524	for (i, &b) in bytes.iter().enumerate() {
525		if b == b'_' {
526			let before = i.checked_sub(1).map(|j| bytes[j]);
527			let after = bytes.get(i + 1);
528			if !before.is_some_and(|c| c.is_ascii_digit())
529				|| !after.is_some_and(|c| c.is_ascii_digit())
530			{
531				return None;
532			}
533		}
534	}
535	Some(s.replace('_', ""))
536}
537
538/// `hash(tuple)`, for a tuple of integers whose hash is the value itself: small
539/// integers other than -1.
540pub fn tuple_hash(items: &[i64]) -> i64 {
541	const XXPRIME_1: u64 = 11400714785074694791;
542	const XXPRIME_2: u64 = 14029467366897019727;
543	const XXPRIME_5: u64 = 2870177450012600261;
544	let mut acc = XXPRIME_5;
545	for &item in items {
546		acc = acc.wrapping_add((item as u64).wrapping_mul(XXPRIME_2));
547		acc = acc.rotate_left(31);
548		acc = acc.wrapping_mul(XXPRIME_1);
549	}
550	acc = acc.wrapping_add(items.len() as u64 ^ (XXPRIME_5 ^ 3527539));
551	if acc == u64::MAX {
552		return 1546275796;
553	}
554	acc as i64
555}
556
557/// The iteration order of a Python `set` to which the keys were added in the given
558/// order, each with its hash, without removals. Equal keys must have equal hashes.
559pub fn set_order<K: Copy + Eq>(keys: impl IntoIterator<Item = (K, i64)>) -> Vec<K> {
560	const LINEAR_PROBES: usize = 9;
561	const PERTURB_SHIFT: u32 = 5;
562	/// `set_insert_clean`.
563	fn insert_clean<K: Copy>(table: &mut [Option<(K, i64)>], key: K, hash: i64) {
564		let mask = table.len() - 1;
565		let mut perturb = hash as u64;
566		let mut i = hash as u64 as usize & mask;
567		loop {
568			if table[i].is_none() {
569				table[i] = Some((key, hash));
570				return;
571			}
572			if i + LINEAR_PROBES <= mask {
573				for j in 1..=LINEAR_PROBES {
574					if table[i + j].is_none() {
575						table[i + j] = Some((key, hash));
576						return;
577					}
578				}
579			}
580			perturb >>= PERTURB_SHIFT;
581			i = i
582				.wrapping_mul(5)
583				.wrapping_add(1)
584				.wrapping_add(perturb as usize)
585				& mask;
586		}
587	}
588	let mut table: Vec<Option<(K, i64)>> = vec![None; 8];
589	let mut used = 0;
590	'keys: for (key, hash) in keys {
591		let mask = table.len() - 1;
592		let mut perturb = hash as u64;
593		let mut i = hash as u64 as usize & mask;
594		// `set_add_entry`.
595		let slot = 'probe: loop {
596			let probes = if i + LINEAR_PROBES <= mask {
597				LINEAR_PROBES
598			} else {
599				0
600			};
601			for j in 0..=probes {
602				match &table[i + j] {
603					None => break 'probe i + j,
604					Some((k, h)) if *h == hash && *k == key => continue 'keys,
605					Some(_) => {}
606				}
607			}
608			perturb >>= PERTURB_SHIFT;
609			i = i
610				.wrapping_mul(5)
611				.wrapping_add(1)
612				.wrapping_add(perturb as usize)
613				& mask;
614		};
615		table[slot] = Some((key, hash));
616		used += 1;
617		if used * 5 >= mask * 3 {
618			// `set_table_resize`.
619			let min_used = if used > 50000 { used * 2 } else { used * 4 };
620			let mut size = 8;
621			while size <= min_used {
622				size <<= 1;
623			}
624			let mut new_table = vec![None; size];
625			for (k, h) in table.iter().flatten() {
626				insert_clean(&mut new_table, *k, *h);
627			}
628			table = new_table;
629		}
630	}
631	table.into_iter().flatten().map(|e| e.0).collect()
632}
633
634#[cfg(test)]
635mod tests {
636	use super::*;
637
638	/// The order of `set` in CPython 3.13 (`tools/reference`).
639	#[test]
640	fn set_order_of_int_tuples() {
641		type Case<'a> = (&'a [(i64, i64, i64)], &'a [(i64, i64, i64)]);
642		let cases: &[Case<'_>] = &[
643			(&[(3, 1, 1033), (1, 0, 0)], &[(3, 1, 1033), (1, 0, 0)]),
644			(
645				&[(1, 0, 0), (3, 1, 1033), (0, 3, 0), (3, 1, 1041)],
646				&[(1, 0, 0), (0, 3, 0), (3, 1, 1041), (3, 1, 1033)],
647			),
648			(
649				&[
650					(3, 1, 1033),
651					(3, 1, 1041),
652					(3, 1, 1042),
653					(3, 1, 2052),
654					(3, 1, 1028),
655					(1, 0, 0),
656					(1, 1, 11),
657					(0, 4, 0),
658					(3, 10, 1033),
659				],
660				&[
661					(3, 1, 1033),
662					(3, 1, 1042),
663					(3, 1, 1041),
664					(0, 4, 0),
665					(1, 0, 0),
666					(3, 1, 1028),
667					(1, 1, 11),
668					(3, 1, 2052),
669					(3, 10, 1033),
670				],
671			),
672			(
673				&[
674					(0, 9, 258),
675					(1, 1, 2029),
676					(1, 7, 1554),
677					(0, 1, 1998),
678					(0, 6, 1772),
679					(3, 0, 1824),
680				],
681				&[
682					(1, 7, 1554),
683					(3, 0, 1824),
684					(0, 6, 1772),
685					(0, 1, 1998),
686					(1, 1, 2029),
687					(0, 9, 258),
688				],
689			),
690			(
691				&[
692					(1, 11, 937),
693					(3, 1, 1300),
694					(0, 0, 104),
695					(3, 8, 37),
696					(1, 10, 887),
697					(1, 11, 118),
698					(3, 3, 1793),
699					(1, 8, 954),
700					(1, 3, 896),
701					(1, 4, 88),
702					(1, 8, 409),
703					(0, 10, 1214),
704					(0, 11, 1362),
705					(3, 11, 2051),
706				],
707				&[
708					(1, 4, 88),
709					(0, 11, 1362),
710					(3, 1, 1300),
711					(3, 11, 2051),
712					(0, 10, 1214),
713					(1, 10, 887),
714					(1, 8, 409),
715					(1, 8, 954),
716					(3, 3, 1793),
717					(1, 11, 118),
718					(1, 3, 896),
719					(3, 8, 37),
720					(1, 11, 937),
721					(0, 0, 104),
722				],
723			),
724			(
725				&[
726					(1, 8, 777),
727					(1, 4, 2045),
728					(3, 6, 141),
729					(1, 3, 1655),
730					(1, 10, 708),
731					(1, 8, 1534),
732					(0, 7, 2082),
733					(0, 2, 2133),
734					(1, 5, 2005),
735					(3, 0, 1922),
736					(0, 4, 1612),
737					(3, 2, 690),
738					(3, 3, 50),
739					(0, 8, 2245),
740					(0, 6, 2104),
741					(1, 9, 1447),
742					(1, 4, 2244),
743					(3, 11, 23),
744					(1, 11, 2099),
745					(0, 8, 2299),
746					(0, 6, 229),
747					(1, 5, 2270),
748					(0, 8, 1693),
749					(1, 5, 1697),
750					(1, 0, 2205),
751					(3, 9, 1356),
752					(1, 9, 114),
753					(0, 10, 725),
754					(3, 9, 740),
755					(0, 8, 1045),
756					(0, 10, 288),
757					(0, 0, 1855),
758					(0, 4, 1022),
759					(1, 1, 756),
760					(1, 4, 284),
761					(0, 2, 1045),
762					(3, 2, 1117),
763					(3, 11, 1206),
764					(1, 11, 1318),
765					(1, 7, 467),
766				],
767				&[
768					(0, 8, 2245),
769					(0, 6, 2104),
770					(1, 10, 708),
771					(0, 2, 1045),
772					(1, 8, 1534),
773					(1, 5, 1697),
774					(1, 5, 2005),
775					(1, 9, 114),
776					(0, 10, 725),
777					(1, 8, 777),
778					(0, 4, 1612),
779					(1, 4, 2244),
780					(1, 9, 1447),
781					(3, 0, 1922),
782					(0, 8, 2299),
783					(1, 5, 2270),
784					(0, 8, 1045),
785					(3, 6, 141),
786					(3, 2, 690),
787					(3, 2, 1117),
788					(1, 7, 467),
789					(3, 3, 50),
790					(0, 2, 2133),
791					(1, 1, 756),
792					(0, 10, 288),
793					(0, 0, 1855),
794					(1, 4, 2045),
795					(1, 11, 1318),
796					(0, 6, 229),
797					(1, 11, 2099),
798					(0, 4, 1022),
799					(3, 9, 740),
800					(1, 3, 1655),
801					(1, 4, 284),
802					(3, 11, 23),
803					(3, 9, 1356),
804					(0, 7, 2082),
805					(1, 0, 2205),
806					(0, 8, 1693),
807					(3, 11, 1206),
808				],
809			),
810			(
811				&[
812					(0, 4, 1583),
813					(1, 6, 770),
814					(1, 1, 1038),
815					(3, 8, 856),
816					(3, 6, 85),
817					(0, 0, 1627),
818					(0, 0, 656),
819					(1, 11, 2073),
820					(3, 6, 2231),
821					(0, 10, 2115),
822					(1, 3, 2145),
823					(3, 0, 1617),
824					(3, 9, 1315),
825					(3, 10, 1746),
826					(0, 11, 1223),
827					(0, 3, 194),
828					(1, 1, 313),
829					(1, 4, 648),
830					(1, 9, 1033),
831					(0, 0, 2296),
832					(0, 9, 891),
833					(3, 7, 702),
834					(3, 9, 2084),
835					(0, 6, 820),
836					(1, 1, 842),
837					(3, 10, 1773),
838					(3, 3, 2016),
839					(0, 10, 1597),
840					(1, 8, 2047),
841					(0, 5, 1647),
842					(1, 0, 642),
843					(0, 5, 553),
844					(1, 6, 872),
845					(1, 10, 394),
846					(1, 8, 1408),
847					(3, 8, 1984),
848					(3, 3, 267),
849					(3, 0, 346),
850					(0, 2, 682),
851					(3, 3, 1097),
852					(1, 9, 2072),
853					(1, 5, 1387),
854					(1, 1, 1192),
855					(0, 9, 2002),
856					(0, 9, 2257),
857					(0, 5, 160),
858					(1, 1, 1557),
859					(0, 2, 1396),
860					(0, 9, 1548),
861					(0, 9, 2253),
862					(0, 9, 334),
863					(1, 5, 1210),
864					(3, 8, 468),
865					(1, 4, 441),
866					(0, 4, 50),
867					(3, 10, 59),
868					(0, 6, 471),
869					(0, 3, 981),
870					(3, 6, 663),
871					(0, 7, 685),
872					(3, 3, 651),
873					(3, 1, 1782),
874					(1, 8, 1204),
875					(3, 4, 1953),
876					(1, 1, 850),
877					(3, 5, 162),
878					(0, 0, 1210),
879					(3, 9, 1311),
880					(1, 6, 1283),
881					(1, 1, 262),
882					(1, 9, 1867),
883					(0, 4, 881),
884					(3, 8, 1920),
885					(3, 5, 1061),
886					(0, 8, 851),
887					(1, 3, 1009),
888					(1, 1, 1150),
889					(0, 7, 370),
890					(3, 9, 1388),
891					(0, 6, 1256),
892					(0, 5, 765),
893					(1, 9, 1240),
894					(0, 5, 413),
895					(3, 9, 377),
896					(0, 3, 83),
897					(0, 6, 296),
898					(1, 8, 290),
899					(3, 1, 88),
900					(3, 0, 1191),
901					(1, 7, 1920),
902					(0, 1, 2053),
903					(1, 1, 2085),
904					(3, 2, 735),
905					(0, 2, 1309),
906					(1, 1, 2106),
907					(3, 4, 517),
908					(0, 2, 2234),
909					(3, 0, 1294),
910					(3, 10, 2264),
911					(3, 11, 841),
912					(0, 4, 1772),
913					(3, 2, 198),
914					(3, 10, 1012),
915					(1, 1, 1829),
916					(1, 8, 1024),
917					(3, 7, 2203),
918					(1, 0, 1620),
919					(1, 2, 1056),
920					(1, 0, 1706),
921					(3, 0, 255),
922					(3, 5, 566),
923					(3, 2, 567),
924					(1, 4, 1629),
925					(3, 6, 705),
926					(3, 1, 956),
927					(1, 0, 727),
928					(3, 5, 2051),
929					(3, 7, 924),
930					(0, 5, 2027),
931					(3, 7, 921),
932					(3, 6, 1380),
933					(3, 9, 1127),
934					(3, 3, 197),
935					(0, 8, 1510),
936					(0, 8, 834),
937					(1, 4, 1227),
938					(3, 5, 676),
939					(3, 11, 1903),
940					(3, 1, 504),
941					(3, 8, 1545),
942					(0, 2, 1026),
943					(1, 3, 213),
944					(1, 10, 1612),
945					(3, 10, 1425),
946					(1, 8, 675),
947					(3, 11, 166),
948					(3, 1, 1045),
949					(3, 1, 1095),
950					(3, 1, 569),
951					(3, 10, 335),
952					(1, 3, 1566),
953					(1, 6, 674),
954					(1, 7, 517),
955					(3, 7, 868),
956					(0, 6, 2187),
957					(1, 1, 1210),
958					(1, 3, 1551),
959					(3, 8, 16),
960					(0, 8, 1797),
961					(3, 0, 126),
962					(3, 9, 992),
963					(1, 3, 708),
964					(1, 2, 2221),
965					(0, 4, 1274),
966					(3, 4, 1828),
967					(0, 8, 1462),
968					(1, 6, 498),
969					(0, 9, 1569),
970					(0, 4, 442),
971					(0, 1, 54),
972					(3, 4, 559),
973					(0, 8, 1530),
974					(3, 4, 1790),
975					(3, 10, 1461),
976					(3, 5, 3),
977					(0, 7, 1841),
978					(1, 4, 2208),
979					(1, 5, 2016),
980					(0, 10, 1546),
981					(1, 3, 2281),
982					(0, 4, 2092),
983					(0, 7, 2117),
984					(1, 11, 1250),
985					(3, 2, 1840),
986					(3, 10, 2174),
987					(0, 5, 2155),
988					(0, 10, 1594),
989					(3, 6, 1659),
990					(1, 9, 277),
991					(1, 11, 1014),
992					(3, 10, 1191),
993					(3, 0, 1667),
994					(3, 10, 639),
995					(3, 6, 1106),
996					(0, 1, 41),
997					(1, 4, 1684),
998					(3, 8, 1243),
999					(0, 7, 1062),
1000					(1, 2, 1913),
1001					(3, 0, 1109),
1002					(3, 1, 1730),
1003					(0, 5, 274),
1004					(3, 7, 80),
1005					(0, 8, 662),
1006					(3, 1, 1646),
1007					(3, 11, 1129),
1008					(3, 4, 855),
1009					(3, 3, 971),
1010					(1, 4, 280),
1011					(0, 11, 2143),
1012				],
1013				&[
1014					(1, 9, 1033),
1015					(0, 2, 1396),
1016					(3, 4, 517),
1017					(1, 1, 1038),
1018					(1, 4, 280),
1019					(0, 9, 1548),
1020					(3, 9, 2084),
1021					(1, 6, 872),
1022					(0, 4, 50),
1023					(1, 11, 1014),
1024					(3, 0, 1617),
1025					(3, 1, 569),
1026					(3, 1, 1646),
1027					(3, 3, 267),
1028					(1, 1, 1150),
1029					(0, 1, 54),
1030					(0, 10, 1594),
1031					(3, 5, 676),
1032					(0, 7, 2117),
1033					(1, 6, 1283),
1034					(3, 6, 705),
1035					(3, 3, 651),
1036					(3, 9, 1311),
1037					(0, 11, 1223),
1038					(0, 3, 981),
1039					(0, 0, 656),
1040					(0, 2, 1309),
1041					(1, 3, 2281),
1042					(1, 5, 2016),
1043					(3, 2, 735),
1044					(3, 3, 971),
1045					(0, 10, 2115),
1046					(0, 6, 296),
1047					(0, 8, 1462),
1048					(1, 9, 1867),
1049					(1, 1, 850),
1050					(1, 8, 675),
1051					(1, 1, 313),
1052					(1, 10, 1612),
1053					(1, 5, 1387),
1054					(3, 1, 1730),
1055					(3, 0, 1109),
1056					(3, 4, 1790),
1057					(0, 8, 662),
1058					(3, 0, 1667),
1059					(3, 0, 346),
1060					(0, 8, 1510),
1061					(3, 10, 1461),
1062					(3, 0, 126),
1063					(0, 6, 1256),
1064					(1, 10, 394),
1065					(0, 2, 682),
1066					(0, 7, 370),
1067					(0, 9, 334),
1068					(1, 9, 1240),
1069					(1, 3, 708),
1070					(3, 0, 1294),
1071					(3, 8, 1545),
1072					(0, 10, 1546),
1073					(3, 7, 924),
1074					(3, 10, 2174),
1075					(1, 8, 1024),
1076					(3, 8, 1920),
1077					(0, 0, 1627),
1078					(3, 8, 1984),
1079					(0, 9, 2002),
1080					(3, 4, 855),
1081					(0, 2, 2234),
1082					(0, 8, 1530),
1083					(3, 8, 16),
1084					(1, 1, 262),
1085					(1, 8, 1408),
1086					(3, 10, 1191),
1087					(1, 9, 2072),
1088					(0, 9, 891),
1089					(1, 0, 1706),
1090					(0, 3, 194),
1091					(3, 5, 566),
1092					(3, 2, 567),
1093					(3, 1, 1782),
1094					(3, 6, 85),
1095					(0, 4, 1583),
1096					(0, 7, 685),
1097					(1, 3, 1551),
1098					(0, 4, 881),
1099					(1, 8, 290),
1100					(0, 5, 160),
1101					(0, 8, 851),
1102					(1, 7, 517),
1103					(3, 0, 1191),
1104					(3, 1, 88),
1105					(0, 11, 2143),
1106					(3, 7, 702),
1107					(0, 0, 2296),
1108					(0, 9, 2253),
1109					(0, 4, 1274),
1110					(0, 5, 553),
1111					(3, 5, 3),
1112					(3, 10, 1012),
1113					(1, 3, 2145),
1114					(1, 4, 2208),
1115					(0, 1, 2053),
1116					(3, 8, 1243),
1117					(3, 8, 468),
1118					(0, 7, 1062),
1119					(3, 11, 1129),
1120					(1, 8, 1204),
1121					(3, 6, 663),
1122					(3, 9, 1315),
1123					(0, 6, 471),
1124					(3, 3, 197),
1125					(3, 6, 2231),
1126					(1, 4, 441),
1127					(3, 9, 1388),
1128					(1, 0, 727),
1129					(3, 4, 1828),
1130					(3, 2, 1840),
1131					(3, 10, 59),
1132					(1, 3, 1009),
1133					(0, 5, 274),
1134					(3, 10, 1746),
1135					(1, 1, 1192),
1136					(3, 10, 1773),
1137					(3, 1, 504),
1138					(1, 6, 770),
1139					(0, 1, 41),
1140					(3, 11, 841),
1141					(1, 2, 1056),
1142					(1, 4, 1227),
1143					(1, 1, 1210),
1144					(1, 5, 1210),
1145					(1, 2, 1913),
1146					(0, 4, 442),
1147					(3, 6, 1659),
1148					(3, 5, 2051),
1149					(1, 9, 277),
1150					(0, 4, 1772),
1151					(1, 6, 498),
1152					(0, 8, 1797),
1153					(3, 9, 1127),
1154					(1, 4, 1684),
1155					(3, 7, 80),
1156					(1, 4, 1629),
1157					(0, 7, 1841),
1158					(1, 11, 1250),
1159					(0, 5, 2027),
1160					(0, 5, 413),
1161					(0, 4, 2092),
1162					(1, 8, 2047),
1163					(3, 7, 2203),
1164					(0, 0, 1210),
1165					(3, 10, 335),
1166					(0, 5, 2155),
1167					(1, 1, 2106),
1168					(3, 8, 856),
1169					(3, 3, 2016),
1170					(1, 7, 1920),
1171					(3, 6, 1106),
1172					(3, 9, 992),
1173					(1, 6, 674),
1174					(1, 11, 2073),
1175					(1, 0, 642),
1176					(3, 7, 921),
1177					(3, 6, 1380),
1178					(0, 9, 1569),
1179					(3, 3, 1097),
1180					(3, 1, 1045),
1181					(0, 2, 1026),
1182					(3, 5, 1061),
1183					(3, 4, 559),
1184					(1, 1, 842),
1185					(3, 10, 639),
1186					(3, 4, 1953),
1187					(1, 3, 213),
1188					(1, 4, 648),
1189					(0, 10, 1597),
1190					(0, 5, 1647),
1191					(3, 1, 956),
1192					(0, 8, 834),
1193					(3, 11, 1903),
1194					(3, 7, 868),
1195					(0, 5, 765),
1196					(3, 2, 198),
1197					(1, 0, 1620),
1198					(3, 10, 1425),
1199					(3, 10, 2264),
1200					(3, 9, 377),
1201					(3, 0, 255),
1202					(0, 9, 2257),
1203					(1, 1, 1829),
1204					(1, 2, 2221),
1205					(0, 6, 2187),
1206					(0, 6, 820),
1207					(0, 3, 83),
1208					(1, 1, 2085),
1209					(3, 11, 166),
1210					(3, 1, 1095),
1211					(3, 5, 162),
1212					(1, 3, 1566),
1213					(1, 1, 1557),
1214				],
1215			),
1216		];
1217		for (input, expected) in cases {
1218			let order = set_order(input.iter().map(|&k| (k, tuple_hash(&[k.0, k.1, k.2]))));
1219			assert_eq!(order.as_slice(), *expected);
1220		}
1221	}
1222
1223	#[test]
1224	fn float_repr_matches_python() {
1225		let cases = [
1226			(1.0, "1.0"),
1227			(-1.5, "-1.5"),
1228			(0.5, "0.5"),
1229			(100.0, "100.0"),
1230			(1234567890123456.0, "1234567890123456.0"),
1231			(1e16, "1e+16"),
1232			(1.5e16, "1.5e+16"),
1233			(0.0001, "0.0001"),
1234			(0.00012, "0.00012"),
1235			(0.00001, "1e-05"),
1236			(1.25e-7, "1.25e-07"),
1237			(1e100, "1e+100"),
1238			(0.1 + 0.2, "0.30000000000000004"),
1239			(0.61884, "0.61884"),
1240			(f64::MAX, "1.7976931348623157e+308"),
1241			(5e-324, "5e-324"),
1242			(f64::INFINITY, "inf"),
1243			(f64::NEG_INFINITY, "-inf"),
1244		];
1245		for (value, expected) in cases {
1246			assert_eq!(float_repr(value), expected, "{value:e}");
1247		}
1248		assert_eq!(float_repr(f64::NAN), "nan");
1249	}
1250
1251	#[test]
1252	fn str_repr_matches_python() {
1253		assert_eq!(str_repr("a\"b"), "'a\"b'");
1254		assert_eq!(str_repr("a'b\"c"), r#"'a\'b"c'"#);
1255		assert_eq!(str_repr("\u{7f}\u{a0}\u{a1}\u{ad}é"), r"'\x7f\xa0¡\xadé'");
1256		assert_eq!(str_repr("tab\there"), r"'tab\there'");
1257	}
1258
1259	#[test]
1260	fn parse_numbers() {
1261		assert_eq!(parse_float(" 1.5 "), Some(1.5));
1262		assert_eq!(parse_float("1_000.5"), Some(1000.5));
1263		assert_eq!(parse_float("1__0"), None);
1264		assert_eq!(parse_float("-Infinity"), Some(f64::NEG_INFINITY));
1265		assert_eq!(parse_int("-12"), Some(-12));
1266		assert_eq!(parse_int("+1_2"), Some(12));
1267		assert_eq!(parse_int("1.0"), None);
1268	}
1269}