Skip to main content

lumen_dioxus/inputs/
number_field_decimal.rs

1//! Exact decimal drafts for `NumberField`: parsing, bounds, and stepping without floating point.
2//!
3//! A port of `parseLumenDecimalDraft`, `isLumenDecimalInBounds`, and `stepLumenDecimalDraft`
4//! from `@santi020k/lumen-core/native-input`. Coefficients are digit strings instead of `BigInt`,
5//! so arithmetic stays exact far beyond `f64` precision.
6
7use std::cmp::Ordering;
8use std::fmt;
9
10use super::number_field_locale::{
11    LocaleSymbols, is_direction_mark, locale_symbols, numeric_digit, utf16_len_capped,
12};
13
14/// The longest draft (in UTF-16 code units, like JavaScript's `length`) that is parsed.
15const DRAFT_LIMIT: usize = 128;
16
17/// An exact, ungrouped decimal number: a coefficient and a scale (`coefficient / 10^scale`).
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct NumberFieldDecimal {
20    negative: bool,
21    /// Magnitude digits without leading zeros (`"0"` for zero).
22    digits: String,
23    scale: usize,
24}
25
26impl NumberFieldDecimal {
27    fn new(negative: bool, digits: &str, scale: usize) -> Self {
28        let trimmed = digits.trim_start_matches('0');
29        let digits = if trimmed.is_empty() { "0" } else { trimmed };
30
31        Self {
32            negative: negative && digits != "0",
33            digits: digits.to_string(),
34            scale,
35        }
36    }
37
38    fn zero() -> Self {
39        Self::new(false, "0", 0)
40    }
41
42    /// The signed integer coefficient as ASCII digits, such as `"-123"` for `-12.3`.
43    pub fn coefficient(&self) -> String {
44        if self.negative {
45            format!("-{}", self.digits)
46        } else {
47            self.digits.clone()
48        }
49    }
50
51    /// How many coefficient digits are fractional.
52    pub fn scale(&self) -> usize {
53        self.scale
54    }
55
56    /// Whether the number is below zero.
57    pub fn is_negative(&self) -> bool {
58        self.negative
59    }
60
61    /// The magnitude digits padded with zeros to `scale`.
62    fn digits_at(&self, scale: usize) -> String {
63        let mut digits = self.digits.clone();
64
65        if self.digits != "0" {
66            digits.extend(std::iter::repeat_n('0', scale.saturating_sub(self.scale)));
67        }
68
69        digits
70    }
71
72    /// Formats the number with a locale's digits, dropping trailing fraction zeros.
73    fn format(&self, symbols: &LocaleSymbols) -> String {
74        let digits = format!("{:0>width$}", self.digits, width = self.scale + 1);
75        let split = digits.len() - self.scale;
76        let (integer, fraction) = digits.split_at(split);
77        let fraction = fraction.trim_end_matches('0');
78        let mut out = String::new();
79
80        if self.negative {
81            out.push(symbols.minus);
82        }
83
84        out.push_str(&symbols.localize_digits(integer));
85
86        if !fraction.is_empty() {
87            out.push(symbols.decimal);
88            out.push_str(&symbols.localize_digits(fraction));
89        }
90
91        out
92    }
93}
94
95impl fmt::Display for NumberFieldDecimal {
96    /// The plain ASCII form, such as `-12.30`.
97    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
98        let digits = format!("{:0>width$}", self.digits, width = self.scale + 1);
99        let (integer, fraction) = digits.split_at(digits.len() - self.scale);
100        let sign = if self.negative { "-" } else { "" };
101
102        if fraction.is_empty() {
103            write!(formatter, "{sign}{integer}")
104        } else {
105            write!(formatter, "{sign}{integer}.{fraction}")
106        }
107    }
108}
109
110/// A parsed `NumberField` draft, like lumen-core's `LumenDecimalDraft`.
111#[derive(Clone, Debug, PartialEq, Eq)]
112#[non_exhaustive]
113pub enum NumberFieldDraft {
114    /// Nothing typed.
115    Empty,
116    /// A draft that can still become a number, such as `-`, `.`, or `12.`.
117    Incomplete,
118    /// Text that is not an ungrouped decimal in the locale.
119    Invalid,
120    /// A complete decimal.
121    Valid(NumberFieldDecimal),
122}
123
124/// Bounds, step, and locale for [`number_field_in_bounds`] and [`number_field_step_draft`], like
125/// lumen-core's `LumenDecimalOptions`.
126///
127/// `min`, `max`, and `step` are complete, ungrouped ASCII decimals such as `"0.25"`.
128#[derive(Clone, Debug, Default, PartialEq, Eq)]
129pub struct NumberFieldOptions {
130    /// Locale of the draft's digits and separators; `en-US` when unset.
131    pub locale: Option<String>,
132    /// Inclusive lower bound.
133    pub min: Option<String>,
134    /// Inclusive upper bound.
135    pub max: Option<String>,
136    /// Step size; `1` when unset. Must be positive.
137    pub step: Option<String>,
138}
139
140/// Why a [`NumberFieldOptions`] configuration was rejected (lumen-core throws a `RangeError`).
141#[derive(Clone, Copy, Debug, PartialEq, Eq)]
142#[non_exhaustive]
143pub enum NumberFieldError {
144    /// `min`, `max`, or `step` is not a complete ungrouped ASCII decimal of at most 128 characters.
145    InvalidConfiguration,
146    /// `step` is zero or negative.
147    NonPositiveStep,
148    /// `min` is greater than `max`.
149    MinAboveMax,
150}
151
152impl fmt::Display for NumberFieldError {
153    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
154        formatter.write_str(match self {
155            Self::InvalidConfiguration => {
156                "Decimal configuration must be a complete ungrouped ASCII decimal of at most 128 characters."
157            }
158            Self::NonPositiveStep => "Decimal step must be positive.",
159            Self::MinAboveMax => "Decimal minimum must not exceed maximum.",
160        })
161    }
162}
163
164impl std::error::Error for NumberFieldError {}
165
166/// Which way [`number_field_step_draft`] moves.
167#[derive(Clone, Copy, Debug, PartialEq, Eq)]
168pub enum NumberFieldStepDirection {
169    /// Add one step (`ArrowUp`).
170    Up,
171    /// Subtract one step (`ArrowDown`).
172    Down,
173}
174
175/// Decimal separator, minus sign, and digits of the ungrouped `Intl.NumberFormat` of a locale.
176fn decimal_symbols(locale: Option<&str>) -> LocaleSymbols {
177    locale_symbols(locale.unwrap_or("en-US"))
178}
179
180/// Parses a draft in a locale's digits and decimal separator. Grouping, exponents, white space,
181/// and drafts over 128 UTF-16 code units are invalid. Like `parseLumenDecimalDraft`.
182pub fn number_field_parse_draft(value: &str, locale: Option<&str>) -> NumberFieldDraft {
183    if value.is_empty() {
184        return NumberFieldDraft::Empty;
185    }
186
187    if utf16_len_capped(value, DRAFT_LIMIT) > DRAFT_LIMIT {
188        return NumberFieldDraft::Invalid;
189    }
190
191    let normalized: String = value.chars().filter(|c| !is_direction_mark(*c)).collect();
192
193    if normalized.is_empty() {
194        return NumberFieldDraft::Invalid;
195    }
196
197    let symbols = decimal_symbols(locale);
198    let (negative, unsigned) = match normalized.strip_prefix(symbols.minus) {
199        Some(rest) => (true, rest),
200        None => match normalized.strip_prefix('-') {
201            Some(rest) => (true, rest),
202            None => (false, normalized.as_str()),
203        },
204    };
205    let mut digits = String::new();
206    let mut decimal_seen = false;
207    let mut scale = 0;
208
209    for character in unsigned.chars() {
210        let digit = symbols
211            .localized_digit(character)
212            .or_else(|| numeric_digit(character));
213
214        if let Some(digit) = digit {
215            digits.push(char::from(b'0' + digit));
216
217            if decimal_seen {
218                scale += 1;
219            }
220        } else if character == symbols.decimal && !decimal_seen {
221            decimal_seen = true;
222        } else {
223            return NumberFieldDraft::Invalid;
224        }
225    }
226
227    if digits.is_empty() || unsigned.ends_with(symbols.decimal) {
228        return NumberFieldDraft::Incomplete;
229    }
230
231    NumberFieldDraft::Valid(NumberFieldDecimal::new(negative, &digits, scale))
232}
233
234fn parse_configuration(
235    value: Option<&str>,
236) -> Result<Option<NumberFieldDecimal>, NumberFieldError> {
237    let Some(value) = value else {
238        return Ok(None);
239    };
240
241    if !value
242        .chars()
243        .all(|character| character.is_ascii_digit() || character == '.' || character == '-')
244    {
245        return Err(NumberFieldError::InvalidConfiguration);
246    }
247
248    match number_field_parse_draft(value, Some("en-US")) {
249        NumberFieldDraft::Valid(decimal) => Ok(Some(decimal)),
250        _ => Err(NumberFieldError::InvalidConfiguration),
251    }
252}
253
254/// Compares two magnitudes given as ASCII digit strings without leading zeros.
255fn compare_magnitudes(left: &str, right: &str) -> Ordering {
256    left.len().cmp(&right.len()).then_with(|| left.cmp(right))
257}
258
259fn compare_decimals(left: &NumberFieldDecimal, right: &NumberFieldDecimal) -> Ordering {
260    match (left.negative, right.negative) {
261        (true, false) => Ordering::Less,
262        (false, true) => Ordering::Greater,
263        (negative, _) => {
264            let scale = left.scale.max(right.scale);
265            let magnitude = compare_magnitudes(
266                strip_zeros(&left.digits_at(scale)),
267                strip_zeros(&right.digits_at(scale)),
268            );
269
270            if negative {
271                magnitude.reverse()
272            } else {
273                magnitude
274            }
275        }
276    }
277}
278
279fn strip_zeros(digits: &str) -> &str {
280    let trimmed = digits.trim_start_matches('0');
281
282    if trimmed.is_empty() { "0" } else { trimmed }
283}
284
285/// Adds two magnitudes of ASCII digits.
286fn add_magnitudes(left: &str, right: &str) -> String {
287    let (left, right) = (left.as_bytes(), right.as_bytes());
288    let mut out = Vec::with_capacity(left.len().max(right.len()) + 1);
289    let mut carry = 0;
290    let (mut i, mut j) = (left.len(), right.len());
291
292    while i > 0 || j > 0 || carry > 0 {
293        let a = if i > 0 {
294            i -= 1;
295            left[i] - b'0'
296        } else {
297            0
298        };
299        let b = if j > 0 {
300            j -= 1;
301            right[j] - b'0'
302        } else {
303            0
304        };
305        let sum = a + b + carry;
306        out.push(b'0' + sum % 10);
307        carry = sum / 10;
308    }
309
310    out.reverse();
311    String::from_utf8(out).unwrap_or_default()
312}
313
314/// Subtracts the smaller magnitude `right` from `left` (`left >= right`).
315fn subtract_magnitudes(left: &str, right: &str) -> String {
316    let (left, right) = (left.as_bytes(), right.as_bytes());
317    let mut out = Vec::with_capacity(left.len());
318    let mut borrow = 0;
319    let (mut i, mut j) = (left.len(), right.len());
320
321    while i > 0 {
322        i -= 1;
323        let a = i16::from(left[i] - b'0');
324        let b = if j > 0 {
325            j -= 1;
326            i16::from(right[j] - b'0')
327        } else {
328            0
329        };
330        let mut difference = a - b - borrow;
331
332        if difference < 0 {
333            difference += 10;
334            borrow = 1;
335        } else {
336            borrow = 0;
337        }
338
339        out.push(b'0' + u8::try_from(difference).unwrap_or(0));
340    }
341
342    out.reverse();
343    String::from_utf8(out).unwrap_or_default()
344}
345
346/// `left + right` for signed decimals.
347fn add_decimals(left: &NumberFieldDecimal, right: &NumberFieldDecimal) -> NumberFieldDecimal {
348    let scale = left.scale.max(right.scale);
349    let a = left.digits_at(scale);
350    let b = right.digits_at(scale);
351    let (a, b) = (strip_zeros(&a), strip_zeros(&b));
352
353    if left.negative == right.negative {
354        return NumberFieldDecimal::new(left.negative, &add_magnitudes(a, b), scale);
355    }
356
357    match compare_magnitudes(a, b) {
358        Ordering::Less => {
359            NumberFieldDecimal::new(right.negative, &subtract_magnitudes(b, a), scale)
360        }
361        _ => NumberFieldDecimal::new(left.negative, &subtract_magnitudes(a, b), scale),
362    }
363}
364
365struct Configuration {
366    min: Option<NumberFieldDecimal>,
367    max: Option<NumberFieldDecimal>,
368    step: NumberFieldDecimal,
369}
370
371fn decimal_configuration(options: &NumberFieldOptions) -> Result<Configuration, NumberFieldError> {
372    let min = parse_configuration(options.min.as_deref())?;
373    let max = parse_configuration(options.max.as_deref())?;
374    let step = parse_configuration(Some(options.step.as_deref().unwrap_or("1")))?
375        .ok_or(NumberFieldError::InvalidConfiguration)?;
376
377    if step.negative || step.digits == "0" {
378        return Err(NumberFieldError::NonPositiveStep);
379    }
380
381    if let (Some(min), Some(max)) = (&min, &max)
382        && compare_decimals(min, max) == Ordering::Greater
383    {
384        return Err(NumberFieldError::MinAboveMax);
385    }
386
387    Ok(Configuration { min, max, step })
388}
389
390/// Whether a draft is a complete number inside the inclusive bounds, like
391/// `isLumenDecimalInBounds`.
392///
393/// # Errors
394///
395/// Returns a [`NumberFieldError`] when the bounds or step are not valid decimals.
396pub fn number_field_in_bounds(
397    value: &str,
398    options: &NumberFieldOptions,
399) -> Result<bool, NumberFieldError> {
400    let configuration = decimal_configuration(options)?;
401    let NumberFieldDraft::Valid(draft) = number_field_parse_draft(value, options.locale.as_deref())
402    else {
403        return Ok(false);
404    };
405
406    Ok(configuration
407        .min
408        .as_ref()
409        .is_none_or(|min| compare_decimals(&draft, min) != Ordering::Less)
410        && configuration
411            .max
412            .as_ref()
413            .is_none_or(|max| compare_decimals(&draft, max) != Ordering::Greater))
414}
415
416/// Adds or subtracts one step from a draft and clamps it to the inclusive bounds, like
417/// `stepLumenDecimalDraft`. An empty draft starts from `min`, a negative `max`, or zero.
418///
419/// Returns `Ok(None)` for incomplete or invalid drafts and for results longer than 128 UTF-16
420/// code units. The result uses the locale's digits and decimal separator, without trailing
421/// fraction zeros.
422///
423/// # Errors
424///
425/// Returns a [`NumberFieldError`] when the bounds or step are not valid decimals.
426pub fn number_field_step_draft(
427    value: &str,
428    direction: NumberFieldStepDirection,
429    options: &NumberFieldOptions,
430) -> Result<Option<String>, NumberFieldError> {
431    let Configuration { min, max, step } = decimal_configuration(options)?;
432    let start = match number_field_parse_draft(value, options.locale.as_deref()) {
433        NumberFieldDraft::Valid(draft) => draft,
434        NumberFieldDraft::Empty => match (&min, &max) {
435            (Some(min), _) => min.clone(),
436            (None, Some(max)) if max.negative => max.clone(),
437            _ => NumberFieldDecimal::zero(),
438        },
439        NumberFieldDraft::Incomplete | NumberFieldDraft::Invalid => return Ok(None),
440    };
441    let delta = NumberFieldDecimal {
442        negative: direction == NumberFieldStepDirection::Down,
443        ..step
444    };
445    let mut result = add_decimals(&start, &delta);
446
447    if let Some(min) = &min
448        && compare_decimals(&result, min) == Ordering::Less
449    {
450        result = min.clone();
451    }
452
453    if let Some(max) = &max
454        && compare_decimals(&result, max) == Ordering::Greater
455    {
456        result = max.clone();
457    }
458
459    let formatted = result.format(&decimal_symbols(options.locale.as_deref()));
460
461    Ok((utf16_len_capped(&formatted, DRAFT_LIMIT) <= DRAFT_LIMIT).then_some(formatted))
462}
463
464#[cfg(test)]
465mod tests {
466    use super::{NumberFieldDraft, add_decimals, compare_decimals, number_field_parse_draft};
467    use std::cmp::Ordering;
468
469    fn valid(value: &str) -> super::NumberFieldDecimal {
470        match number_field_parse_draft(value, None) {
471            NumberFieldDraft::Valid(decimal) => decimal,
472            other => panic!("{value} parsed as {other:?}"),
473        }
474    }
475
476    #[test]
477    fn arithmetic_is_exact_across_signs_and_scales() {
478        let sum = add_decimals(&valid("9007199254740993.1"), &valid("0.2"));
479        assert_eq!(sum.to_string(), "9007199254740993.3");
480        assert_eq!(
481            add_decimals(&valid("-0.1"), &valid("0.1")).to_string(),
482            "0.0"
483        );
484        assert_eq!(
485            add_decimals(&valid("1"), &valid("-2.5")).to_string(),
486            "-1.5"
487        );
488        assert_eq!(
489            add_decimals(&valid("-1"), &valid("-2.5")).to_string(),
490            "-3.5"
491        );
492        assert_eq!(
493            compare_decimals(&valid("-2"), &valid("-1.5")),
494            Ordering::Less
495        );
496        assert_eq!(
497            compare_decimals(&valid("10.00"), &valid("10")),
498            Ordering::Equal
499        );
500        assert_eq!(compare_decimals(&valid("-0"), &valid("0")), Ordering::Equal);
501    }
502}