Skip to main content

style/values/
mod.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//! Common [values][values] used in CSS.
6//!
7//! [values]: https://drafts.csswg.org/css-values/
8
9#![deny(missing_docs)]
10
11use crate::derives::*;
12use crate::parser::{Parse, ParserContext};
13use crate::typed_om::{KeywordValue, NumericType, NumericValue, ToTyped, TypedValue, UnitValue};
14use crate::values::distance::{ComputeSquaredDistance, SquaredDistance};
15use crate::values::generics::position::IsTreeScoped;
16use crate::Atom;
17pub use cssparser::{serialize_identifier, serialize_name, CowRcStr, Parser};
18pub use cssparser::{SourceLocation, Token};
19use num_traits::Zero;
20use precomputed_hash::PrecomputedHash;
21use selectors::parser::SelectorParseErrorKind;
22use std::fmt::{self, Debug, Write};
23use style_traits::{CssString, CssWriter, ParseError, StyleParseErrorKind, ToCss};
24use thin_vec::ThinVec;
25use to_shmem::impl_trivial_to_shmem;
26
27pub use crate::url::CssUrl;
28
29pub mod animated;
30pub mod computed;
31pub mod distance;
32pub mod generics;
33pub mod resolved;
34pub mod specified;
35pub mod tagged_numeric;
36
37/// A CSS float value.
38pub type CSSFloat = f32;
39
40/// Normalizes a float value to zero after a set of operations that might turn
41/// it into NaN.
42#[inline]
43pub fn normalize(v: CSSFloat) -> CSSFloat {
44    if v.is_nan() {
45        0.0
46    } else {
47        v
48    }
49}
50
51/// Computes the minimum value of the two floats. The CSS Values and Units definition
52/// for min() considers -0 to be less than +0 (whereas Rust considers them equal).
53/// https://drafts.csswg.org/css-values-4/#css-signed-zero
54#[inline]
55pub fn calc_min(a: CSSFloat, b: CSSFloat) -> CSSFloat {
56    match (a.is_sign_negative(), b.is_sign_negative()) {
57        (true, false) => a,
58        (false, true) => b,
59        _ => a.min(b),
60    }
61}
62
63/// Computes the maximum value of the two floats. The CSS Values and Units definition
64/// for max() considers +0 to be greater than -0 (whereas Rust considers them equal).
65/// https://drafts.csswg.org/css-values-4/#css-signed-zero
66#[inline]
67pub fn calc_max(a: CSSFloat, b: CSSFloat) -> CSSFloat {
68    match (a.is_sign_negative(), b.is_sign_negative()) {
69        (true, false) => b,
70        (false, true) => a,
71        _ => a.max(b),
72    }
73}
74
75/// Computes the sign of the given value. The CSS Values and Units definition for
76/// sign() returns +0 or -0 for an input of +0 or -0, respectively (whereas the
77/// Rust f32::signum() function returns +1 or -1, respectively).
78/// https://drafts.csswg.org/css-values-4/#funcdef-sign
79#[inline]
80pub fn calc_sign(value: CSSFloat) -> CSSFloat {
81    if value.is_nan() {
82        f32::NAN
83    } else if value.is_zero() {
84        value
85    } else if value.is_sign_negative() {
86        -1.0
87    } else {
88        1.0
89    }
90}
91
92/// A CSS integer value.
93pub type CSSInteger = i32;
94
95/// Serialize an identifier which is represented as an atom.
96#[cfg(feature = "gecko")]
97pub fn serialize_atom_identifier<W>(ident: &Atom, dest: &mut W) -> fmt::Result
98where
99    W: Write,
100{
101    ident.with_str(|s| serialize_identifier(s, dest))
102}
103
104/// Serialize an identifier which is represented as an atom.
105#[cfg(feature = "servo")]
106pub fn serialize_atom_identifier<Static, W>(
107    ident: &::string_cache::Atom<Static>,
108    dest: &mut W,
109) -> fmt::Result
110where
111    Static: string_cache::StaticAtomSet,
112    W: Write,
113{
114    serialize_identifier(&ident, dest)
115}
116
117/// Serialize a name which is represented as an Atom.
118#[cfg(feature = "gecko")]
119pub fn serialize_atom_name<W>(ident: &Atom, dest: &mut W) -> fmt::Result
120where
121    W: Write,
122{
123    ident.with_str(|s| serialize_name(s, dest))
124}
125
126/// Serialize a name which is represented as an Atom.
127#[cfg(feature = "servo")]
128pub fn serialize_atom_name<Static, W>(
129    ident: &::string_cache::Atom<Static>,
130    dest: &mut W,
131) -> fmt::Result
132where
133    Static: string_cache::StaticAtomSet,
134    W: Write,
135{
136    serialize_name(&ident, dest)
137}
138
139/// Serialize a number with calc, and NaN/infinity handling (if enabled)
140pub fn serialize_number<W>(v: f32, dest: &mut CssWriter<W>) -> fmt::Result
141where
142    W: Write,
143{
144    serialize_specified_dimension(v, "", /* was_calc = */ false, dest)
145}
146
147/// Serialize a specified dimension with unit, calc, and NaN/infinity handling (if enabled)
148pub fn serialize_specified_dimension<W>(
149    v: f32,
150    unit: &str,
151    was_calc: bool,
152    dest: &mut CssWriter<W>,
153) -> fmt::Result
154where
155    W: Write,
156{
157    if was_calc {
158        dest.write_str("calc(")?;
159    }
160
161    if !v.is_finite() {
162        // https://drafts.csswg.org/css-values/#calc-error-constants:
163        // "While not technically numbers, these keywords act as numeric values,
164        // similar to e and pi. Thus to get an infinite length, for example,
165        // requires an expression like calc(infinity * 1px)."
166
167        if v.is_nan() {
168            dest.write_str("NaN")?;
169        } else if v == f32::INFINITY {
170            dest.write_str("infinity")?;
171        } else if v == f32::NEG_INFINITY {
172            dest.write_str("-infinity")?;
173        }
174
175        if !unit.is_empty() {
176            dest.write_str(" * 1")?;
177        }
178    } else {
179        v.to_css(dest)?;
180    }
181
182    dest.write_str(unit)?;
183
184    if was_calc {
185        dest.write_char(')')?;
186    }
187    Ok(())
188}
189
190/// A CSS string stored as an `Atom`.
191#[repr(transparent)]
192#[derive(
193    Clone,
194    Debug,
195    Default,
196    Deref,
197    Eq,
198    Hash,
199    MallocSizeOf,
200    PartialEq,
201    SpecifiedValueInfo,
202    ToAnimatedValue,
203    ToComputedValue,
204    ToResolvedValue,
205    ToShmem,
206)]
207pub struct AtomString(pub Atom);
208
209#[cfg(feature = "servo")]
210impl AsRef<str> for AtomString {
211    fn as_ref(&self) -> &str {
212        &*self.0
213    }
214}
215
216impl Parse for AtomString {
217    fn parse(_: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
218        Ok(Self(Atom::from(input.expect_string()?.as_ref())))
219    }
220}
221
222impl cssparser::ToCss for AtomString {
223    fn to_css<W>(&self, dest: &mut W) -> fmt::Result
224    where
225        W: Write,
226    {
227        // Wrap in quotes to form a string literal
228        dest.write_char('"')?;
229        #[cfg(feature = "servo")]
230        {
231            cssparser::CssStringWriter::new(dest).write_str(self.as_ref())?;
232        }
233        #[cfg(feature = "gecko")]
234        {
235            self.0
236                .with_str(|s| cssparser::CssStringWriter::new(dest).write_str(s))?;
237        }
238        dest.write_char('"')
239    }
240}
241
242impl style_traits::ToCss for AtomString {
243    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
244    where
245        W: Write,
246    {
247        cssparser::ToCss::to_css(self, dest)
248    }
249}
250
251impl PrecomputedHash for AtomString {
252    #[inline]
253    fn precomputed_hash(&self) -> u32 {
254        self.0.precomputed_hash()
255    }
256}
257
258impl From<&str> for AtomString {
259    #[inline]
260    fn from(string: &str) -> Self {
261        Self(Atom::from(string))
262    }
263}
264
265/// A generic CSS `<ident>` stored as an `Atom`.
266#[cfg(feature = "servo")]
267#[repr(transparent)]
268#[derive(Deref)]
269pub struct GenericAtomIdent<Set>(pub string_cache::Atom<Set>)
270where
271    Set: string_cache::StaticAtomSet;
272
273/// A generic CSS `<ident>` stored as an `Atom`, for the default atom set.
274#[cfg(feature = "servo")]
275pub type AtomIdent = GenericAtomIdent<stylo_atoms::AtomStaticSet>;
276
277#[cfg(feature = "servo")]
278impl<Set: string_cache::StaticAtomSet> style_traits::SpecifiedValueInfo for GenericAtomIdent<Set> {}
279
280#[cfg(feature = "servo")]
281impl<Set: string_cache::StaticAtomSet> Default for GenericAtomIdent<Set> {
282    fn default() -> Self {
283        Self(string_cache::Atom::default())
284    }
285}
286
287#[cfg(feature = "servo")]
288impl<Set: string_cache::StaticAtomSet> std::fmt::Debug for GenericAtomIdent<Set> {
289    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
290        self.0.fmt(f)
291    }
292}
293
294#[cfg(feature = "servo")]
295impl<Set: string_cache::StaticAtomSet> std::hash::Hash for GenericAtomIdent<Set> {
296    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
297        self.0.hash(state)
298    }
299}
300
301#[cfg(feature = "servo")]
302impl<Set: string_cache::StaticAtomSet> Eq for GenericAtomIdent<Set> {}
303
304#[cfg(feature = "servo")]
305impl<Set: string_cache::StaticAtomSet> PartialEq for GenericAtomIdent<Set> {
306    fn eq(&self, other: &Self) -> bool {
307        self.0 == other.0
308    }
309}
310
311#[cfg(feature = "servo")]
312impl<Set: string_cache::StaticAtomSet> Clone for GenericAtomIdent<Set> {
313    fn clone(&self) -> Self {
314        Self(self.0.clone())
315    }
316}
317
318#[cfg(feature = "servo")]
319impl<Set: string_cache::StaticAtomSet> to_shmem::ToShmem for GenericAtomIdent<Set> {
320    fn to_shmem(&self, builder: &mut to_shmem::SharedMemoryBuilder) -> to_shmem::Result<Self> {
321        use std::mem::ManuallyDrop;
322
323        let atom = self.0.to_shmem(builder)?;
324        Ok(ManuallyDrop::new(Self(ManuallyDrop::into_inner(atom))))
325    }
326}
327
328#[cfg(feature = "servo")]
329impl<Set: string_cache::StaticAtomSet> malloc_size_of::MallocSizeOf for GenericAtomIdent<Set> {
330    fn size_of(&self, ops: &mut malloc_size_of::MallocSizeOfOps) -> usize {
331        self.0.size_of(ops)
332    }
333}
334
335#[cfg(feature = "servo")]
336impl<Set: string_cache::StaticAtomSet> cssparser::ToCss for GenericAtomIdent<Set> {
337    fn to_css<W>(&self, dest: &mut W) -> fmt::Result
338    where
339        W: Write,
340    {
341        serialize_atom_identifier(&self.0, dest)
342    }
343}
344
345#[cfg(feature = "servo")]
346impl<Set: string_cache::StaticAtomSet> style_traits::ToCss for GenericAtomIdent<Set> {
347    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
348    where
349        W: Write,
350    {
351        serialize_atom_identifier(&self.0, dest)
352    }
353}
354
355#[cfg(feature = "servo")]
356impl<Set: string_cache::StaticAtomSet> PrecomputedHash for GenericAtomIdent<Set> {
357    #[inline]
358    fn precomputed_hash(&self) -> u32 {
359        self.0.precomputed_hash()
360    }
361}
362
363#[cfg(feature = "servo")]
364impl<'a, Set: string_cache::StaticAtomSet> From<&'a str> for GenericAtomIdent<Set> {
365    #[inline]
366    fn from(string: &str) -> Self {
367        Self(string_cache::Atom::from(string))
368    }
369}
370
371#[cfg(feature = "servo")]
372impl<Set: string_cache::StaticAtomSet> std::borrow::Borrow<string_cache::Atom<Set>>
373    for GenericAtomIdent<Set>
374{
375    #[inline]
376    fn borrow(&self) -> &string_cache::Atom<Set> {
377        &self.0
378    }
379}
380
381#[cfg(feature = "servo")]
382impl<Set: string_cache::StaticAtomSet> GenericAtomIdent<Set> {
383    /// Constructs a new GenericAtomIdent.
384    #[inline]
385    pub fn new(atom: string_cache::Atom<Set>) -> Self {
386        Self(atom)
387    }
388
389    /// Cast an atom ref to an AtomIdent ref.
390    #[inline]
391    pub fn cast<'a>(atom: &'a string_cache::Atom<Set>) -> &'a Self {
392        let ptr = atom as *const _ as *const Self;
393        // safety: repr(transparent)
394        unsafe { &*ptr }
395    }
396}
397
398/// A CSS `<ident>` stored as an `Atom`.
399#[cfg(feature = "gecko")]
400#[repr(transparent)]
401#[derive(
402    Clone, Debug, Default, Deref, Eq, Hash, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToShmem,
403)]
404pub struct AtomIdent(pub Atom);
405
406#[cfg(feature = "gecko")]
407impl cssparser::ToCss for AtomIdent {
408    fn to_css<W>(&self, dest: &mut W) -> fmt::Result
409    where
410        W: Write,
411    {
412        serialize_atom_identifier(&self.0, dest)
413    }
414}
415
416#[cfg(feature = "gecko")]
417impl style_traits::ToCss for AtomIdent {
418    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
419    where
420        W: Write,
421    {
422        cssparser::ToCss::to_css(self, dest)
423    }
424}
425
426#[cfg(feature = "gecko")]
427impl PrecomputedHash for AtomIdent {
428    #[inline]
429    fn precomputed_hash(&self) -> u32 {
430        self.0.precomputed_hash()
431    }
432}
433
434#[cfg(feature = "gecko")]
435impl From<&str> for AtomIdent {
436    #[inline]
437    fn from(string: &str) -> Self {
438        Self(Atom::from(string))
439    }
440}
441
442#[cfg(feature = "gecko")]
443impl AtomIdent {
444    /// Constructs a new AtomIdent.
445    #[inline]
446    pub fn new(atom: Atom) -> Self {
447        Self(atom)
448    }
449
450    /// Like `Atom::with` but for `AtomIdent`.
451    pub unsafe fn with<F, R>(ptr: *const crate::gecko_bindings::structs::nsAtom, callback: F) -> R
452    where
453        F: FnOnce(&Self) -> R,
454    {
455        unsafe {
456            Atom::with(ptr, |atom: &Atom| {
457                // safety: repr(transparent)
458                let atom = atom as *const Atom as *const AtomIdent;
459                callback(&*atom)
460            })
461        }
462    }
463
464    /// Cast an atom ref to an AtomIdent ref.
465    #[inline]
466    pub fn cast(atom: &Atom) -> &Self {
467        let ptr = atom as *const _ as *const Self;
468        // safety: repr(transparent)
469        unsafe { &*ptr }
470    }
471}
472
473#[cfg(feature = "gecko")]
474impl std::borrow::Borrow<crate::gecko_string_cache::WeakAtom> for AtomIdent {
475    #[inline]
476    fn borrow(&self) -> &crate::gecko_string_cache::WeakAtom {
477        self.0.borrow()
478    }
479}
480
481/// Serialize a value into percentage.
482pub fn serialize_percentage<W>(value: CSSFloat, dest: &mut CssWriter<W>) -> fmt::Result
483where
484    W: Write,
485{
486    serialize_specified_dimension(value * 100., "%", /* was_calc = */ false, dest)
487}
488
489/// Serialize a value into normalized (no NaN/inf serialization) percentage.
490pub fn serialize_normalized_percentage<W>(value: CSSFloat, dest: &mut CssWriter<W>) -> fmt::Result
491where
492    W: Write,
493{
494    (value * 100.).to_css(dest)?;
495    dest.write_char('%')
496}
497
498/// Reify a percentage.
499pub fn reify_percentage(value: CSSFloat, dest: &mut ThinVec<TypedValue>) -> Result<(), ()> {
500    let numeric_value = NumericValue::Unit(UnitValue {
501        numeric_type: NumericType::percent(),
502        value: value * 100.,
503        unit: CssString::from("percent"),
504    });
505
506    dest.push(TypedValue::Numeric(numeric_value));
507    Ok(())
508}
509
510/// Convenience void type to disable some properties and values through types.
511#[derive(
512    Clone,
513    Copy,
514    Debug,
515    Deserialize,
516    MallocSizeOf,
517    PartialEq,
518    Serialize,
519    SpecifiedValueInfo,
520    ToAnimatedValue,
521    ToComputedValue,
522    ToCss,
523    ToResolvedValue,
524)]
525pub enum Impossible {}
526
527// FIXME(nox): This should be derived but the derive code cannot cope
528// with uninhabited enums.
529impl ComputeSquaredDistance for Impossible {
530    #[inline]
531    fn compute_squared_distance(&self, _other: &Self) -> Result<SquaredDistance, ()> {
532        match *self {}
533    }
534}
535
536impl_trivial_to_shmem!(Impossible);
537
538impl Parse for Impossible {
539    fn parse(_context: &ParserContext, _input: &mut Parser) -> Result<Self, ParseError> {
540        Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError))
541    }
542}
543
544/// A struct representing one of two kinds of values.
545#[derive(
546    Animate,
547    Clone,
548    ComputeSquaredDistance,
549    Copy,
550    MallocSizeOf,
551    PartialEq,
552    Parse,
553    SpecifiedValueInfo,
554    ToAnimatedValue,
555    ToAnimatedZero,
556    ToComputedValue,
557    ToCss,
558    ToResolvedValue,
559    ToShmem,
560)]
561pub enum Either<A, B> {
562    /// The first value.
563    First(A),
564    /// The second kind of value.
565    Second(B),
566}
567
568impl<A: Debug, B: Debug> Debug for Either<A, B> {
569    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
570        match *self {
571            Either::First(ref v) => v.fmt(f),
572            Either::Second(ref v) => v.fmt(f),
573        }
574    }
575}
576
577/// <https://drafts.csswg.org/css-values-4/#custom-idents>
578#[derive(
579    Clone,
580    Debug,
581    Default,
582    Deserialize,
583    Eq,
584    Hash,
585    MallocSizeOf,
586    PartialEq,
587    Serialize,
588    SpecifiedValueInfo,
589    ToAnimatedValue,
590    ToComputedValue,
591    ToResolvedValue,
592    ToShmem,
593)]
594#[repr(C)]
595pub struct CustomIdent(pub Atom);
596
597impl CustomIdent {
598    /// Parse a <custom-ident>
599    ///
600    /// TODO(zrhoffman, bug 1844501): Use CustomIdent::parse in more places instead of
601    /// CustomIdent::from_ident.
602    pub fn parse(input: &mut Parser, invalid: &[&str]) -> Result<Self, ParseError> {
603        let ident = input.expect_ident()?;
604        CustomIdent::from_ident(ident, invalid)
605    }
606
607    /// Parse an already-tokenizer identifier
608    pub fn from_ident<'i>(ident: &CowRcStr<'i>, excluding: &[&str]) -> Result<Self, ParseError> {
609        if !Self::is_valid(ident, excluding) {
610            return Err(ParseError::custom(SelectorParseErrorKind::UnexpectedIdent));
611        }
612        if excluding.iter().any(|s| ident.eq_ignore_ascii_case(s)) {
613            Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError))
614        } else {
615            Ok(CustomIdent(Atom::from(ident.as_ref())))
616        }
617    }
618
619    fn is_valid(ident: &str, excluding: &[&str]) -> bool {
620        use crate::properties::CSSWideKeyword;
621        // https://drafts.csswg.org/css-values-4/#custom-idents:
622        //
623        //     The CSS-wide keywords are not valid <custom-ident>s. The default
624        //     keyword is reserved and is also not a valid <custom-ident>.
625        if CSSWideKeyword::from_ident(ident).is_ok() || ident.eq_ignore_ascii_case("default") {
626            return false;
627        }
628
629        // https://drafts.csswg.org/css-values-4/#custom-idents:
630        //
631        //     Excluded keywords are excluded in all ASCII case permutations.
632        !excluding.iter().any(|s| ident.eq_ignore_ascii_case(s))
633    }
634}
635
636impl ToCss for CustomIdent {
637    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
638    where
639        W: Write,
640    {
641        serialize_atom_identifier(&self.0, dest)
642    }
643}
644
645impl ToTyped for CustomIdent {
646    fn to_typed(&self, dest: &mut ThinVec<TypedValue>) -> Result<(), ()> {
647        // This shouldn't escape identifiers. See bug 2023533.
648        let s = ToCss::to_css_cssstring(self);
649        dest.push(TypedValue::Keyword(KeywordValue(s)));
650        Ok(())
651    }
652}
653
654/// <https://www.w3.org/TR/css-values-4/#dashed-idents>
655/// This is simply an Atom, but will only parse if the identifier starts with "--".
656#[repr(transparent)]
657#[derive(
658    Clone,
659    Debug,
660    Eq,
661    Hash,
662    MallocSizeOf,
663    PartialEq,
664    SpecifiedValueInfo,
665    ToAnimatedValue,
666    ToComputedValue,
667    ToResolvedValue,
668    ToShmem,
669    Serialize,
670    Deserialize,
671)]
672pub struct DashedIdent(pub Atom);
673
674impl DashedIdent {
675    /// Parse an already-tokenizer identifier
676    pub fn from_ident<'i>(ident: &CowRcStr<'i>) -> Result<Self, ParseError> {
677        if !ident.starts_with("--") {
678            return Err(ParseError::custom(SelectorParseErrorKind::UnexpectedIdent));
679        }
680        Ok(Self(Atom::from(ident.as_ref())))
681    }
682
683    /// Special value for internal use. Useful where we can't use Option<>.
684    pub fn empty() -> Self {
685        Self(atom!(""))
686    }
687
688    /// Check for special internal value.
689    pub fn is_empty(&self) -> bool {
690        self.0 == atom!("")
691    }
692
693    /// Returns an atom with the same value, but without the starting "--".
694    ///
695    /// # Panics
696    ///
697    /// Panics when used on the special `DashedIdent::empty()`.
698    pub(crate) fn undashed(&self) -> Atom {
699        assert!(!self.is_empty(), "Can't undash the empty DashedIdent");
700        #[cfg(feature = "gecko")]
701        let name = &self.0.as_slice()[2..];
702        #[cfg(feature = "servo")]
703        let name = &self.0[2..];
704        Atom::from(name)
705    }
706}
707
708impl IsTreeScoped for DashedIdent {
709    fn is_tree_scoped(&self) -> bool {
710        !self.is_empty()
711    }
712}
713
714impl Parse for DashedIdent {
715    fn parse(_: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
716        let ident = input.expect_ident()?;
717        Self::from_ident(ident)
718    }
719}
720
721impl ToCss for DashedIdent {
722    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
723    where
724        W: Write,
725    {
726        serialize_atom_identifier(&self.0, dest)
727    }
728}
729
730/// The <keyframes-name>.
731///
732/// <https://drafts.csswg.org/css-animations/#typedef-keyframes-name>
733///
734/// We use a single atom for this. Empty atom represents `none` animation.
735#[repr(transparent)]
736#[derive(
737    Clone,
738    Debug,
739    Eq,
740    Hash,
741    PartialEq,
742    MallocSizeOf,
743    SpecifiedValueInfo,
744    ToComputedValue,
745    ToResolvedValue,
746    ToShmem,
747)]
748pub struct KeyframesName(Atom);
749
750impl KeyframesName {
751    /// <https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-name>
752    pub fn from_ident(value: &str) -> Self {
753        Self(Atom::from(value))
754    }
755
756    /// Returns the `none` value.
757    pub fn none() -> Self {
758        Self(atom!(""))
759    }
760
761    /// Returns whether this is the special `none` value.
762    pub fn is_none(&self) -> bool {
763        self.0 == atom!("")
764    }
765
766    /// Create a new KeyframesName from Atom.
767    #[cfg(feature = "gecko")]
768    pub fn from_atom(atom: Atom) -> Self {
769        Self(atom)
770    }
771
772    /// The name as an Atom
773    pub fn as_atom(&self) -> &Atom {
774        &self.0
775    }
776}
777
778impl Parse for KeyframesName {
779    fn parse(_: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
780        Ok(match *input.next()? {
781            Token::Ident(ref s) => Self(CustomIdent::from_ident(s, &["none"])?.0),
782            // Note that empty <string> should be rejected.
783            Token::QuotedString(ref s) if !s.as_ref().is_empty() => Self(Atom::from(s.as_ref())),
784            _ => return Err(ParseError::unexpected_token()),
785        })
786    }
787}
788
789impl ToCss for KeyframesName {
790    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
791    where
792        W: Write,
793    {
794        if self.is_none() {
795            return dest.write_str("none");
796        }
797
798        fn serialize<W: Write>(string: &str, dest: &mut CssWriter<W>) -> fmt::Result {
799            if CustomIdent::is_valid(string, &["none"]) {
800                serialize_identifier(string, dest)
801            } else {
802                string.to_css(dest)
803            }
804        }
805
806        #[cfg(feature = "gecko")]
807        return self.0.with_str(|s| serialize(s, dest));
808
809        #[cfg(feature = "servo")]
810        return serialize(self.0.as_ref(), dest);
811    }
812}
813
814impl ToTyped for KeyframesName {
815    fn to_typed(&self, dest: &mut ThinVec<TypedValue>) -> Result<(), ()> {
816        let s = ToCss::to_css_cssstring(self);
817        dest.push(TypedValue::Keyword(KeywordValue(s)));
818        Ok(())
819    }
820}