Skip to main content

adam_web_ui/
input.rs

1//! Model-independent numeric types and editor diagnostics.
2//!
3//! Use [`NumberKind::range`] for exact primitive endpoints.
4
5/// Distinguishes input syntax, concrete range, editor support, and locale failures.
6///
7/// # Examples
8/// ```
9/// use adam_web_ui::input::InputError;
10/// assert!(matches!(InputError::Lexical("bad input".into()), InputError::Lexical(_)));
11/// ```
12#[derive(Clone, Debug, PartialEq, Eq)]
13pub enum InputError {
14    /// Reports malformed numeric syntax.
15    Lexical(String),
16    /// Reports a value outside its concrete primitive range.
17    TypeRange {
18        /// Identifies the target primitive.
19        kind: NumberKind,
20        /// Preserves the rejected canonical text.
21        value: String,
22    },
23    /// Reports an unsupported editor or primitive width.
24    UnsupportedEditor(String),
25    /// Reports locale resolution, symbol, serialization, or transport failure.
26    Locale(String),
27    /// Reports native event capture, composition range support, or channel failure.
28    ///
29    /// # Examples
30    /// ```
31    /// use adam_web_ui::input::InputError;
32    /// let error = InputError::EventSource("Native selection is unavailable".into());
33    /// assert!(matches!(error, InputError::EventSource(_)));
34    /// ```
35    EventSource(String),
36}
37
38/// Identifies a concrete primitive without erasing its integer width.
39///
40/// Only Rust primitive widths 8, 16, 32, 64, and 128 are supported.
41///
42/// # Examples
43/// ```
44/// use adam_web_ui::input::NumberKind;
45/// assert_eq!(NumberKind::Unsigned(8).range().unwrap().max, "255");
46/// ```
47#[derive(Clone, Copy, Debug, PartialEq, Eq)]
48pub enum NumberKind {
49    /// Identifies a signed integer by bit width.
50    Signed(u32),
51    /// Identifies an unsigned integer by bit width.
52    Unsigned(u32),
53    /// Identifies an IEEE 754 single-precision float.
54    F32,
55    /// Identifies an IEEE 754 double-precision float.
56    F64,
57}
58
59/// Carries exact canonical primitive endpoints, excluding nonfinite floats.
60///
61/// # Examples
62/// ```
63/// use adam_web_ui::input::NumberKind;
64/// assert_eq!(NumberKind::Signed(8).range().unwrap().min, "-128");
65/// ```
66#[derive(Clone, Debug, PartialEq, Eq)]
67pub struct NumericRange {
68    /// Contains the inclusive minimum.
69    pub min: String,
70    /// Contains the inclusive maximum.
71    pub max: String,
72}
73
74impl NumberKind {
75    /// Returns exact finite bounds for a Rust numeric primitive.
76    ///
77    /// # Errors
78    /// Returns `UnsupportedEditor` for nonprimitive integer widths.
79    ///
80    /// # Examples
81    /// ```
82    /// use adam_web_ui::input::NumberKind;
83    /// assert_eq!(NumberKind::Unsigned(8).range().unwrap().max, "255");
84    /// ```
85    pub fn range(self) -> Result<NumericRange, InputError> {
86        self.validate()?;
87        let (min, max) = match self {
88            Self::Signed(128) => (i128::MIN.to_string(), i128::MAX.to_string()),
89            Self::Signed(bits) => {
90                let magnitude = 1_i128 << (bits - 1);
91                (
92                    magnitude.checked_neg().unwrap().to_string(),
93                    magnitude.checked_sub(1).unwrap().to_string(),
94                )
95            }
96            Self::Unsigned(128) => ("0".into(), u128::MAX.to_string()),
97            Self::Unsigned(bits) => ("0".into(), ((1_u128 << bits) - 1).to_string()),
98            Self::F32 => (f32::MIN.to_string(), f32::MAX.to_string()),
99            Self::F64 => (f64::MIN.to_string(), f64::MAX.to_string()),
100        };
101        Ok(NumericRange { min, max })
102    }
103
104    /// Rejects widths that do not identify a Rust primitive.
105    ///
106    /// # Errors
107    /// Returns `UnsupportedEditor` for nonprimitive integer widths.
108    pub(crate) fn validate(self) -> Result<(), InputError> {
109        match self {
110            Self::Signed(8 | 16 | 32 | 64 | 128)
111            | Self::Unsigned(8 | 16 | 32 | 64 | 128)
112            | Self::F32
113            | Self::F64 => Ok(()),
114            _ => Err(InputError::UnsupportedEditor(format!(
115                "unsupported numeric kind: {self:?}"
116            ))),
117        }
118    }
119}
120
121impl std::fmt::Display for InputError {
122    /// Writes a model-independent diagnostic.
123    ///
124    /// - Complexity: O(diagnostic bytes) time.
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        match self {
127            Self::Lexical(message) => write!(f, "Invalid numeric input: {message}"),
128            Self::TypeRange { kind, value } => {
129                write!(f, "{value} is outside the finite range of {kind:?}")
130            }
131            Self::UnsupportedEditor(message) => write!(f, "Unsupported editor: {message}"),
132            Self::Locale(message) => write!(f, "Numeric locale error: {message}"),
133            Self::EventSource(message) => write!(f, "Numeric event source error: {message}"),
134        }
135    }
136}
137
138impl std::error::Error for InputError {}