Skip to main content

azul_css/props/basic/
error.rs

1//! C-compatible (`#[repr(C)]`) error types for CSS parsing failures.
2//!
3//! Mirrors `core::num::ParseFloatError` and `core::num::ParseIntError` for FFI use,
4//! and provides generic invalid-value error wrappers.
5
6use crate::corety::AzString;
7
8/// Simple "invalid value" error, used for basic parsing failures
9#[derive(Debug, Copy, Clone, Eq, PartialEq)]
10pub struct InvalidValueErr<'a>(pub &'a str);
11
12/// Owned version of `InvalidValueErr` with `AzString`.
13#[derive(Debug, Clone, PartialEq, Eq)]
14#[repr(C)]
15pub struct InvalidValueErrOwned {
16    pub value: AzString,
17}
18
19/// C-compatible enum mirroring `core::num::ParseFloatError` internals.
20///
21/// `core::num::ParseFloatError` is a 1-byte enum with variants `Empty` and `Invalid`,
22/// but its `kind` field is private. We mirror the variants here for FFI compatibility.
23#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
24#[repr(C)]
25pub enum ParseFloatError {
26    /// Input string was empty.
27    Empty,
28    /// Input string was not a valid float literal.
29    Invalid,
30}
31
32impl ParseFloatError {
33    /// Convert from `core::num::ParseFloatError` by comparing against known error instances.
34    fn from_std(e: &core::num::ParseFloatError) -> Self {
35        // Compare against the known Empty error instance to avoid
36        // relying on Display message wording or allocating a format string.
37        let empty_err = "".parse::<f32>().unwrap_err();
38        if *e == empty_err {
39            Self::Empty
40        } else {
41            Self::Invalid
42        }
43    }
44
45    /// Reconstruct a `core::num::ParseFloatError` from our C-compatible variant.
46    #[must_use] pub fn to_std(&self) -> core::num::ParseFloatError {
47        match self {
48            Self::Empty => "".parse::<f32>().unwrap_err(),
49            Self::Invalid => "x".parse::<f32>().unwrap_err(),
50        }
51    }
52}
53
54impl core::fmt::Display for ParseFloatError {
55    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
56        match self {
57            Self::Empty => write!(f, "cannot parse float from empty string"),
58            Self::Invalid => write!(f, "invalid float literal"),
59        }
60    }
61}
62
63impl From<core::num::ParseFloatError> for ParseFloatError {
64    fn from(e: core::num::ParseFloatError) -> Self {
65        Self::from_std(&e)
66    }
67}
68
69/// C-compatible enum mirroring `core::num::ParseIntError` internals.
70///
71/// `core::num::ParseIntError` is a 1-byte enum with variants matching `IntErrorKind`.
72/// We mirror them here for FFI compatibility.
73#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
74#[repr(C)]
75pub enum ParseIntError {
76    /// Input string was empty.
77    Empty,
78    /// Input contained an invalid digit.
79    InvalidDigit,
80    /// Input overflowed the target integer type (positive).
81    PosOverflow,
82    /// Input overflowed the target integer type (negative).
83    NegOverflow,
84    /// Input was zero but zero is not allowed (rarely used).
85    Zero,
86}
87
88impl ParseIntError {
89    /// Convert from `core::num::ParseIntError` using the stable `kind()` method.
90    const fn from_std(e: &core::num::ParseIntError) -> Self {
91        use core::num::IntErrorKind;
92        match e.kind() {
93            IntErrorKind::Empty => Self::Empty,
94            IntErrorKind::PosOverflow => Self::PosOverflow,
95            IntErrorKind::NegOverflow => Self::NegOverflow,
96            IntErrorKind::Zero => Self::Zero,
97            _ => Self::InvalidDigit, // future-proofing
98        }
99    }
100
101    /// Reconstruct a `core::num::ParseIntError` from our C-compatible variant.
102    #[must_use] pub fn to_std(&self) -> core::num::ParseIntError {
103        match self {
104            Self::Empty => "".parse::<i32>().unwrap_err(),
105            Self::InvalidDigit => "x".parse::<i32>().unwrap_err(),
106            Self::PosOverflow => "99999999999999999999".parse::<i32>().unwrap_err(),
107            Self::NegOverflow => "-99999999999999999999".parse::<i32>().unwrap_err(),
108            Self::Zero => {
109                // Zero variant cannot be reproduced on stable Rust; falls back to InvalidDigit.
110                // Note: round-tripping Zero through to_std() then from_std() yields InvalidDigit.
111                "x".parse::<i32>().unwrap_err()
112            }
113        }
114    }
115}
116
117impl core::fmt::Display for ParseIntError {
118    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
119        match self {
120            Self::Empty => write!(f, "cannot parse integer from empty string"),
121            Self::InvalidDigit => write!(f, "invalid digit found in string"),
122            Self::PosOverflow => write!(f, "number too large to fit in target type"),
123            Self::NegOverflow => write!(f, "number too small to fit in target type"),
124            Self::Zero => write!(f, "number would be zero for non-zero type"),
125        }
126    }
127}
128
129impl From<core::num::ParseIntError> for ParseIntError {
130    fn from(e: core::num::ParseIntError) -> Self {
131        Self::from_std(&e)
132    }
133}
134
135/// Wrapper for a `ParseFloatError` paired with the input string that failed.
136/// Used by multiple Owned error enums that need to store both the error and input.
137#[derive(Debug, Clone, PartialEq, Eq)]
138#[repr(C)]
139pub struct ParseFloatErrorWithInput {
140    pub error: ParseFloatError,
141    pub input: AzString,
142}
143
144/// Wrapper for `WrongNumberOfComponents` errors in CSS filter/transform parsing.
145#[derive(Debug, Clone, PartialEq, Eq)]
146#[repr(C)]
147pub struct WrongComponentCountError {
148    pub expected: usize,
149    pub got: usize,
150    pub input: AzString,
151}
152
153impl InvalidValueErr<'_> {
154    #[must_use] pub fn to_contained(&self) -> InvalidValueErrOwned {
155        InvalidValueErrOwned { value: self.0.to_string().into() }
156    }
157}
158
159impl InvalidValueErrOwned {
160    #[must_use] pub fn to_shared(&self) -> InvalidValueErr<'_> {
161        InvalidValueErr(self.value.as_str())
162    }
163}