1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
// This file is part of css. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/css/master/COPYRIGHT. No part of predicator, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2017 The developers of css. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/css/master/COPYRIGHT.

use {
    super::{CssNumber, CssNumberNewType},
    crate::{
        domain::{
            expressions::{
                CalcExpression,
                CalculablePropertyValue::{self, *},
                FunctionParser,
            },
            units::{
                conversions::*,
                AppUnitsPer,
                PercentageUnit,
                Unit,
                UnitFromStrError,
            },
        },
        parsers::ParserContext,
        CustomParseError,
    },
    cssparser::{ParseError, Parser, ParserInput, ToCss, Token},
    either::{Either, Left},
    std::{
        cmp::Ordering,
        fmt::{self, Display, Formatter, LowerExp, UpperExp},
        hash::{Hash, Hasher},
        ops::*,
        str::FromStr,
    },
};

/// A CSS float value similar to f32 but with a more restricted range
#[derive(Debug, Copy, Clone)]
pub struct CssSignedNumber(f32);

impl PartialEq for CssSignedNumber {
    #[inline(always)]
    fn eq(&self, other: &Self) -> bool {
        self.to_f32().eq(&other.0)
    }
}

impl Eq for CssSignedNumber {}

impl PartialOrd for CssSignedNumber {
    #[inline(always)]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.to_f32().partial_cmp(&other.0)
    }
}

impl Ord for CssSignedNumber {
    #[inline(always)]
    fn cmp(&self, other: &Self) -> Ordering {
        self.partial_cmp(other).unwrap_or(Ordering::Equal)
    }
}

impl Hash for CssSignedNumber {
    #[inline(always)]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.to_bits().hash(state)
    }
}

impl ToCss for CssSignedNumber {
    #[inline(always)]
    fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
        self.to_f32().to_css(dest)
    }
}

impl Display for CssSignedNumber {
    #[inline(always)]
    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        <f32 as Display>::fmt(&self.to_f32(), fmt)
    }
}

impl LowerExp for CssSignedNumber {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        <f32 as LowerExp>::fmt(&self.to_f32(), f)
    }
}

impl UpperExp for CssSignedNumber {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        <f32 as UpperExp>::fmt(&self.to_f32(), f)
    }
}

impl Default for CssSignedNumber {
    #[inline(always)]
    fn default() -> Self {
        Self::Zero
    }
}

impl Add<CssSignedNumber> for CssSignedNumber {
    type Output = Self;

    #[inline(always)]
    fn add(self, rhs: CssSignedNumber) -> Self::Output {
        <Self as CssNumber>::clamp(self.to_f32() + rhs.0)
    }
}

impl AddAssign<CssSignedNumber> for CssSignedNumber {
    #[inline(always)]
    fn add_assign(&mut self, rhs: CssSignedNumber) {
        *self = self.add(rhs)
    }
}

impl Sub<CssSignedNumber> for CssSignedNumber {
    type Output = Self;

    #[inline(always)]
    fn sub(self, rhs: CssSignedNumber) -> Self::Output {
        <Self as CssNumber>::clamp(self.to_f32() - rhs.0)
    }
}

impl SubAssign<CssSignedNumber> for CssSignedNumber {
    #[inline(always)]
    fn sub_assign(&mut self, rhs: CssSignedNumber) {
        *self = self.sub(rhs)
    }
}

impl Mul<CssSignedNumber> for CssSignedNumber {
    type Output = Self;

    #[inline(always)]
    fn mul(self, rhs: CssSignedNumber) -> Self::Output {
        <Self as CssNumber>::clamp(self.to_f32() * rhs.0)
    }
}

impl MulAssign<CssSignedNumber> for CssSignedNumber {
    #[inline(always)]
    fn mul_assign(&mut self, rhs: CssSignedNumber) {
        *self = self.mul(rhs)
    }
}

impl Div<CssSignedNumber> for CssSignedNumber {
    type Output = Self;

