malachite_base/chars/scripts.rs
1// Copyright © 2026 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::num::conversion::traits::{ExactFrom, WrappingFrom};
10use core::fmt::{Formatter, Result, Write};
11
12// The ten Unicode subscript digits, in order, so that a digit's value is its position.
13//
14// They are contiguous in Unicode, but writing them out keeps the conversion from needing a fallible
15// `char::from_u32`, and shows at a glance which characters are meant.
16const SUBSCRIPT_DIGITS: [char; 10] = ['₀', '₁', '₂', '₃', '₄', '₅', '₆', '₇', '₈', '₉'];
17
18/// Writes a number as a run of Unicode subscript digits.
19///
20/// The digits are the Subscripts block's `₀` through `₉`, so that 10 is written `₁₀`. There
21/// is no sign and no leading zero: zero is written `₀`, and nothing else begins with it.
22///
23/// # Worst-case complexity
24/// $T(n) = O(n)$
25///
26/// $M(n) = O(1)$
27///
28/// where $T$ is time, $M$ is additional memory, and $n$ is `n.significant_bits()`.
29///
30/// # Examples
31/// ```
32/// use malachite_base::chars::scripts::fmt_subscript_digits;
33/// use std::fmt::{Display, Formatter, Result};
34///
35/// struct Indexed(u64);
36///
37/// impl Display for Indexed {
38/// fn fmt(&self, f: &mut Formatter) -> Result {
39/// f.write_str("x")?;
40/// fmt_subscript_digits(self.0, f)
41/// }
42/// }
43///
44/// assert_eq!(Indexed(0).to_string(), "x₀");
45/// assert_eq!(Indexed(10).to_string(), "x₁₀");
46/// ```
47pub fn fmt_subscript_digits(n: u64, f: &mut Formatter) -> Result {
48 // The digits come out least-significant first, so they are buffered rather than written as they
49 // are found. Twenty is how many a `u64` can have.
50 let mut digits = [0u8; 20];
51 let mut len = 0;
52 let mut n = n;
53 loop {
54 digits[len] = u8::wrapping_from(n % 10);
55 len += 1;
56 n /= 10;
57 if n == 0 {
58 break;
59 }
60 }
61 for &d in digits[..len].iter().rev() {
62 f.write_char(SUBSCRIPT_DIGITS[usize::from(d)])?;
63 }
64 Ok(())
65}
66
67/// Reads a number written as a run of Unicode subscript digits.
68///
69/// This accepts exactly what [`fmt_subscript_digits`] writes, and nothing else: the empty string, a
70/// string holding anything but a subscript digit, a string with a leading zero, and a number too
71/// large for a [`u64`] are all rejected. Accepting only the one spelling of a number is what makes
72/// the two functions inverse to each other.
73///
74/// # Worst-case complexity
75/// $T(n) = O(n)$
76///
77/// $M(n) = O(1)$
78///
79/// where $T$ is time, $M$ is additional memory, and $n$ is `s.len()`.
80///
81/// # Examples
82/// ```
83/// use malachite_base::chars::scripts::parse_subscript_digits;
84///
85/// assert_eq!(parse_subscript_digits("₀"), Some(0));
86/// assert_eq!(parse_subscript_digits("₁₀"), Some(10));
87/// assert_eq!(parse_subscript_digits(""), None);
88/// assert_eq!(parse_subscript_digits("10"), None);
89/// assert_eq!(parse_subscript_digits("₀₁"), None);
90/// ```
91pub fn parse_subscript_digits(s: &str) -> Option<u64> {
92 let mut n: u64 = 0;
93 let mut len = 0;
94 for c in s.chars() {
95 let d = SUBSCRIPT_DIGITS.iter().position(|&x| x == c)?;
96 if len == 1 && n == 0 {
97 // A leading zero, which nothing this reads back is written with.
98 return None;
99 }
100 n = n.checked_mul(10)?.checked_add(u64::exact_from(d))?;
101 len += 1;
102 }
103 if len == 0 { None } else { Some(n) }
104}