adam_web_ui/components/number/
locale.rs1use crate::input::{InputError, NumberKind};
6use num_bigint::BigInt;
7use num_integer::Integer;
8
9pub 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
31pub 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
65pub fn decode_locale_reply(reply: &str) -> Result<NumberLocale, InputError> {
78 let locale = decode_reply(reply)?;
79 validate_locale(&locale)?;
80 Ok(locale)
81}
82
83pub 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
108fn 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
118fn transport_error(error: serde_json::Error) -> InputError {
122 InputError::Locale(error.to_string())
123}
124
125fn 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#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
152pub struct NumberLocale {
153 pub resolved: String,
155 pub digits: [String; 10],
157 pub decimal: String,
159 pub group: String,
161 pub minus: String,
163 pub plus: String,
165 pub ignorable: Vec<String>,
167 pub primary_group: usize,
169 pub secondary_group: usize,
171}
172
173#[derive(Clone, Debug, PartialEq, Eq)]
182pub enum NormalizedDraft {
183 Incomplete,
185 Complete(String),
187}
188
189pub 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 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
259pub 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
365pub(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
379fn decimal_step(current: &str, step: &str, increment: bool) -> String {
384 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
412fn 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
423fn 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
463fn is_group_space(token: &str) -> bool {
465 matches!(token, " " | "\u{a0}" | "\u{202f}")
466}
467
468fn 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
501fn 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
549fn 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
579fn lexical(text: &str) -> InputError {
583 InputError::Lexical(text.into())
584}
585
586fn range_error(text: &str, kind: NumberKind) -> InputError {
590 InputError::TypeRange {
591 kind,
592 value: text.into(),
593 }
594}
595
596fn 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}