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