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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
//! CSS length values.

use super::angle::impl_try_from_angle;
use super::calc::{Calc, MathFunction};
use super::number::CSSNumber;
use super::percentage::DimensionPercentage;
use crate::error::{ParserError, PrinterError};
use crate::printer::Printer;
use crate::traits::TrySign;
use crate::traits::{
  private::{AddInternal, TryAdd},
  Map, Parse, Sign, ToCss, TryMap, TryOp, Zero,
};
use const_str;
use cssparser::*;

/// A CSS [`<length-percentage>`](https://www.w3.org/TR/css-values-4/#typedef-length-percentage) value.
/// May be specified as either a length or a percentage that resolves to an length.
pub type LengthPercentage = DimensionPercentage<LengthValue>;

impl LengthPercentage {
  /// Constructs a `LengthPercentage` with the given pixel value.
  pub fn px(val: CSSNumber) -> LengthPercentage {
    LengthPercentage::Dimension(LengthValue::Px(val))
  }

  pub(crate) fn to_css_unitless<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
  where
    W: std::fmt::Write,
  {
    match self {
      DimensionPercentage::Dimension(d) => d.to_css_unitless(dest),
      _ => self.to_css(dest),
    }
  }
}

/// Either a [`<length-percentage>`](https://www.w3.org/TR/css-values-4/#typedef-length-percentage), or the `auto` keyword.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
  feature = "serde",
  derive(serde::Serialize, serde::Deserialize),
  serde(tag = "type", content = "value", rename_all = "kebab-case")
)]
pub enum LengthPercentageOrAuto {
  /// The `auto` keyword.
  Auto,
  /// A [`<length-percentage>`](https://www.w3.org/TR/css-values-4/#typedef-length-percentage).
  LengthPercentage(LengthPercentage),
}

impl<'i> Parse<'i> for LengthPercentageOrAuto {
  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
    if input.try_parse(|i| i.expect_ident_matching("auto")).is_ok() {
      return Ok(LengthPercentageOrAuto::Auto);
    }

    if let Ok(percent) = input.try_parse(|input| LengthPercentage::parse(input)) {
      return Ok(LengthPercentageOrAuto::LengthPercentage(percent));
    }

    Err(input.new_error_for_next_token())
  }
}

impl ToCss for LengthPercentageOrAuto {
  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
  where
    W: std::fmt::Write,
  {
    use LengthPercentageOrAuto::*;
    match self {
      Auto => dest.write_str("auto"),
      LengthPercentage(l) => l.to_css(dest),
    }
  }
}

const PX_PER_IN: f32 = 96.0;
const PX_PER_CM: f32 = PX_PER_IN / 2.54;
const PX_PER_MM: f32 = PX_PER_CM / 10.0;
const PX_PER_Q: f32 = PX_PER_CM / 40.0;
const PX_PER_PT: f32 = PX_PER_IN / 72.0;
const PX_PER_PC: f32 = PX_PER_IN / 6.0;

