Skip to main content

leptos_css/
number.rs

1use std::fmt;
2
3/// Error returned when a floating-point value cannot be represented by a typed CSS value.
4#[derive(Clone, Copy, Debug, PartialEq)]
5#[non_exhaustive]
6pub enum InvalidCssNumber {
7    /// The value is `NaN` or positive/negative infinity.
8    NonFinite {
9        /// The rejected value.
10        value: f64,
11        /// The CSS unit or channel being constructed.
12        context: &'static str,
13    },
14    /// The value is finite but outside the permitted inclusive range.
15    OutOfRange {
16        /// The rejected value.
17        value: f64,
18        /// The CSS unit or channel being constructed.
19        context: &'static str,
20        /// The inclusive lower bound.
21        min: f64,
22        /// The inclusive upper bound.
23        max: f64,
24    },
25    /// The value is finite but negative where CSS requires a non-negative number.
26    Negative {
27        /// The rejected value.
28        value: f64,
29        /// The CSS unit or channel being constructed.
30        context: &'static str,
31    },
32}
33
34impl fmt::Display for InvalidCssNumber {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        match self {
37            Self::NonFinite { value, context } => {
38                write!(f, "CSS {context} value must be finite, got {value}")
39            }
40            Self::OutOfRange {
41                value,
42                context,
43                min,
44                max,
45            } => write!(
46                f,
47                "CSS {context} must be in range [{min}, {max}], got {value}"
48            ),
49            Self::Negative { value, context } => {
50                write!(f, "CSS {context} must be non-negative, got {value}")
51            }
52        }
53    }
54}
55
56impl std::error::Error for InvalidCssNumber {}
57
58/// A finite IEEE-754 double used by typed CSS numeric values.
59///
60/// The private field makes `NaN` and positive/negative infinity unrepresentable through the
61/// public API. Use [`FiniteF64::try_new`] for runtime-derived values and [`FiniteF64::new`] for
62/// values whose validity is a programming invariant.
63#[repr(transparent)]
64#[derive(Clone, Copy, Debug, PartialEq)]
65pub struct FiniteF64(f64);
66
67pub(crate) const fn try_finite(
68    value: f64,
69    context: &'static str,
70) -> Result<FiniteF64, InvalidCssNumber> {
71    if value.is_finite() {
72        Ok(FiniteF64(value))
73    } else {
74        Err(InvalidCssNumber::NonFinite { value, context })
75    }
76}
77
78impl FiniteF64 {
79    /// Construct a finite value, panicking if `value` is `NaN` or infinite.
80    ///
81    /// # Panics
82    ///
83    /// Panics if `value` is not finite.
84    #[track_caller]
85    pub const fn new(value: f64) -> Self {
86        assert!(value.is_finite(), "CSS numeric value must be finite");
87        Self(value)
88    }
89
90    /// Attempt to construct a finite value.
91    ///
92    /// # Errors
93    ///
94    /// Returns [`InvalidCssNumber::NonFinite`] if `value` is `NaN` or infinite.
95    pub const fn try_new(value: f64) -> Result<Self, InvalidCssNumber> {
96        try_finite(value, "number")
97    }
98
99    /// Return the contained finite `f64`.
100    pub const fn get(self) -> f64 {
101        self.0
102    }
103}
104
105impl TryFrom<f64> for FiniteF64 {
106    type Error = InvalidCssNumber;
107
108    fn try_from(value: f64) -> Result<Self, Self::Error> {
109        Self::try_new(value)
110    }
111}
112
113impl From<FiniteF64> for f64 {
114    fn from(value: FiniteF64) -> Self {
115        value.get()
116    }
117}
118
119impl fmt::Display for FiniteF64 {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        self.0.fmt(f)
122    }
123}
124
125impl std::ops::Neg for FiniteF64 {
126    type Output = Self;
127
128    fn neg(self) -> Self::Output {
129        Self(-self.0)
130    }
131}
132
133/// A finite, non-negative number used by CSS grammars with a lower bound of zero.
134///
135/// The inner value is private, so negative and non-finite values cannot be represented.
136#[repr(transparent)]
137#[derive(Clone, Copy, Debug, PartialEq)]
138pub struct NonNegativeFiniteF64(FiniteF64);
139
140impl NonNegativeFiniteF64 {
141    /// Construct a non-negative finite number.
142    ///
143    /// # Panics
144    ///
145    /// Panics if `value` is negative, `NaN`, or infinite.
146    #[track_caller]
147    pub fn new(value: f64) -> Self {
148        Self::try_new(value).unwrap_or_else(|error| panic!("{error}"))
149    }
150
151    /// Attempt to construct a non-negative finite number.
152    pub fn try_new(value: f64) -> Result<Self, InvalidCssNumber> {
153        try_non_negative(value, "non-negative number").map(Self)
154    }
155
156    /// Return the contained number.
157    pub const fn get(self) -> f64 {
158        self.0.get()
159    }
160}
161
162impl fmt::Display for NonNegativeFiniteF64 {
163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164        self.0.fmt(f)
165    }
166}
167
168/// A finite number in the inclusive range `0..=1`.
169///
170/// This is the range used by alpha channels and normalized opacity values.
171#[repr(transparent)]
172#[derive(Clone, Copy, Debug, PartialEq)]
173pub struct UnitInterval(FiniteF64);
174
175impl UnitInterval {
176    /// Construct a value in the inclusive range `0..=1`.
177    ///
178    /// # Panics
179    ///
180    /// Panics if `value` is outside the range or is not finite.
181    #[track_caller]
182    pub fn new(value: f64) -> Self {
183        Self::try_new(value).unwrap_or_else(|error| panic!("{error}"))
184    }
185
186    /// Attempt to construct a value in the inclusive range `0..=1`.
187    pub fn try_new(value: f64) -> Result<Self, InvalidCssNumber> {
188        try_in_range(value, "unit interval", 0.0, 1.0).map(Self)
189    }
190
191    /// Return the contained number.
192    pub const fn get(self) -> f64 {
193        self.0.get()
194    }
195}
196
197impl fmt::Display for UnitInterval {
198    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199        self.0.fmt(f)
200    }
201}
202
203/// A finite percentage channel in the inclusive range `0..=100`.
204#[repr(transparent)]
205#[derive(Clone, Copy, Debug, PartialEq)]
206pub struct PercentageChannel(FiniteF64);
207
208impl PercentageChannel {
209    /// Construct a percentage channel in the inclusive range `0..=100`.
210    ///
211    /// # Panics
212    ///
213    /// Panics if `value` is outside the range or is not finite.
214    #[track_caller]
215    pub fn new(value: f64) -> Self {
216        Self::try_new(value).unwrap_or_else(|error| panic!("{error}"))
217    }
218
219    /// Attempt to construct a percentage channel in the inclusive range `0..=100`.
220    pub fn try_new(value: f64) -> Result<Self, InvalidCssNumber> {
221        try_in_range(value, "percentage channel", 0.0, 100.0).map(Self)
222    }
223
224    /// Return the contained percentage.
225    pub const fn get(self) -> f64 {
226        self.0.get()
227    }
228}
229
230impl fmt::Display for PercentageChannel {
231    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232        self.0.fmt(f)
233    }
234}
235
236#[inline]
237#[track_caller]
238pub(crate) fn assert_finite(v: f64, context: &'static str) -> FiniteF64 {
239    try_finite(v, context).unwrap_or_else(|error| panic!("{error}"))
240}
241
242#[inline]
243fn try_in_range(
244    v: f64,
245    context: &'static str,
246    min: f64,
247    max: f64,
248) -> Result<FiniteF64, InvalidCssNumber> {
249    let finite = try_finite(v, context)?;
250    if (min..=max).contains(&v) {
251        Ok(finite)
252    } else {
253        Err(InvalidCssNumber::OutOfRange {
254            value: v,
255            context,
256            min,
257            max,
258        })
259    }
260}
261
262#[inline]
263fn try_non_negative(v: f64, context: &'static str) -> Result<FiniteF64, InvalidCssNumber> {
264    let finite = try_finite(v, context)?;
265    if v >= 0.0 {
266        Ok(finite)
267    } else {
268        Err(InvalidCssNumber::Negative { value: v, context })
269    }
270}