Skip to main content

style/values/generics/
rect.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! Generic types for CSS values that are composed of four sides.
6
7use crate::derives::*;
8use crate::parser::{Parse, ParserContext};
9use cssparser::Parser;
10use std::fmt::{self, Write};
11use style_traits::{CssWriter, ParseError, ToCss};
12
13/// A CSS value made of four components, where its `ToCss` impl will try to
14/// serialize as few components as possible, like for example in `border-width`.
15#[derive(
16    Animate,
17    Clone,
18    ComputeSquaredDistance,
19    Copy,
20    Debug,
21    Deserialize,
22    MallocSizeOf,
23    PartialEq,
24    SpecifiedValueInfo,
25    Serialize,
26    ToAnimatedValue,
27    ToAnimatedZero,
28    ToComputedValue,
29    ToResolvedValue,
30    ToShmem,
31)]
32#[repr(C)]
33pub struct Rect<T>(pub T, pub T, pub T, pub T);
34
35impl<T> Rect<T> {
36    /// Returns a new `Rect<T>` value.
37    pub fn new(first: T, second: T, third: T, fourth: T) -> Self {
38        Rect(first, second, third, fourth)
39    }
40}
41
42impl<T> Rect<T>
43where
44    T: Clone,
45{
46    /// Returns a rect with all the values equal to `v`.
47    pub fn all(v: T) -> Self {
48        Rect::new(v.clone(), v.clone(), v.clone(), v)
49    }
50
51    /// Returns whether all four sides have the same value.
52    #[inline]
53    pub fn all_sides_equal(&self) -> bool
54    where
55        T: PartialEq,
56    {
57        self.0 == self.1 && self.1 == self.2 && self.2 == self.3
58    }
59
60    /// Parses a new `Rect<T>` value with the given parse function.
61    pub fn parse_with<'i, 't, Parse>(
62        context: &ParserContext,
63        input: &mut Parser<'i, 't>,
64        parse: Parse,
65    ) -> Result<Self, ParseError<'i>>
66    where
67        Parse: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<T, ParseError<'i>>,
68    {
69        let first = parse(context, input)?;
70        let second = if let Ok(second) = input.try_parse(|i| parse(context, i)) {
71            second
72        } else {
73            // <first>
74            return Ok(Self::new(
75                first.clone(),
76                first.clone(),
77                first.clone(),
78                first,
79            ));
80        };
81        let third = if let Ok(third) = input.try_parse(|i| parse(context, i)) {
82            third
83        } else {
84            // <first> <second>
85            return Ok(Self::new(first.clone(), second.clone(), first, second));
86        };
87        let fourth = if let Ok(fourth) = input.try_parse(|i| parse(context, i)) {
88            fourth
89        } else {
90            // <first> <second> <third>
91            return Ok(Self::new(first, second.clone(), third, second));
92        };
93        // <first> <second> <third> <fourth>
94        Ok(Self::new(first, second, third, fourth))
95    }
96
97    /// Parses a new `Rect<T>` value which all components must be specified, with the given parse
98    /// function.
99    pub fn parse_all_components_with<'i, 't, Parse>(
100        context: &ParserContext,
101        input: &mut Parser<'i, 't>,
102        parse: Parse,
103    ) -> Result<Self, ParseError<'i>>
104    where
105        Parse: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<T, ParseError<'i>>,
106    {
107        let first = parse(context, input)?;
108        let second = parse(context, input)?;
109        let third = parse(context, input)?;
110        let fourth = parse(context, input)?;
111        // <first> <second> <third> <fourth>
112        Ok(Self::new(first, second, third, fourth))
113    }
114}
115
116impl<T> Parse for Rect<T>
117where
118    T: Clone + Parse,
119{
120    #[inline]
121    fn parse<'i, 't>(
122        context: &ParserContext,
123        input: &mut Parser<'i, 't>,
124    ) -> Result<Self, ParseError<'i>> {
125        Self::parse_with(context, input, T::parse)
126    }
127}
128
129impl<T> ToCss for Rect<T>
130where
131    T: PartialEq + ToCss,
132{
133    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
134    where
135        W: Write,
136    {
137        self.0.to_css(dest)?;
138        let same_vertical = self.0 == self.2;
139        let same_horizontal = self.1 == self.3;
140        if same_vertical && same_horizontal && self.0 == self.1 {
141            return Ok(());
142        }
143        dest.write_char(' ')?;
144        self.1.to_css(dest)?;
145        if same_vertical && same_horizontal {
146            return Ok(());
147        }
148        dest.write_char(' ')?;
149        self.2.to_css(dest)?;
150        if same_horizontal {
151            return Ok(());
152        }
153        dest.write_char(' ')?;
154        self.3.to_css(dest)
155    }
156}