macro_rules! define_length_units {
  (
    $(
      $(#[$meta: meta])*
      $name: ident,
    )+
  ) => {
    /// A CSS [`<length>`](https://www.w3.org/TR/css-values-4/#lengths) value,
    /// without support for `calc()`. See also: [Length](Length).
    #[derive(Debug, Clone, PartialEq)]
    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(tag = "unit", content = "value", rename_all = "kebab-case"))]
    pub enum LengthValue {
      $(
        $(#[$meta])*
        $name(CSSNumber),
      )+
    }

    impl<'i> Parse<'i> for LengthValue {
      fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
        let location = input.current_source_location();
        let token = input.next()?;
        match *token {
          Token::Dimension { value, ref unit, .. } => {
            Ok(match unit {
              $(
                s if s.eq_ignore_ascii_case(stringify!($name)) => LengthValue::$name(value),
              )+
              _ => return Err(location.new_unexpected_token_error(token.clone())),
            })
          },
          Token::Number { value, .. } => {
            // TODO: quirks mode only?
            Ok(LengthValue::Px(value))
          }
          ref token => return Err(location.new_unexpected_token_error(token.clone())),
        }
      }
    }

    impl LengthValue {
      /// Returns the numeric value and unit string for the length value.
      pub fn to_unit_value(&self) -> (CSSNumber, &str) {
        match self {
          $(
            LengthValue::$name(value) => (*value, const_str::convert_ascii_case!(lower, stringify!($name))),
          )+
        }
      }
    }

    impl TryAdd<LengthValue> for LengthValue {
      fn try_add(&self, other: &LengthValue) -> Option<LengthValue> {
        use LengthValue::*;
        match (self, other) {
          $(
            ($name(a), $name(b)) => Some($name(a + b)),
          )+
          (a, b) => {
            if let (Some(a), Some(b)) = (a.to_px(), b.to_px()) {
              Some(Px(a + b))
            } else {
              None
            }
          }
        }
      }
    }

    impl std::ops::Mul<CSSNumber> for LengthValue {
      type Output = Self;

      fn mul(self, other: CSSNumber) -> LengthValue {
        use LengthValue::*;
        match self {
          $(
            $name(value) => $name(value * other),
          )+
        }
      }
    }

    impl std::cmp::PartialOrd<LengthValue> for LengthValue {
      fn partial_cmp(&self, other: &LengthValue) -> Option<std::cmp::Ordering> {
        use LengthValue::*;
        match (self, other) {
          $(
            ($name(a), $name(b)) => a.partial_cmp(b),
          )+
          (a, b) => {
            if let (Some(a), Some(b)) = (a.to_px(), b.to_px()) {
              a.partial_cmp(&b)
            } else {
              None
            }
          }
        }
      }
    }

    impl TryOp for LengthValue {
      fn try_op<F: FnOnce(f32, f32) -> f32>(&self, rhs: &Self, op: F) -> Option<Self> {
        use LengthValue::*;
        match (self, rhs) {
          $(
            ($name(a), $name(b)) => Some($name(op(*a, *b))),
          )+
          (a, b) => {
            if let (Some(a), Some(b)) = (a.to_px(), b.to_px()) {
              Some(Px(op(a, b)))
            } else {
              None
            }
          }
        }
      }

      fn try_op_to<T, F: FnOnce(f32, f32) -> T>(&self, rhs: &Self, op: F) -> Option<T> {
        use LengthValue::*;
        match (self, rhs) {
          $(
            ($name(a), $name(b)) => Some(op(*a, *b)),
          )+
          (a, b) => {
            if let (Some(a), Some(b)) = (a.to_px(), b.to_px()) {
              Some(op(a, b))
            } else {
              None
            }
          }
        }
      }
    }

    impl Map for LengthValue {
      fn map<F: FnOnce(f32) -> f32>(&self, op: F) -> Self {
        use LengthValue::*;
        match self {
          $(
            $name(value) => $name(op(*value)),
          )+
        }
      }
    }

    impl Sign for LengthValue {
      fn sign(&self) -> f32 {
        use LengthValue::*;
        match self {
          $(
            $name(value) => value.sign(),
          )+
        }
      }
    }

    impl Zero for LengthValue {
      fn zero() -> Self {
        LengthValue::Px(0.0)
      }

      fn is_zero(&self) -> bool {
        use LengthValue::*;
        match self {
          $(
            $name(value) => value.is_zero(),
          )+
        }
      }
    }

    impl_try_from_angle!(LengthValue);
  };
}

