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<Parse>(
62        context: &ParserContext,
63        input: &mut Parser,
64        parse: Parse,
65    ) -> Result<Self, ParseError>
66    where
67        Parse: Fn(&ParserContext, &mut Parser) -> Result<T, ParseError>,
68    {
69        let first = parse(context, input)?;
70        let Ok(second) = input.try_parse(|i| parse(context, i)) else {
71            // <first>
72            return Ok(Self::new(
73                first.clone(),
74                first.clone(),
75                first.clone(),
76                first,
77            ));
78        };
79        let Ok(third) = input.try_parse(|i| parse(context, i)) else {
80            // <first> <second>
81            return Ok(Self::new(first.clone(), second.clone(), first, second));
82        };
83        let Ok(fourth) = input.try_parse(|i| parse(context, i)) else {
84            // <first> <second> <third>
85            return Ok(Self::new(first, second.clone(), third, second));
86        };
87        // <first> <second> <third> <fourth>
88        Ok(Self::new(first, second, third, fourth))
89    }
90
91    /// Parses a new `Rect<T>` value which all components must be specified, with the given parse
92    /// function.
93    pub fn parse_all_components_with<Parse>(
94        context: &ParserContext,
95        input: &mut Parser,
96        parse: Parse,
97    ) -> Result<Self, ParseError>
98    where
99        Parse: Fn(&ParserContext, &mut Parser) -> Result<T, ParseError>,
100    {
101        let first = parse(context, input)?;
102        let second = parse(context, input)?;
103        let third = parse(context, input)?;
104        let fourth = parse(context, input)?;
105        // <first> <second> <third> <fourth>
106        Ok(Self::new(first, second, third, fourth))
107    }
108}
109
110impl<T> Parse for Rect<T>
111where
112    T: Clone + Parse,
113{
114    #[inline]
115    fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
116        Self::parse_with(context, input, T::parse)
117    }
118}
119
120impl<T> ToCss for Rect<T>
121where
122    T: PartialEq + ToCss,
123{
124    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
125    where
126        W: Write,
127    {
128        self.0.to_css(dest)?;
129        let same_vertical = self.0 == self.2;
130        let same_horizontal = self.1 == self.3;
131        if same_vertical && same_horizontal && self.0 == self.1 {
132            return Ok(());
133        }
134        dest.write_char(' ')?;
135        self.1.to_css(dest)?;
136        if same_vertical && same_horizontal {
137            return Ok(());
138        }
139        dest.write_char(' ')?;
140        self.2.to_css(dest)?;
141        if same_horizontal {
142            return Ok(());
143        }
144        dest.write_char(' ')?;
145        self.3.to_css(dest)
146    }
147}