Skip to main content

style/values/computed/
time.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//! Computed time values.
6
7use crate::derives::*;
8use crate::typed_om::{NumericValue, ToTyped, TypedValue, UnitValue};
9use crate::values::CSSFloat;
10use crate::Zero;
11use std::fmt::{self, Write};
12use std::ops::AddAssign;
13use style_traits::{CssString, CssWriter, ToCss};
14use thin_vec::ThinVec;
15
16/// A computed `<time>` value.
17#[derive(
18    Animate,
19    Clone,
20    Copy,
21    Debug,
22    Deserialize,
23    MallocSizeOf,
24    PartialEq,
25    PartialOrd,
26    Serialize,
27    ToAnimatedZero,
28    ToResolvedValue,
29)]
30#[repr(C)]
31pub struct Time {
32    seconds: CSSFloat,
33}
34
35impl Time {
36    /// Creates a time value from a seconds amount.
37    pub fn from_seconds(seconds: CSSFloat) -> Self {
38        Time { seconds }
39    }
40
41    /// Returns the amount of seconds this time represents.
42    #[inline]
43    pub fn seconds(&self) -> CSSFloat {
44        self.seconds
45    }
46}
47
48impl ToCss for Time {
49    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
50    where
51        W: Write,
52    {
53        self.seconds().to_css(dest)?;
54        dest.write_char('s')
55    }
56}
57
58impl ToTyped for Time {
59    fn to_typed(&self, dest: &mut ThinVec<TypedValue>) -> Result<(), ()> {
60        dest.push(TypedValue::Numeric(NumericValue::Unit(UnitValue {
61            value: self.seconds(),
62            unit: CssString::from("s"),
63        })));
64        Ok(())
65    }
66}
67
68impl Zero for Time {
69    fn zero() -> Self {
70        Self::from_seconds(0.0)
71    }
72
73    fn is_zero(&self) -> bool {
74        self.seconds == 0.
75    }
76}
77
78impl AddAssign for Time {
79    fn add_assign(&mut self, rhs: Self) {
80        self.seconds += rhs.seconds
81    }
82}