define_length_units! {
  // https://www.w3.org/TR/css-values-4/#absolute-lengths
  /// A length in pixels.
  Px,
  /// A length in inches. 1in = 96px.
  In,
  /// A length in centimeters. 1cm = 96px / 2.54.
  Cm,
  /// A length in millimeters. 1mm = 1/10th of 1cm.
  Mm,
  /// A length in quarter-millimeters. 1Q = 1/40th of 1cm.
  Q,
  /// A length in points. 1pt = 1/72nd of 1in.
  Pt,
  /// A length in picas. 1pc = 1/6th of 1in.
  Pc,

  // https://www.w3.org/TR/css-values-4/#font-relative-lengths
  /// A length in the `em` unit. An `em` is equal to the computed value of the
  /// font-size property of the element on which it is used.
  Em,
  /// A length in the `rem` unit. A `rem` is equal to the computed value of the
  /// `em` unit on the root element.
  Rem,
  /// A length in `ex` unit. An `ex` is equal to the x-height of the font.
  Ex,
  /// A length in the `rex` unit. A `rex` is equal to the value of the `ex` unit on the root element.
  Rex,
  /// A length in the `ch` unit. A `ch` is equal to the width of the zero ("0") character in the current font.
  Ch,
  /// A length in the `rch` unit. An `rch` is equal to the value of the `ch` unit on the root element.
  Rch,
  /// A length in the `cap` unit. A `cap` is equal to the cap-height of the font.
  Cap,
  /// A length in the `rcap` unit. An `rcap` is equal to the value of the `cap` unit on the root element.
  Rcap,
  /// A length in the `ic` unit. An `ic` is equal to the width of the “水” (CJK water ideograph) character in the current font.
  Ic,
  /// A length in the `ric` unit. An `ric` is equal to the value of the `ic` unit on the root element.
  Ric,
  /// A length in the `lh` unit. An `lh` is equal to the computed value of the `line-height` property.
  Lh,
  /// A length in the `rlh` unit. An `rlh` is equal to the value of the `lh` unit on the root element.
  Rlh,

  // https://www.w3.org/TR/css-values-4/#viewport-relative-units
  /// A length in the `vw` unit. A `vw` is equal to 1% of the [viewport width](https://www.w3.org/TR/css-values-4/#ua-default-viewport-size).
  Vw,
  /// A length in the `lvw` unit. An `lvw` is equal to 1% of the [large viewport width](https://www.w3.org/TR/css-values-4/#large-viewport-size).
  Lvw,
  /// A length in the `svw` unit. An `svw` is equal to 1% of the [small viewport width](https://www.w3.org/TR/css-values-4/#small-viewport-size).
  Svw,
  /// A length in the `dvw` unit. An `dvw` is equal to 1% of the [dynamic viewport width](https://www.w3.org/TR/css-values-4/#dynamic-viewport-size).
  Dvw,
  /// A length in the `cqw` unit. An `cqw` is equal to 1% of the [query container](https://drafts.csswg.org/css-contain-3/#query-container) width.
  Cqw,

  /// A length in the `vh` unit. A `vh` is equal to 1% of the [viewport height](https://www.w3.org/TR/css-values-4/#ua-default-viewport-size).
  Vh,
  /// A length in the `lvh` unit. An `lvh` is equal to 1% of the [large viewport height](https://www.w3.org/TR/css-values-4/#large-viewport-size).
  Lvh,
  /// A length in the `svh` unit. An `svh` is equal to 1% of the [small viewport height](https://www.w3.org/TR/css-values-4/#small-viewport-size).
  Svh,
  /// A length in the `dvh` unit. An `dvh` is equal to 1% of the [dynamic viewport height](https://www.w3.org/TR/css-values-4/#dynamic-viewport-size).
  Dvh,
  /// A length in the `cqh` unit. An `cqh` is equal to 1% of the [query container](https://drafts.csswg.org/css-contain-3/#query-container) height.
  Cqh,

  /// A length in the `vi` unit. A `vi` is equal to 1% of the [viewport size](https://www.w3.org/TR/css-values-4/#ua-default-viewport-size)
  /// in the box's [inline axis](https://www.w3.org/TR/css-writing-modes-4/#inline-axis).
  Vi,
  /// A length in the `svi` unit. A `svi` is equal to 1% of the [small viewport size](https://www.w3.org/TR/css-values-4/#small-viewport-size)
  /// in the box's [inline axis](https://www.w3.org/TR/css-writing-modes-4/#inline-axis).
  Svi,
  /// A length in the `lvi` unit. A `lvi` is equal to 1% of the [large viewport size](https://www.w3.org/TR/css-values-4/#large-viewport-size)
  /// in the box's [inline axis](https://www.w3.org/TR/css-writing-modes-4/#inline-axis).
  Lvi,
  /// A length in the `dvi` unit. A `dvi` is equal to 1% of the [dynamic viewport size](https://www.w3.org/TR/css-values-4/#dynamic-viewport-size)
  /// in the box's [inline axis](https://www.w3.org/TR/css-writing-modes-4/#inline-axis).
  Dvi,
  /// A length in the `cqi` unit. An `cqi` is equal to 1% of the [query container](https://drafts.csswg.org/css-contain-3/#query-container) inline size.
  Cqi,

  /// A length in the `vb` unit. A `vb` is equal to 1% of the [viewport size](https://www.w3.org/TR/css-values-4/#ua-default-viewport-size)
  /// in the box's [block axis](https://www.w3.org/TR/css-writing-modes-4/#block-axis).
  Vb,
  /// A length in the `svb` unit. A `svb` is equal to 1% of the [small viewport size](https://www.w3.org/TR/css-values-4/#small-viewport-size)
  /// in the box's [block axis](https://www.w3.org/TR/css-writing-modes-4/#block-axis).
  Svb,
  /// A length in the `lvb` unit. A `lvb` is equal to 1% of the [large viewport size](https://www.w3.org/TR/css-values-4/#large-viewport-size)
  /// in the box's [block axis](https://www.w3.org/TR/css-writing-modes-4/#block-axis).
  Lvb,
  /// A length in the `dvb` unit. A `dvb` is equal to 1% of the [dynamic viewport size](https://www.w3.org/TR/css-values-4/#dynamic-viewport-size)
  /// in the box's [block axis](https://www.w3.org/TR/css-writing-modes-4/#block-axis).
  Dvb,
  /// A length in the `cqb` unit. An `cqb` is equal to 1% of the [query container](https://drafts.csswg.org/css-contain-3/#query-container) block size.
  Cqb,

  /// A length in the `vmin` unit. A `vmin` is equal to the smaller of `vw` and `vh`.
  Vmin,
  /// A length in the `svmin` unit. An `svmin` is equal to the smaller of `svw` and `svh`.
  Svmin,
  /// A length in the `lvmin` unit. An `lvmin` is equal to the smaller of `lvw` and `lvh`.
  Lvmin,
  /// A length in the `dvmin` unit. A `dvmin` is equal to the smaller of `dvw` and `dvh`.
  Dvmin,
  /// A length in the `cqmin` unit. An `cqmin` is equal to the smaller of `cqi` and `cqb`.
  Cqmin,

  /// A length in the `vmax` unit. A `vmax` is equal to the larger of `vw` and `vh`.
  Vmax,
  /// A length in the `svmax` unit. An `svmax` is equal to the larger of `svw` and `svh`.
  Svmax,
  /// A length in the `lvmax` unit. An `lvmax` is equal to the larger of `lvw` and `lvh`.
  Lvmax,
  /// A length in the `dvmax` unit. An `dvmax` is equal to the larger of `dvw` and `dvh`.
  Dvmax,
  /// A length in the `cqmax` unit. An `cqmin` is equal to the larger of `cqi` and `cqb`.
  Cqmax,
}