    #[inline(always)]
    fn div(self, rhs: CssSignedNumber) -> Self::Output {
        if rhs.0.is_nan() {
            let value = if (self.to_f32() / rhs.0).is_sign_positive() {
                ::std::f32::MAX
            } else {
                ::std::f32::MIN
            };
            CssSignedNumber(value)
        } else {
            <Self as CssNumber>::clamp(self.to_f32() / rhs.0)
        }
    }
}

impl DivAssign<CssSignedNumber> for CssSignedNumber {
    #[inline(always)]
    fn div_assign(&mut self, rhs: CssSignedNumber) {
        *self = self.div(rhs)
    }
}

impl Rem<CssSignedNumber> for CssSignedNumber {
    type Output = Self;

    #[inline(always)]
    fn rem(self, rhs: CssSignedNumber) -> Self::Output {
        if rhs.0.is_nan() {
            let value = if (self.to_f32() % rhs.0).is_sign_positive() {
                ::std::f32::MAX
            } else {
                ::std::f32::MIN
            };
            CssSignedNumber(value)
        } else {
            <Self as CssNumber>::clamp(self.to_f32() % rhs.0)
        }
    }
}

impl RemAssign<CssSignedNumber> for CssSignedNumber {
    #[inline(always)]
    fn rem_assign(&mut self, rhs: CssSignedNumber) {
        *self = self.rem(rhs)
    }
}

impl Neg for CssSignedNumber {
    type Output = Self;

    #[inline(always)]
    fn neg(self) -> Self::Output {
        if self.is_zero() {
            self
        } else {
            CssSignedNumber(-self.to_f32())
        }
    }
}

impl CssNumberNewType<Self> for CssSignedNumber {
    #[inline(always)]
    fn to_f32(&self) -> f32 {
        self.0
    }

    #[inline(always)]
    fn as_CssNumber(&self) -> &CssSignedNumber {
        self
    }
}

impl Deref for CssSignedNumber {
    type Target = f32;

    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl From<u16> for CssSignedNumber {
    #[inline(always)]
    fn from(small: u16) -> CssSignedNumber {
        CssSignedNumber(small as f32)
    }
}

impl From<i16> for CssSignedNumber {
    #[inline(always)]
    fn from(small: i16) -> CssSignedNumber {
        CssSignedNumber(small as f32)
    }
}

impl From<u8> for CssSignedNumber {
    #[inline(always)]
    fn from(small: u8) -> CssSignedNumber {
        CssSignedNumber(small as f32)
    }
}

impl From<i8> for CssSignedNumber {
    #[inline(always)]
    fn from(small: i8) -> CssSignedNumber {
        CssSignedNumber(small as f32)
    }
}

impl FromStr for CssSignedNumber {
    type Err = UnitFromStrError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let value = f32::from_str(s)?;
        Ok(CssSignedNumber::new(value)?)
    }
}

impl CssNumber for CssSignedNumber {
    const Zero: Self = CssSignedNumber(0.0);

    const One: Self = CssSignedNumber(1.0);

    const Maximum: Self = CssSignedNumber(::std::f32::MAX);

    const Minimum: Self = CssSignedNumber(::std::f32::MIN);

    const DotsPerInch: Self = CssSignedNumber(96.0);

    const CentimetresPerInch: Self = CssSignedNumber(2.54);

    #[inline(always)]
    fn as_f32(&self) -> f32 {
        self.0
    }

    #[inline(always)]
    fn as_u32(&self) -> u32 {
        self.0 as u32
    }

    #[doc(hidden)]
    #[inline(always)]
    fn _construct(value: f32) -> Self {
        CssSignedNumber(value)
    }

    #[inline(always)]
    fn parseNumber<'i>(
        value: f32,
        _int_value: Option<i32>,
    ) -> Result<Self, ParseError<'i, CustomParseError<'i>>> {
        CssSignedNumber::new(value).map_err(|cssNumberConversionError| {
            ParseError::from(CustomParseError::CouldNotParseCssSignedNumber(
                cssNumberConversionError,
                value,
            ))
        })
    }
}

impl AppUnitsPer for CssSignedNumber {
    /// Number of app units per pixel
    const AppUnitsPerPX: Self = CssSignedNumber(f32::AppUnitsPerPX);

