Skip to main content

adam_web_ui/components/number/
locale.rs

1//! Numeric normalization and checked stepping.
2//!
3//! Pass a resolved [`NumberLocale`] to [`normalize_draft`], then submit only
4//! [`NormalizedDraft::Complete`] values.
5use crate::input::{InputError, NumberKind};
6use num_bigint::BigInt;
7use num_integer::Integer;
8
9/// Builds an eval script that sends a resolved locale or explicit locale failure.
10///
11/// Every dynamic argument is JSON-encoded; `None` requests the host default.
12/// The script sends a serde-compatible `Result` object through `dioxus.send`.
13///
14/// - Complexity: O(locale bytes) time and space, plus fixed helper source.
15///
16/// # Errors
17/// Returns `Locale` if argument serialization fails.
18///
19/// # Examples
20/// ```
21/// use adam_web_ui::components::number::number_locale_script;
22/// let script = number_locale_script(Some("de-DE")).unwrap();
23/// ```
24pub fn number_locale_script(locale: Option<&str>) -> Result<String, InputError> {
25    let argument = serde_json::to_string(&locale).map_err(transport_error)?;
26    Ok(eval_script(&format!(
27        "numberLocale({argument} ?? undefined)"
28    )))
29}
30
31/// Builds an eval script that formats concretely validated canonical text.
32///
33/// Every dynamic argument is JSON-encoded. The script sends a serde-compatible
34/// `Result<String, String>` through `dioxus.send`; JavaScript never handles
35/// instance/revision integers. Capture those in Rust for [`decode_format_reply`].
36///
37/// - Complexity: O(canonical + locale + options bytes) time and space.
38///
39/// # Errors
40/// Returns the numeric validation error or `Locale` for serialization failure.
41///
42/// # Examples
43/// ```
44/// use adam_web_ui::{components::number::format_number_script, input::NumberKind};
45/// let script = format_number_script("255", NumberKind::Unsigned(8), "en-US",
46///     &serde_json::json!({})).unwrap();
47/// ```
48pub fn format_number_script(
49    canonical: &str,
50    kind: NumberKind,
51    locale: &str,
52    options: &serde_json::Value,
53) -> Result<String, InputError> {
54    kind.validate()?;
55    if !complete_syntax(canonical, kind)? {
56        return Err(lexical(canonical));
57    }
58    validate_number(canonical, kind)?;
59    let integer = matches!(kind, NumberKind::Signed(_) | NumberKind::Unsigned(_));
60    let arguments =
61        serde_json::to_string(&(canonical, integer, locale, options)).map_err(transport_error)?;
62    Ok(eval_script(&format!("formatNumber(...{arguments})")))
63}
64
65/// Decodes and validates a locale script reply without substituting defaults.
66///
67/// - Complexity: O(reply bytes) time and space.
68///
69/// # Errors
70/// Returns `Locale` for failed resolution, malformed transport, or invalid symbols.
71///
72/// # Examples
73/// ```
74/// use adam_web_ui::components::number::decode_locale_reply;
75/// assert!(decode_locale_reply(r#"{"Err":"unsupported locale"}"#).is_err());
76/// ```
77pub fn decode_locale_reply(reply: &str) -> Result<NumberLocale, InputError> {
78    let locale = decode_reply(reply)?;
79    validate_locale(&locale)?;
80    Ok(locale)
81}
82
83/// Decodes a formatter reply with its Rust-captured instance/revision stamp.
84///
85/// - Complexity: O(reply bytes) time and space.
86///
87/// # Errors
88/// Returns `Locale` for formatting failures or malformed transport.
89///
90/// # Examples
91/// ```
92/// use adam_web_ui::components::number::{decode_format_reply, DraftEvent};
93/// assert_eq!(decode_format_reply(r#"{"Ok":"1,234"}"#, 2, 3).unwrap(),
94///     DraftEvent::Formatted { text: "1,234".into(), generation: 2, revision: 3 });
95/// ```
96pub fn decode_format_reply(
97    reply: &str,
98    generation: u64,
99    revision: u64,
100) -> Result<super::DraftEvent, InputError> {
101    Ok(super::DraftEvent::Formatted {
102        text: decode_reply(reply)?,
103        generation,
104        revision,
105    })
106}
107
108/// Wraps a JSON-encoded expression in the locale helper and an explicit result envelope.
109///
110/// - Complexity: O(expression bytes) time and space, plus fixed helper source.
111fn eval_script(expression: &str) -> String {
112    let helpers = include_str!("locale.js").replace("export function", "function");
113    format!(
114        "{helpers}\ntry {{ dioxus.send({{Ok: {expression}}}); }} catch (error) {{ dioxus.send({{Err: String(error)}}); }}"
115    )
116}
117
118/// Converts serde transport/serialization errors into model-independent locale diagnostics.
119///
120/// - Complexity: O(diagnostic bytes) time and space.
121fn transport_error(error: serde_json::Error) -> InputError {
122    InputError::Locale(error.to_string())
123}
124
125/// Decodes the helper's result envelope without hiding failures behind defaults.
126///
127/// - Complexity: O(reply bytes) time and space.
128fn decode_reply<T: serde::de::DeserializeOwned>(reply: &str) -> Result<T, InputError> {
129    serde_json::from_str::<Result<T, String>>(reply)
130        .map_err(transport_error)?
131        .map_err(InputError::Locale)
132}
133
134/// Owns the token vocabulary of one resolved decimal locale.
135///
136/// Digit tokens are ordered zero through nine. Group sizes count digits from
137/// the right; the secondary size repeats to the left of the primary group.
138/// Nonempty symbols have at most 16 bytes and no prefix ambiguities. Only
139/// Arabic letter mark and left/right direction marks are ignorable. Normalization
140/// validates these constraints and reports `InputError::Locale` on failure.
141///
142/// # Examples
143/// ```
144/// use adam_web_ui::components::number::NumberLocale;
145/// let locale: NumberLocale = serde_json::from_str(r#"{
146/// "resolved":"en-US","digits":["0","1","2","3","4","5","6","7","8","9"],
147/// "decimal":".","group":",","minus":"-","plus":"+","ignorable":[],
148/// "primary_group":3,"secondary_group":3}"#).unwrap();
149/// assert_eq!(locale.resolved, "en-US");
150/// ```
151#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
152pub struct NumberLocale {
153    /// Contains the Intl-resolved locale identifier.
154    pub resolved: String,
155    /// Contains the localized digits in numeric order.
156    pub digits: [String; 10],
157    /// Separates the fraction from the integer.
158    pub decimal: String,
159    /// Separates integer digit groups.
160    pub group: String,
161    /// Contains the localized negative sign.
162    pub minus: String,
163    /// Contains the localized positive sign.
164    pub plus: String,
165    /// Contains ignorable bidi formatting marks.
166    pub ignorable: Vec<String>,
167    /// Counts digits in the rightmost integer group.
168    pub primary_group: usize,
169    /// Counts digits in subsequent integer groups.
170    pub secondary_group: usize,
171}
172
173/// Distinguishes a numeric prefix from a complete, representable canonical draft.
174///
175/// # Examples
176/// ```
177/// use adam_web_ui::components::number::NormalizedDraft;
178/// let complete = NormalizedDraft::Complete("18446744073709551615".into());
179/// assert_ne!(complete, NormalizedDraft::Incomplete);
180/// ```
181#[derive(Clone, Debug, PartialEq, Eq)]
182pub enum NormalizedDraft {
183    /// Retains an empty, sign, decimal, or exponent prefix without a write.
184    Incomplete,
185    /// Carries ASCII decimal syntax validated against the concrete primitive.
186    Complete(String),
187}
188
189/// Normalizes locale tokens without coercing integer values through floats.
190///
191/// Empty input, lone signs/decimal separators, and exponent prefixes remain
192/// incomplete. Grouping is accepted only in the mantissa's integer part, with
193/// the locale's primary/secondary group widths. Space-grouping locales accept
194/// ordinary, nonbreaking, and narrow nonbreaking spaces interchangeably.
195/// Complete integer input uses decimal integer syntax; incomplete prefixes
196/// remain local even when their eventual spelling would require a float.
197///
198/// - Complexity: O(raw bytes + locale token bytes) time and space.
199///
200/// # Errors
201/// Returns `Lexical` for malformed syntax/grouping, `TypeRange` for overflow,
202/// nonfinite conversion, or nonzero values rounded to zero, `UnsupportedEditor`
203/// for unknown widths, and `Locale` for ambiguous or malformed vocabularies.
204///
205/// # Examples
206/// ```
207/// use adam_web_ui::{components::number::*, input::NumberKind};
208/// fn incomplete_prefix(locale: &NumberLocale) {
209///     assert_eq!(normalize_draft("-", locale, NumberKind::F64),
210///         Ok(NormalizedDraft::Incomplete));
211/// }
212/// ```
213pub fn normalize_draft(
214    raw: &str,
215    locale: &NumberLocale,
216    kind: NumberKind,
217) -> Result<NormalizedDraft, InputError> {
218    kind.validate()?;
219    validate_locale(locale)?;
220    let tokens = locale_tokens(locale);
221    let mut rest = raw;
222    let mut ascii = String::with_capacity(raw.len());
223    // Translate a fixed vocabulary while consuming each source token exactly once.
224    while !rest.is_empty() {
225        if let Some(mark) = locale
226            .ignorable
227            .iter()
228            .find(|mark| rest.starts_with(mark.as_str()))
229        {
230            rest = &rest[mark.len()..];
231            continue;
232        }
233        if let Some((token, value)) = tokens
234            .iter()
235            .find(|(token, _)| !token.is_empty() && rest.starts_with(token))
236        {
237            ascii.push(*value);
238            rest = &rest[token.len()..];
239            continue;
240        }
241        let ch = rest.chars().next().unwrap();
242        if is_group_space(&locale.group) && matches!(ch, ' ' | '\u{a0}' | '\u{202f}') {
243            ascii.push(',');
244        } else if ch.is_ascii_digit() || matches!(ch, '+' | '-' | 'e' | 'E') {
245            ascii.push(ch);
246        } else {
247            return Err(lexical(raw));
248        }
249        rest = &rest[ch.len_utf8()..];
250    }
251    remove_grouping(&mut ascii, locale)?;
252    if !complete_syntax(&ascii, kind)? {
253        return Ok(NormalizedDraft::Incomplete);
254    }
255    validate_number(&ascii, kind)?;
256    Ok(NormalizedDraft::Complete(ascii))
257}
258
259/// Steps canonical text to the next zero-anchored multiple without clamping.
260///
261/// A step must be positive and representable by the bound primitive. An aligned
262/// value advances by one step. Floating-point inputs use their shortest decimal
263/// representations, independently of localized display formatting.
264///
265/// - Complexity: O(current bytes + step bytes) time and space.
266///
267/// # Errors
268/// Returns `Lexical` for malformed canonical text or nonpositive steps,
269/// `TypeRange` for nonfinite values, overflow, or an unrepresentable transition,
270/// and `UnsupportedEditor` for unknown widths.
271///
272/// # Examples
273/// ```
274/// use adam_web_ui::{components::number::step_number, input::NumberKind};
275/// assert_eq!(step_number("255", NumberKind::Unsigned(16), "1", true).unwrap(), "256");
276/// ```
277pub fn step_number(
278    current: &str,
279    kind: NumberKind,
280    step: &str,
281    increment: bool,
282) -> Result<String, InputError> {
283    kind.validate()?;
284    for text in [current, step] {
285        validate_canonical_number(text, kind)?;
286    }
287    let result = match kind {
288        NumberKind::Signed(_) => {
289            let value = current
290                .parse::<i128>()
291                .map_err(|_| range_error(current, kind))?;
292            let step = step.parse::<i128>().map_err(|_| range_error(step, kind))?;
293            if step <= 0 {
294                return Err(lexical("step must be positive"));
295            }
296            let remainder = value.rem_euclid(step);
297            if increment {
298                value.checked_add(step - remainder)
299            } else {
300                value.checked_sub(if remainder == 0 { step } else { remainder })
301            }
302            .ok_or_else(|| range_error(current, kind))?
303            .to_string()
304        }
305        NumberKind::Unsigned(_) => {
306            let value = current
307                .parse::<u128>()
308                .map_err(|_| range_error(current, kind))?;
309            let step = step.parse::<u128>().map_err(|_| range_error(step, kind))?;
310            if step == 0 {
311                return Err(lexical("step must be positive"));
312            }
313            let remainder = value % step;
314            if increment {
315                value.checked_add(step - remainder)
316            } else {
317                value.checked_sub(if remainder == 0 { step } else { remainder })
318            }
319            .ok_or_else(|| range_error(current, kind))?
320            .to_string()
321        }
322        NumberKind::F32 => {
323            let value = current
324                .parse::<f32>()
325                .map_err(|_| range_error(current, kind))?;
326            let step = step.parse::<f32>().map_err(|_| range_error(step, kind))?;
327            if step <= 0.0 {
328                return Err(lexical("step must be positive"));
329            }
330            let result = decimal_step(&value.to_string(), &step.to_string(), increment)
331                .parse::<f32>()
332                .map_err(|_| range_error(current, kind))?;
333            if !result.is_finite()
334                || (increment && result <= value)
335                || (!increment && result >= value)
336            {
337                return Err(range_error(current, kind));
338            }
339            result.to_string()
340        }
341        NumberKind::F64 => {
342            let value = current
343                .parse::<f64>()
344                .map_err(|_| range_error(current, kind))?;
345            let step = step.parse::<f64>().map_err(|_| range_error(step, kind))?;
346            if step <= 0.0 {
347                return Err(lexical("step must be positive"));
348            }
349            let result = decimal_step(&value.to_string(), &step.to_string(), increment)
350                .parse::<f64>()
351                .map_err(|_| range_error(current, kind))?;
352            if !result.is_finite()
353                || (increment && result <= value)
354                || (!increment && result >= value)
355            {
356                return Err(range_error(current, kind));
357            }
358            result.to_string()
359        }
360    };
361    validate_number(&result, kind)?;
362    Ok(result)
363}
364
365/// Validates canonical numeric text against its concrete primitive.
366///
367/// - Complexity: O(text bytes) time and O(1) additional space.
368///
369/// # Errors
370/// Returns lexical, concrete-range, or unsupported-kind errors.
371pub(crate) fn validate_canonical_number(text: &str, kind: NumberKind) -> Result<(), InputError> {
372    kind.validate()?;
373    if !complete_syntax(text, kind)? {
374        return Err(lexical(text));
375    }
376    validate_number(text, kind)
377}
378
379/// Computes the next decimal multiple using normalized finite float strings.
380///
381/// - Precondition: `current` and positive `step` are finite float display strings.
382/// - Complexity: Arbitrary-precision division in the number of decimal digits.
383fn decimal_step(current: &str, step: &str, increment: bool) -> String {
384    /// Returns the integer coefficient and scale of a finite float display string.
385    fn coefficient(text: &str) -> (BigInt, u32) {
386        let (whole, fraction) = text.split_once('.').unwrap_or((text, ""));
387        let digits = format!("{whole}{fraction}");
388        let scale = u32::try_from(fraction.len()).expect("finite float scale fits u32");
389        (
390            digits.parse().expect("finite float has decimal digits"),
391            scale,
392        )
393    }
394
395    let (value, value_scale) = coefficient(current);
396    let (step, step_scale) = coefficient(step);
397    let scale = value_scale.max(step_scale);
398    let ten = BigInt::from(10);
399    let value = value * ten.pow(scale - value_scale);
400    let step = step * ten.pow(scale - step_scale);
401    let (quotient, remainder) = value.div_mod_floor(&step);
402    let next = if increment {
403        quotient + 1
404    } else if remainder == BigInt::from(0) {
405        quotient - 1
406    } else {
407        quotient
408    };
409    format!("{}e-{scale}", next * step)
410}
411
412/// Returns fixed-size token mappings; an empty grouping token is unused.
413fn locale_tokens(locale: &NumberLocale) -> [(&str, char); 14] {
414    std::array::from_fn(|i| match i {
415        0..=9 => (locale.digits[i].as_str(), char::from(b'0' + i as u8)),
416        10 => (locale.decimal.as_str(), '.'),
417        11 => (locale.group.as_str(), ','),
418        12 => (locale.minus.as_str(), '-'),
419        _ => (locale.plus.as_str(), '+'),
420    })
421}
422
423/// Rejects empty/ambiguous symbols and unsupported ignorable tokens.
424///
425/// Symbol tokens have at most 16 bytes; only the three numeric bidi marks are
426/// ignorable. This bounds vocabulary lookup independently of draft length.
427/// - Complexity: O(locale token bytes) time, O(1) additional space.
428fn validate_locale(locale: &NumberLocale) -> Result<(), InputError> {
429    let tokens = locale_tokens(locale);
430    if locale.resolved.is_empty()
431        || locale.primary_group == 0
432        || locale.secondary_group == 0
433        || locale.ignorable.len() > 3
434        || locale
435            .ignorable
436            .iter()
437            .any(|s| !matches!(s.as_str(), "\u{61c}" | "\u{200e}" | "\u{200f}"))
438    {
439        return Err(InputError::Locale("invalid locale metadata".into()));
440    }
441    for (i, (token, value)) in tokens.iter().enumerate() {
442        if i == 11 && token.is_empty() {
443            continue;
444        }
445        if token.is_empty()
446            || token.len() > 16
447            || token
448                .chars()
449                .any(|c| matches!(c, 'e' | 'E' | '\u{61c}' | '\u{200e}' | '\u{200f}'))
450            || token.chars().any(|c| {
451                (c.is_ascii_digit() || matches!(c, '+' | '-')) && (token.len() != 1 || c != *value)
452            })
453            || tokens[..i].iter().any(|(other, _)| {
454                !other.is_empty() && (token.starts_with(other) || other.starts_with(token))
455            })
456        {
457            return Err(InputError::Locale("ambiguous numeric symbols".into()));
458        }
459    }
460    Ok(())
461}
462
463/// Identifies the interchangeable space grouping tokens.
464fn is_group_space(token: &str) -> bool {
465    matches!(token, " " | "\u{a0}" | "\u{202f}")
466}
467
468/// Validates integer grouping before removing its separators.
469///
470/// - Complexity: O(text bytes) time and O(1) additional space.
471fn remove_grouping(text: &mut String, locale: &NumberLocale) -> Result<(), InputError> {
472    if !text.contains(',') {
473        return Ok(());
474    }
475    let unsigned = text.strip_prefix(['+', '-']).unwrap_or(text);
476    let end = unsigned.find(['.', 'e', 'E']).unwrap_or(unsigned.len());
477    let integer = &unsigned[..end];
478    if unsigned[end..].contains(',') {
479        return Err(lexical(text));
480    }
481    let mut groups = integer.rsplit(',');
482    let last = groups.next().unwrap();
483    if last.len() != locale.primary_group || !last.bytes().all(|b| b.is_ascii_digit()) {
484        return Err(lexical(text));
485    }
486    let mut groups = groups.peekable();
487    while let Some(group) = groups.next() {
488        let valid_width = if groups.peek().is_none() {
489            !group.is_empty() && group.len() <= locale.secondary_group
490        } else {
491            group.len() == locale.secondary_group
492        };
493        if !valid_width || !group.bytes().all(|b| b.is_ascii_digit()) {
494            return Err(lexical(text));
495        }
496    }
497    text.retain(|c| c != ',');
498    Ok(())
499}
500
501/// Recognizes decimal syntax and its incomplete prefixes from ASCII text.
502///
503/// - Complexity: O(text bytes) time and O(1) additional space.
504fn complete_syntax(text: &str, kind: NumberKind) -> Result<bool, InputError> {
505    let bytes = text.as_bytes();
506    let mut index = usize::from(bytes.first().is_some_and(|b| matches!(b, b'+' | b'-')));
507    let start = index;
508    while bytes.get(index).is_some_and(u8::is_ascii_digit) {
509        index += 1;
510    }
511    let mut digits = index - start;
512    if bytes.get(index) == Some(&b'.') {
513        index += 1;
514        let start = index;
515        while bytes.get(index).is_some_and(u8::is_ascii_digit) {
516            index += 1;
517        }
518        digits += index - start;
519    }
520    if digits == 0 {
521        return if index == bytes.len() {
522            Ok(false)
523        } else {
524            Err(lexical(text))
525        };
526    }
527    if bytes.get(index).is_some_and(|b| matches!(b, b'e' | b'E')) {
528        index += 1;
529        if bytes.get(index).is_some_and(|b| matches!(b, b'+' | b'-')) {
530            index += 1;
531        }
532        let start = index;
533        while bytes.get(index).is_some_and(u8::is_ascii_digit) {
534            index += 1;
535        }
536        if index == start && index == bytes.len() {
537            return Ok(false);
538        }
539    }
540    if index != bytes.len()
541        || (matches!(kind, NumberKind::Signed(_) | NumberKind::Unsigned(_))
542            && text.contains(['.', 'e', 'E']))
543    {
544        return Err(lexical(text));
545    }
546    Ok(true)
547}
548
549/// Checks exact integer bounds and concrete finite float conversion.
550///
551/// - Precondition: `kind` has a supported primitive width.
552/// - Complexity: O(text bytes) time and O(1) additional space.
553fn validate_number(text: &str, kind: NumberKind) -> Result<(), InputError> {
554    debug_assert!(kind.validate().is_ok());
555    let valid = match kind {
556        NumberKind::Signed(bits) => text.parse::<i128>().is_ok_and(|value| {
557            bits == 128 || {
558                let magnitude = 1_i128 << (bits - 1);
559                value >= magnitude.checked_neg().unwrap() && value < magnitude
560            }
561        }),
562        NumberKind::Unsigned(bits) => text
563            .parse::<u128>()
564            .is_ok_and(|value| bits == 128 || value < (1_u128 << bits)),
565        NumberKind::F32 => text
566            .parse::<f32>()
567            .is_ok_and(|value| value.is_finite() && (value != 0.0 || zero_mantissa(text))),
568        NumberKind::F64 => text
569            .parse::<f64>()
570            .is_ok_and(|value| value.is_finite() && (value != 0.0 || zero_mantissa(text))),
571    };
572    if valid {
573        Ok(())
574    } else {
575        Err(range_error(text, kind))
576    }
577}
578
579/// Creates an owned lexical diagnostic.
580///
581/// - Complexity: O(text bytes) time and space.
582fn lexical(text: &str) -> InputError {
583    InputError::Lexical(text.into())
584}
585
586/// Preserves the rejected text in a concrete-range diagnostic.
587///
588/// - Complexity: O(text bytes) time and space.
589fn range_error(text: &str, kind: NumberKind) -> InputError {
590    InputError::TypeRange {
591        kind,
592        value: text.into(),
593    }
594}
595
596/// Checks whether the decimal mantissa contains no nonzero digit.
597///
598/// - Complexity: O(text bytes) time and O(1) additional space.
599fn zero_mantissa(text: &str) -> bool {
600    !text
601        .bytes()
602        .take_while(|b| !matches!(b, b'e' | b'E'))
603        .any(|b| matches!(b, b'1'..=b'9'))
604}