impl ToCss for LengthValue {
  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
  where
    W: std::fmt::Write,
  {
    let (value, unit) = self.to_unit_value();

    // The unit can be omitted if the value is zero, except inside calc()
    // expressions, where unitless numbers won't be parsed as dimensions.
    if !dest.in_calc && value == 0.0 {
      return dest.write_char('0');
    }

    serialize_dimension(value, unit, dest)
  }
}

impl LengthValue {
  pub(crate) fn to_css_unitless<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
  where
    W: std::fmt::Write,
  {
    match self {
      LengthValue::Px(value) => value.to_css(dest),
      _ => self.to_css(dest),
    }
  }
}

pub(crate) fn serialize_dimension<W>(value: f32, unit: &str, dest: &mut Printer<W>) -> Result<(), PrinterError>
where
  W: std::fmt::Write,
{
  use cssparser::ToCss;
  let int_value = if value.fract() == 0.0 { Some(value as i32) } else { None };
  let token = Token::Dimension {
    has_sign: value < 0.0,
    value,
    int_value,
    unit: CowRcStr::from(unit),
  };
  if value != 0.0 && value.abs() < 1.0 {
    let mut s = String::new();
    token.to_css(&mut s)?;
    if value < 0.0 {
      dest.write_char('-')?;
      dest.write_str(s.trim_start_matches("-0"))
    } else {
      dest.write_str(s.trim_start_matches('0'))
    }
  } else {
    token.to_css(dest)?;
    Ok(())
  }
}

impl LengthValue {
  /// Attempts to convert the value to pixels.
  /// Returns `None` if the conversion is not possible.
  pub fn to_px(&self) -> Option<CSSNumber> {
    use LengthValue::*;
    match self {
      Px(value) => Some(*value),
      In(value) => Some(value * PX_PER_IN),
      Cm(value) => Some(value * PX_PER_CM),
      Mm(value) => Some(value * PX_PER_MM),
      Q(value) => Some(value * PX_PER_Q),
      Pt(value) => Some(value * PX_PER_PT),
      Pc(value) => Some(value * PX_PER_PC),
      _ => None,
    }
  }
}

/// A CSS [`<length>`](https://www.w3.org/TR/css-values-4/#lengths) value, with support for `calc()`.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
  feature = "serde",
  derive(serde::Serialize, serde::Deserialize),
  serde(tag = "type", content = "value", rename_all = "kebab-case")
)]
pub enum Length {
  /// An explicitly specified length value.
  Value(LengthValue),
  /// A computed length value using `calc()`.
  Calc(Box<Calc<Length>>),
}

