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