Skip to main content

rspack_lightningcss/values/
number.rs

1//! CSS number values.
2
3use super::angle::impl_try_from_angle;
4use super::calc::Calc;
5use crate::error::{ParserError, PrinterError};
6use crate::traits::private::AddInternal;
7use crate::traits::{IsCompatible, Map, Op, Parse, ParseNumeric, Sign, ToCss, TrySign, Zero};
8#[cfg(feature = "visitor")]
9use crate::visitor::Visit;
10use cssparser::*;
11
12/// Describes what values are allowed when parsing a numeric value.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum NumericRange {
15  /// All values are allowed.
16  All,
17  /// Only values >= 0 are allowed.
18  NonNegative,
19}
20
21impl NumericRange {
22  /// Checks whether a value is allowed.
23  pub fn check(
24    &self,
25    value: f32,
26    location: SourceLocation,
27  ) -> Result<f32, ParseError<'static, ParserError<'static>>> {
28    match self {
29      NumericRange::All => Ok(value),
30      NumericRange::NonNegative if value >= 0.0 => Ok(value),
31      _ => Err(location.new_custom_error(ParserError::InvalidValue)),
32    }
33  }
34
35  /// Clamps the value to the valid range.
36  pub fn clamp(&self, value: f32) -> f32 {
37    match self {
38      NumericRange::All => value,
39      NumericRange::NonNegative => value.max(0.0),
40    }
41  }
42}
43
44/// A numeric value in a grammar position that only allows non-negative values.
45///
46/// Negative literals are rejected. Calculations are clamped when their result
47/// can be resolved, or preserved for the browser to clamp after resolution.
48/// This wrapper constrains parsing; its contents may still be modified directly.
49#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default)]
50#[cfg_attr(feature = "visitor", derive(Visit))]
51#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(transparent))]
52#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
53#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
54pub struct NonNegative<T>(pub T);
55
56impl<'i, T: ParseNumeric<'i>> Parse<'i> for NonNegative<T> {
57  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
58    T::parse_with_range(input, NumericRange::NonNegative).map(Self)
59  }
60}
61
62impl<T: ToCss> ToCss for NonNegative<T> {
63  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
64    self.0.to_css(dest)
65  }
66}
67
68impl<T: IsCompatible> IsCompatible for NonNegative<T> {
69  fn is_compatible(&self, browsers: crate::targets::Browsers) -> bool {
70    self.0.is_compatible(browsers)
71  }
72}
73
74impl<T: Zero> Zero for NonNegative<T> {
75  fn zero() -> Self {
76    Self(T::zero())
77  }
78
79  fn is_zero(&self) -> bool {
80    self.0.is_zero()
81  }
82}
83
84impl<T: TrySign> TrySign for NonNegative<T> {
85  fn try_sign(&self) -> Option<f32> {
86    self.0.try_sign()
87  }
88}
89
90/// A CSS [`<number>`](https://www.w3.org/TR/css-values-4/#numbers) value.
91///
92/// Numbers may be explicit or computed by `calc()`, but are always stored and serialized
93/// as their computed value.
94pub type CSSNumber = f32;
95
96impl<'i> Parse<'i> for CSSNumber {
97  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
98    Self::parse_with_range(input, NumericRange::All)
99  }
100}
101
102impl<'i> ParseNumeric<'i> for CSSNumber {
103  fn parse_with_range<'t>(
104    input: &mut Parser<'i, 't>,
105    range: NumericRange,
106  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
107    match input.try_parse(Calc::parse) {
108      Ok(Calc::Value(v)) => return Ok(range.clamp(*v)),
109      Ok(Calc::Number(n)) => return Ok(range.clamp(n)),
110      // Numbers are always compatible, so they will always compute to a value.
111      Ok(_) => return Err(input.new_custom_error(ParserError::InvalidValue)),
112      _ => {}
113    }
114
115    let location = input.current_source_location();
116    let number = input.expect_number()?;
117    range.check(number, location)
118  }
119}
120
121impl ToCss for CSSNumber {
122  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
123    let number = *self;
124    if number != 0.0 && number.abs() < 1.0 {
125      let mut s = String::new();
126      cssparser::ToCss::to_css(self, &mut s)?;
127      if number < 0.0 {
128        dest.write_char('-')?;
129        dest.write_str(s.trim_start_matches("-").trim_start_matches("0"))?;
130        Ok(())
131      } else {
132        dest.write_str(s.trim_start_matches('0'))?;
133        Ok(())
134      }
135    } else {
136      cssparser::ToCss::to_css(self, dest)?;
137      Ok(())
138    }
139  }
140}
141
142impl std::convert::Into<Calc<CSSNumber>> for CSSNumber {
143  fn into(self) -> Calc<CSSNumber> {
144    Calc::Value(Box::new(self))
145  }
146}
147
148impl std::convert::From<Calc<CSSNumber>> for CSSNumber {
149  fn from(calc: Calc<CSSNumber>) -> CSSNumber {
150    match calc {
151      Calc::Value(v) => *v,
152      Calc::Number(n) => n,
153      _ => unreachable!(),
154    }
155  }
156}
157
158impl AddInternal for CSSNumber {
159  fn add(self, other: Self) -> Self {
160    self + other
161  }
162}
163
164impl Op for CSSNumber {
165  fn op<F: FnOnce(f32, f32) -> f32>(&self, to: &Self, op: F) -> Self {
166    op(*self, *to)
167  }
168
169  fn op_to<T, F: FnOnce(f32, f32) -> T>(&self, rhs: &Self, op: F) -> T {
170    op(*self, *rhs)
171  }
172}
173
174impl Map for CSSNumber {
175  fn map<F: FnOnce(f32) -> f32>(&self, op: F) -> Self {
176    op(*self)
177  }
178}
179
180impl Sign for CSSNumber {
181  fn sign(&self) -> f32 {
182    if *self == 0.0 {
183      return if f32::is_sign_positive(*self) { 0.0 } else { -0.0 };
184    }
185    self.signum()
186  }
187}
188
189impl Zero for CSSNumber {
190  fn zero() -> Self {
191    0.0
192  }
193
194  fn is_zero(&self) -> bool {
195    *self == 0.0
196  }
197}
198
199impl_try_from_angle!(CSSNumber);
200
201/// A CSS [`<integer>`](https://www.w3.org/TR/css-values-4/#integers) value.
202pub type CSSInteger = i32;
203
204impl<'i> Parse<'i> for CSSInteger {
205  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
206    Self::parse_with_range(input, NumericRange::All)
207  }
208}
209
210impl<'i> ParseNumeric<'i> for CSSInteger {
211  fn parse_with_range<'t>(
212    input: &mut Parser<'i, 't>,
213    range: NumericRange,
214  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
215    // TODO: calc??
216    let location = input.current_source_location();
217    let integer = input.expect_integer()?;
218    range.check(integer as f32, location)?;
219    Ok(integer)
220  }
221}
222
223impl ToCss for CSSInteger {
224  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
225    cssparser::ToCss::to_css(self, dest)?;
226    Ok(())
227  }
228}
229
230impl Zero for CSSInteger {
231  fn zero() -> Self {
232    0
233  }
234
235  fn is_zero(&self) -> bool {
236    *self == 0
237  }
238}