impl<'i> Parse<'i> for Length {
  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
    match input.try_parse(Calc::parse) {
      Ok(Calc::Value(v)) => return Ok(*v),
      Ok(calc) => return Ok(Length::Calc(Box::new(calc))),
      _ => {}
    }

    let len = LengthValue::parse(input)?;
    Ok(Length::Value(len))
  }
}

impl ToCss for Length {
  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
  where
    W: std::fmt::Write,
  {
    match self {
      Length::Value(a) => a.to_css(dest),
      Length::Calc(c) => c.to_css(dest),
    }
  }
}

impl std::ops::Mul<CSSNumber> for Length {
  type Output = Self;

  fn mul(self, other: CSSNumber) -> Length {
    match self {
      Length::Value(a) => Length::Value(a * other),
      Length::Calc(a) => Length::Calc(Box::new(*a * other)),
    }
  }
}

impl std::ops::Add<Length> for Length {
  type Output = Self;

  fn add(self, other: Length) -> Length {
    // Unwrap calc(...) functions so we can add inside.
    // Then wrap the result in a calc(...) again if necessary.
    let a = unwrap_calc(self);
    let b = unwrap_calc(other);
    let res = AddInternal::add(a, b);
    match res {
      Length::Calc(c) => match *c {
        Calc::Value(l) => *l,
        Calc::Function(f) if !matches!(*f, MathFunction::Calc(_)) => Length::Calc(Box::new(Calc::Function(f))),
        c => Length::Calc(Box::new(Calc::Function(Box::new(MathFunction::Calc(c))))),
      },
      _ => res,
    }
  }
}

fn unwrap_calc(length: Length) -> Length {
  match length {
    Length::Calc(c) => match *c {
      Calc::Function(f) => match *f {
        MathFunction::Calc(c) => Length::Calc(Box::new(c)),
        c => Length::Calc(Box::new(Calc::Function(Box::new(c)))),
      },
      _ => Length::Calc(c),
    },
    _ => length,
  }
}

impl AddInternal for Length {
  fn add(self, other: Self) -> Self {
    match self.try_add(&other) {
      Some(r) => r,
      None => self.add(other),
    }
  }
}

impl Length {
  /// Constructs a length with the given pixel value.
  pub fn px(px: CSSNumber) -> Length {
    Length::Value(LengthValue::Px(px))
  }

  /// Attempts to convert the length to pixels.
  /// Returns `None` if the conversion is not possible.
  pub fn to_px(&self) -> Option<CSSNumber> {
    match self {
      Length::Value(a) => a.to_px(),
      _ => None,
    }
  }

  fn add(self, other: Length) -> Length {
    let mut a = self;
    let mut b = other;

    if a.is_zero() {
      return b;
    }

    if b.is_zero() {
      return a;
    }

    if a.is_sign_negative() && b.is_sign_positive() {
      std::mem::swap(&mut a, &mut b);
    }

    match (a, b) {
      (Length::Calc(a), Length::Calc(b)) => return Length::Calc(Box::new(a.add(*b))),
      (Length::Calc(calc), b) => {
        if let Calc::Value(a) = *calc {
          a.add(b)
        } else {
          Length::Calc(Box::new(Calc::Sum(Box::new((*calc).into()), Box::new(b.into()))))
        }
      }
      (a, Length::Calc(calc)) => {
        if let Calc::Value(b) = *calc {
          a.add(*b)
        } else {
          Length::Calc(Box::new(Calc::Sum(Box::new(a.into()), Box::new((*calc).into()))))
        }
      }
      (a, b) => Length::Calc(Box::new(Calc::Sum(Box::new(a.into()), Box::new(b.into())))),
    }
  }
}

impl Zero for Length {
  fn zero() -> Length {
    Length::Value(LengthValue::Px(0.0))
  }

  fn is_zero(&self) -> bool {
    match self {
      Length::Value(v) => v.is_zero(),
      _ => false,
    }
  }
}