    /// Number of app units per inch
    const AppUnitsPerIN: Self = CssSignedNumber(f32::AppUnitsPerIN);

    /// Number of app units per centimeter
    const AppUnitsPerCM: Self = CssSignedNumber(f32::AppUnitsPerCM);

    /// Number of app units per millimeter
    const AppUnitsPerMM: Self = CssSignedNumber(f32::AppUnitsPerMM);

    /// Number of app units per quarter
    const AppUnitsPerQ: Self = CssSignedNumber(f32::AppUnitsPerQ);

    /// Number of app units per point
    const AppUnitsPerPT: Self = CssSignedNumber(f32::AppUnitsPerPT);

    /// Number of app units per pica
    const AppUnitsPerPC: Self = CssSignedNumber(f32::AppUnitsPerPC);
}

impl Unit for CssSignedNumber {
    type Number = Self;

    const HasDimension: bool = false;

    #[inline(always)]
    fn parse_one_outside_calc_function<'i, 't>(
        context: &ParserContext,
        input: &mut Parser<'i, 't>,
    ) -> Result<
        CalculablePropertyValue<Self>,
        ParseError<'i, CustomParseError<'i>>,
    > {
        let functionParser = match *input.next()? {
            Token::Number {
                value, int_value, ..
            } => return Self::parseNumber(value, int_value).map(Constant),

            Token::Function(ref name) => FunctionParser::parser(name)?,

            ref unexpectedToken => {
                return CustomParseError::unexpectedToken(unexpectedToken)
            }
        };
        functionParser.parse_one_outside_calc_function(context, input)
    }

    #[inline(always)]
    fn parse_one_inside_calc_function<'i, 't>(
        context: &ParserContext,
        input: &mut Parser<'i, 't>,
    ) -> Result<
        Either<CalculablePropertyValue<Self>, CalcExpression<Self>>,
        ParseError<'i, CustomParseError<'i>>,
    > {
        let functionParser = match *input.next()? {
            Token::Number {
                value, int_value, ..
            } => {
                return Self::parseNumber(value, int_value)
                    .map(|value| Left(Constant(value)))
            }

            Token::Percentage { unit_value, .. } => {
                return PercentageUnit::parse_percentage(unit_value)
                    .map(|value| Left(Percentage(value)))
            }

            Token::ParenthesisBlock => FunctionParser::parentheses,

            Token::Function(ref name) => FunctionParser::parser(name)?,

            ref unexpectedToken => {
                return CustomParseError::unexpectedToken(unexpectedToken)
            }
        };
        functionParser.parse_one_inside_calc_function(context, input)
    }

    #[inline(always)]
    fn to_canonical_dimension_value<
        Conversion: FontRelativeLengthConversion<Self::Number>
            + ViewportPercentageLengthConversion<Self::Number>
            + PercentageConversion<Self::Number>,
    >(
        &self,
        _conversion: &Conversion,
    ) -> Self::Number {
        self.to_CssNumber()
    }

    #[inline(always)]
    fn from_raw_css_for_var_expression_evaluation(
        value: &str,
        _is_not_in_page_rule: bool,
    ) -> Option<Self> {
        fn from_raw_css_for_var_expression_evaluation_internal<'i: 't, 't>(
            input: &mut Parser<'i, 't>,
        ) -> Result<CssSignedNumber, ParseError<'i, CustomParseError<'i>>>
        {
            let value = match *input.next()? {
                Token::Number {
                    value, int_value, ..
                } => CssSignedNumber::parseNumber(value, int_value),

                ref unexpectedToken => {
                    CustomParseError::unexpectedToken(unexpectedToken)
                }
            };

            input.skip_whitespace();

            input.expect_exhausted()?;

            value
        }

        const LineNumberingIsZeroBased: u32 = 0;

        let mut parserInput = ParserInput::new_with_line_number_offset(
            value,
            LineNumberingIsZeroBased,
        );
        let mut input = Parser::new(&mut parserInput);

        from_raw_css_for_var_expression_evaluation_internal(&mut input).ok()
    }
}