impl TryAdd<Length> for Length {
  fn try_add(&self, other: &Length) -> Option<Length> {
    match (self, other) {
      (Length::Value(a), Length::Value(b)) => {
        if let Some(res) = a.try_add(b) {
          Some(Length::Value(res))
        } else {
          None
        }
      }
      (Length::Calc(a), other) => match &**a {
        Calc::Value(v) => v.try_add(other),
        Calc::Sum(a, b) => {
          if let Some(res) = Length::Calc(Box::new(*a.clone())).try_add(other) {
            return Some(res.add(Length::from(*b.clone())));
          }

          if let Some(res) = Length::Calc(Box::new(*b.clone())).try_add(other) {
            return Some(Length::from(*a.clone()).add(res));
          }

          None
        }
        _ => None,
      },
      (other, Length::Calc(b)) => match &**b {
        Calc::Value(v) => other.try_add(&*v),
        Calc::Sum(a, b) => {
          if let Some(res) = other.try_add(&Length::Calc(Box::new(*a.clone()))) {
            return Some(res.add(Length::from(*b.clone())));
          }

          if let Some(res) = other.try_add(&Length::Calc(Box::new(*b.clone()))) {
            return Some(Length::from(*a.clone()).add(res));
          }

          None
        }
        _ => None,
      },
    }
  }
}

impl std::convert::Into<Calc<Length>> for Length {
  fn into(self) -> Calc<Length> {
    match self {
      Length::Calc(c) => *c,
      b => Calc::Value(Box::new(b)),
    }
  }
}

impl std::convert::From<Calc<Length>> for Length {
  fn from(calc: Calc<Length>) -> Length {
    Length::Calc(Box::new(calc))
  }
}

impl std::cmp::PartialOrd<Length> for Length {
  fn partial_cmp(&self, other: &Length) -> Option<std::cmp::Ordering> {
    match (self, other) {
      (Length::Value(a), Length::Value(b)) => a.partial_cmp(b),
      _ => None,
    }
  }
}

impl TryOp for Length {
  fn try_op<F: FnOnce(f32, f32) -> f32>(&self, rhs: &Self, op: F) -> Option<Self> {
    match (self, rhs) {
      (Length::Value(a), Length::Value(b)) => a.try_op(b, op).map(Length::Value),
      _ => None,
    }
  }

  fn try_op_to<T, F: FnOnce(f32, f32) -> T>(&self, rhs: &Self, op: F) -> Option<T> {
    match (self, rhs) {
      (Length::Value(a), Length::Value(b)) => a.try_op_to(b, op),
      _ => None,
    }
  }
}

impl TryMap for Length {
  fn try_map<F: FnOnce(f32) -> f32>(&self, op: F) -> Option<Self> {
    match self {
      Length::Value(v) => v.try_map(op).map(Length::Value),
      _ => None,
    }
  }
}

impl TrySign for Length {
  fn try_sign(&self) -> Option<f32> {
    match self {
      Length::Value(v) => Some(v.sign()),
      Length::Calc(c) => c.try_sign(),
    }
  }
}

impl_try_from_angle!(Length);

/// Either a [`<length>`](https://www.w3.org/TR/css-values-4/#lengths) or a [`<number>`](https://www.w3.org/TR/css-values-4/#numbers).
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
  feature = "serde",
  derive(serde::Serialize, serde::Deserialize),
  serde(tag = "type", content = "value", rename_all = "kebab-case")
)]
pub enum LengthOrNumber {
  /// A length.
  Length(Length),
  /// A number.
  Number(CSSNumber),
}

impl Default for LengthOrNumber {
  fn default() -> LengthOrNumber {
    LengthOrNumber::Number(0.0)
  }
}

impl Zero for LengthOrNumber {
  fn zero() -> Self {
    LengthOrNumber::Number(0.0)
  }

  fn is_zero(&self) -> bool {
    match self {
      LengthOrNumber::Length(l) => l.is_zero(),
      LengthOrNumber::Number(v) => v.is_zero(),
    }
  }
}

impl<'i> Parse<'i> for LengthOrNumber {
  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
    // Parse number first so unitless numbers are not parsed as lengths.
    if let Ok(number) = input.try_parse(CSSNumber::parse) {
      return Ok(LengthOrNumber::Number(number));
    }

    if let Ok(length) = Length::parse(input) {
      return Ok(LengthOrNumber::Length(length));
    }

    Err(input.new_error_for_next_token())
  }
}

impl ToCss for LengthOrNumber {
  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
  where
    W: std::fmt::Write,
  {
    match self {
      LengthOrNumber::Length(length) => length.to_css(dest),
      LengthOrNumber::Number(number) => number.to_css(dest),
    }
  }
}