Change ToCss to take a CssWriter<W>

This more concrete wrapper type can write a prefix the very first time something
is written to it. This allows removing plenty of useless monomorphisations caused
by the former W/SequenceWriter<W> pair of types.
This commit is contained in:
Anthony Ramine 2018-01-22 19:58:01 +01:00
parent 3672856efa
commit cd8f96cc9e
89 changed files with 873 additions and 533 deletions

View file

@ -93,12 +93,11 @@ impl MediaListMethods for MediaList {
// https://drafts.csswg.org/cssom/#dom-medialist-item // https://drafts.csswg.org/cssom/#dom-medialist-item
fn Item(&self, index: u32) -> Option<DOMString> { fn Item(&self, index: u32) -> Option<DOMString> {
let guard = self.shared_lock().read(); let guard = self.shared_lock().read();
self.media_queries.read_with(&guard).media_queries self.media_queries
.get(index as usize).and_then(|query| { .read_with(&guard)
let mut s = String::new(); .media_queries
query.to_css(&mut s).unwrap(); .get(index as usize)
Some(DOMString::from_string(s)) .map(|query| query.to_css_string().into())
})
} }
// https://drafts.csswg.org/cssom/#dom-medialist-item // https://drafts.csswg.org/cssom/#dom-medialist-item

View file

@ -83,9 +83,7 @@ impl MediaQueryList {
impl MediaQueryListMethods for MediaQueryList { impl MediaQueryListMethods for MediaQueryList {
// https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-media // https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-media
fn Media(&self) -> DOMString { fn Media(&self) -> DOMString {
let mut s = String::new(); self.media_query_list.to_css_string().into()
self.media_query_list.to_css(&mut s).unwrap();
DOMString::from_string(s)
} }
// https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-matches // https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-matches

View file

@ -20,7 +20,8 @@ use std::borrow::Cow;
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use std::ops::Range; use std::ops::Range;
use str::CssStringWriter; use str::CssStringWriter;
use style_traits::{Comma, OneOrMoreSeparated, ParseError, StyleParseErrorKind, ToCss}; use style_traits::{Comma, CssWriter, OneOrMoreSeparated, ParseError};
use style_traits::{StyleParseErrorKind, ToCss};
use values::CustomIdent; use values::CustomIdent;
/// Parse a counter style name reference. /// Parse a counter style name reference.
@ -231,12 +232,12 @@ macro_rules! counter_style_descriptors {
impl ToCssWithGuard for CounterStyleRuleData { impl ToCssWithGuard for CounterStyleRuleData {
fn to_css(&self, _guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result { fn to_css(&self, _guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result {
dest.write_str("@counter-style ")?; dest.write_str("@counter-style ")?;
self.name.to_css(dest)?; self.name.to_css(&mut CssWriter::new(dest))?;
dest.write_str(" {\n")?; dest.write_str(" {\n")?;
$( $(
if let Some(ref value) = self.$ident { if let Some(ref value) = self.$ident {
dest.write_str(concat!(" ", $name, ": "))?; dest.write_str(concat!(" ", $name, ": "))?;
ToCss::to_css(value, dest)?; ToCss::to_css(value, &mut CssWriter::new(dest))?;
dest.write_str(";\n")?; dest.write_str(";\n")?;
} }
)+ )+
@ -362,7 +363,10 @@ impl Parse for System {
} }
impl ToCss for System { impl ToCss for System {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self { match *self {
System::Cyclic => dest.write_str("cyclic"), System::Cyclic => dest.write_str("cyclic"),
System::Numeric => dest.write_str("numeric"), System::Numeric => dest.write_str("numeric"),
@ -410,7 +414,10 @@ impl Parse for Symbol {
} }
impl ToCss for Symbol { impl ToCss for Symbol {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self { match *self {
Symbol::String(ref s) => s.to_css(dest), Symbol::String(ref s) => s.to_css(dest),
Symbol::Ident(ref s) => serialize_identifier(s, dest), Symbol::Ident(ref s) => serialize_identifier(s, dest),
@ -477,7 +484,10 @@ fn parse_bound<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Option<i32>, ParseE
} }
impl ToCss for Ranges { impl ToCss for Ranges {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
let mut iter = self.0.iter(); let mut iter = self.0.iter();
if let Some(first) = iter.next() { if let Some(first) = iter.next() {
range_to_css(first, dest)?; range_to_css(first, dest)?;
@ -492,14 +502,19 @@ impl ToCss for Ranges {
} }
} }
fn range_to_css<W>(range: &Range<Option<i32>>, dest: &mut W) -> fmt::Result fn range_to_css<W>(range: &Range<Option<i32>>, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write { where
W: Write,
{
bound_to_css(range.start, dest)?; bound_to_css(range.start, dest)?;
dest.write_char(' ')?; dest.write_char(' ')?;
bound_to_css(range.end, dest) bound_to_css(range.end, dest)
} }
fn bound_to_css<W>(range: Option<i32>, dest: &mut W) -> fmt::Result where W: fmt::Write { fn bound_to_css<W>(range: Option<i32>, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if let Some(finite) = range { if let Some(finite) = range {
finite.to_css(dest) finite.to_css(dest)
} else { } else {
@ -556,7 +571,10 @@ impl Parse for Symbols {
} }
impl ToCss for Symbols { impl ToCss for Symbols {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
let mut iter = self.0.iter(); let mut iter = self.0.iter();
let first = iter.next().expect("expected at least one symbol"); let first = iter.next().expect("expected at least one symbol");
first.to_css(dest)?; first.to_css(dest)?;

View file

@ -17,9 +17,9 @@ use smallvec::SmallVec;
#[allow(unused_imports)] use std::ascii::AsciiExt; #[allow(unused_imports)] use std::ascii::AsciiExt;
use std::borrow::{Borrow, Cow}; use std::borrow::{Borrow, Cow};
use std::cmp; use std::cmp;
use std::fmt; use std::fmt::{self, Write};
use std::hash::Hash; use std::hash::Hash;
use style_traits::{ToCss, StyleParseErrorKind, ParseError}; use style_traits::{CssWriter, ToCss, StyleParseErrorKind, ParseError};
/// A custom property name is just an `Atom`. /// A custom property name is just an `Atom`.
/// ///
@ -53,8 +53,9 @@ pub struct VariableValue {
} }
impl ToCss for SpecifiedValue { impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write, where
W: Write,
{ {
dest.write_str(&self.css) dest.write_str(&self.css)
} }

View file

@ -22,7 +22,8 @@ use selectors::parser::SelectorParseErrorKind;
use shared_lock::{SharedRwLockReadGuard, ToCssWithGuard}; use shared_lock::{SharedRwLockReadGuard, ToCssWithGuard};
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use str::CssStringWriter; use str::CssStringWriter;
use style_traits::{Comma, OneOrMoreSeparated, ParseError, StyleParseErrorKind, ToCss}; use style_traits::{Comma, CssWriter, OneOrMoreSeparated, ParseError};
use style_traits::{StyleParseErrorKind, ToCss};
use values::computed::font::FamilyName; use values::computed::font::FamilyName;
use values::specified::url::SpecifiedUrl; use values::specified::url::SpecifiedUrl;
@ -55,8 +56,9 @@ pub struct UrlSource {
} }
impl ToCss for UrlSource { impl ToCss for UrlSource {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write, where
W: Write,
{ {
self.url.to_css(dest) self.url.to_css(dest)
} }
@ -278,7 +280,7 @@ macro_rules! font_face_descriptors_common {
$( $(
if let Some(ref value) = self.$ident { if let Some(ref value) = self.$ident {
dest.write_str(concat!(" ", $name, ": "))?; dest.write_str(concat!(" ", $name, ": "))?;
ToCss::to_css(value, dest)?; ToCss::to_css(value, &mut CssWriter::new(dest))?;
dest.write_str(";\n")?; dest.write_str(";\n")?;
} }
)* )*

View file

@ -24,7 +24,7 @@ use std::fmt::{self, Write};
use std::sync::atomic::{AtomicBool, AtomicIsize, AtomicUsize, Ordering}; use std::sync::atomic::{AtomicBool, AtomicIsize, AtomicUsize, Ordering};
use str::starts_with_ignore_ascii_case; use str::starts_with_ignore_ascii_case;
use string_cache::Atom; use string_cache::Atom;
use style_traits::{CSSPixel, DevicePixel}; use style_traits::{CSSPixel, CssWriter, DevicePixel};
use style_traits::{ToCss, ParseError, StyleParseErrorKind}; use style_traits::{ToCss, ParseError, StyleParseErrorKind};
use style_traits::viewport::ViewportConstraints; use style_traits::viewport::ViewportConstraints;
use stylesheets::Origin; use stylesheets::Origin;
@ -236,7 +236,7 @@ pub struct Expression {
} }
impl ToCss for Expression { impl ToCss for Expression {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write, where W: fmt::Write,
{ {
dest.write_str("(")?; dest.write_str("(")?;
@ -408,7 +408,7 @@ impl MediaExpressionValue {
} }
impl MediaExpressionValue { impl MediaExpressionValue {
fn to_css<W>(&self, dest: &mut W, for_expr: &Expression) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>, for_expr: &Expression) -> fmt::Result
where W: fmt::Write, where W: fmt::Write,
{ {
match *self { match *self {

View file

@ -16,7 +16,7 @@ use selectors::parser::{self as selector_parser, Selector, Visit, SelectorParseE
use selectors::visitor::SelectorVisitor; use selectors::visitor::SelectorVisitor;
use std::fmt; use std::fmt;
use string_cache::{Atom, Namespace, WeakAtom, WeakNamespace}; use string_cache::{Atom, Namespace, WeakAtom, WeakNamespace};
use style_traits::{ParseError, StyleParseErrorKind, ToCss as ToCss_}; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss as ToCss_};
pub use gecko::pseudo_element::{PseudoElement, EAGER_PSEUDOS, EAGER_PSEUDO_COUNT, PSEUDO_COUNT}; pub use gecko::pseudo_element::{PseudoElement, EAGER_PSEUDOS, EAGER_PSEUDO_COUNT, PSEUDO_COUNT};
pub use gecko::snapshot::SnapshotMap; pub use gecko::snapshot::SnapshotMap;
@ -86,12 +86,12 @@ impl ToCss for NonTSPseudoClass {
}, )* }, )*
NonTSPseudoClass::MozLocaleDir(ref dir) => { NonTSPseudoClass::MozLocaleDir(ref dir) => {
dest.write_str(":-moz-locale-dir(")?; dest.write_str(":-moz-locale-dir(")?;
dir.to_css(dest)?; dir.to_css(&mut CssWriter::new(dest))?;
return dest.write_char(')') return dest.write_char(')')
}, },
NonTSPseudoClass::Dir(ref dir) => { NonTSPseudoClass::Dir(ref dir) => {
dest.write_str(":dir(")?; dest.write_str(":dir(")?;
dir.to_css(dest)?; dir.to_css(&mut CssWriter::new(dest))?;
return dest.write_char(')') return dest.write_char(')')
}, },
NonTSPseudoClass::MozAny(ref selectors) => { NonTSPseudoClass::MozAny(ref selectors) => {

View file

@ -12,9 +12,9 @@ use gecko_bindings::sugar::refptr::RefPtr;
use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
use parser::ParserContext; use parser::ParserContext;
use servo_arc::{Arc, RawOffsetArc}; use servo_arc::{Arc, RawOffsetArc};
use std::fmt; use std::fmt::{self, Write};
use std::mem; use std::mem;
use style_traits::{ToCss, ParseError}; use style_traits::{CssWriter, ToCss, ParseError};
/// A specified url() value for gecko. Gecko does not eagerly resolve SpecifiedUrls. /// A specified url() value for gecko. Gecko does not eagerly resolve SpecifiedUrls.
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
@ -136,7 +136,10 @@ impl SpecifiedUrl {
} }
impl ToCss for SpecifiedUrl { impl ToCss for SpecifiedUrl {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("url(")?; dest.write_str("url(")?;
self.serialization.to_css(dest)?; self.serialization.to_css(dest)?;
dest.write_str(")") dest.write_str(")")

View file

@ -134,8 +134,8 @@ pub mod traversal_flags;
#[allow(non_camel_case_types)] #[allow(non_camel_case_types)]
pub mod values; pub mod values;
use std::fmt; use std::fmt::{self, Write};
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
#[cfg(feature = "gecko")] pub use gecko_string_cache as string_cache; #[cfg(feature = "gecko")] pub use gecko_string_cache as string_cache;
#[cfg(feature = "gecko")] pub use gecko_string_cache::Atom; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom;
@ -181,10 +181,12 @@ longhand_properties_idents!(reexport_computed_values);
/// Serializes as CSS a comma-separated list of any `T` that supports being /// Serializes as CSS a comma-separated list of any `T` that supports being
/// serialized as CSS. /// serialized as CSS.
pub fn serialize_comma_separated_list<W, T>(dest: &mut W, pub fn serialize_comma_separated_list<W, T>(
list: &[T]) dest: &mut CssWriter<W>,
-> fmt::Result list: &[T],
where W: fmt::Write, ) -> fmt::Result
where
W: Write,
T: ToCss, T: ToCss,
{ {
if list.is_empty() { if list.is_empty() {

View file

@ -91,8 +91,11 @@ macro_rules! define_numbered_css_keyword_enum {
} }
} }
impl ::style_traits::values::ToCss for $name { impl ::style_traits::ToCss for $name {
fn to_css<W>(&self, dest: &mut W) -> ::std::fmt::Result fn to_css<W>(
&self,
dest: &mut ::style_traits::CssWriter<W>,
) -> ::std::fmt::Result
where where
W: ::std::fmt::Write, W: ::std::fmt::Write,
{ {

View file

@ -14,9 +14,9 @@ use error_reporting::{ContextualParseError, ParseErrorReporter};
use parser::{ParserContext, ParserErrorContext}; use parser::{ParserContext, ParserErrorContext};
use selectors::parser::SelectorParseErrorKind; use selectors::parser::SelectorParseErrorKind;
use serialize_comma_separated_list; use serialize_comma_separated_list;
use std::fmt; use std::fmt::{self, Write};
use str::string_as_ascii_lowercase; use str::string_as_ascii_lowercase;
use style_traits::{ToCss, ParseError, StyleParseErrorKind}; use style_traits::{CssWriter, ToCss, ParseError, StyleParseErrorKind};
use values::CustomIdent; use values::CustomIdent;
#[cfg(feature = "servo")] #[cfg(feature = "servo")]
@ -33,8 +33,9 @@ pub struct MediaList {
} }
impl ToCss for MediaList { impl ToCss for MediaList {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write where
W: Write,
{ {
serialize_comma_separated_list(dest, &self.media_queries) serialize_comma_separated_list(dest, &self.media_queries)
} }
@ -86,8 +87,9 @@ impl MediaQuery {
} }
impl ToCss for MediaQuery { impl ToCss for MediaQuery {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write, where
W: Write,
{ {
if let Some(qual) = self.qualifier { if let Some(qual) = self.qualifier {
qual.to_css(dest)?; qual.to_css(dest)?;

View file

@ -16,11 +16,11 @@ use properties::animated_properties::AnimationValue;
use shared_lock::Locked; use shared_lock::Locked;
use smallbitvec::{self, SmallBitVec}; use smallbitvec::{self, SmallBitVec};
use smallvec::SmallVec; use smallvec::SmallVec;
use std::fmt; use std::fmt::{self, Write};
use std::iter::{DoubleEndedIterator, Zip}; use std::iter::{DoubleEndedIterator, Zip};
use std::slice::Iter; use std::slice::Iter;
use str::{CssString, CssStringBorrow, CssStringWriter}; use str::{CssString, CssStringBorrow, CssStringWriter};
use style_traits::{ToCss, ParseError, ParsingMode, StyleParseErrorKind}; use style_traits::{CssWriter, ParseError, ParsingMode, StyleParseErrorKind, ToCss};
use stylesheets::{CssRuleType, Origin, UrlExtraData}; use stylesheets::{CssRuleType, Origin, UrlExtraData};
use super::*; use super::*;
use values::computed::Context; use values::computed::Context;
@ -664,7 +664,7 @@ impl PropertyDeclarationBlock {
css.append_to(dest) css.append_to(dest)
}, },
Some(AppendableValue::DeclarationsForShorthand(_, decls)) => { Some(AppendableValue::DeclarationsForShorthand(_, decls)) => {
shorthand.longhands_to_css(decls, dest) shorthand.longhands_to_css(decls, &mut CssWriter::new(dest))
} }
_ => Ok(()) _ => Ok(())
} }
@ -845,7 +845,7 @@ impl PropertyDeclarationBlock {
} }
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
(_, Some(sys)) => { (_, Some(sys)) => {
sys.to_css(&mut v)?; sys.to_css(&mut CssWriter::new(&mut v))?;
AppendableValue::Css { AppendableValue::Css {
css: CssStringBorrow::from(&v), css: CssStringBorrow::from(&v),
with_variables: false, with_variables: false,
@ -951,10 +951,12 @@ pub enum AppendableValue<'a, I>
} }
/// Potentially appends whitespace after the first (property: value;) pair. /// Potentially appends whitespace after the first (property: value;) pair.
fn handle_first_serialization<W>(dest: &mut W, fn handle_first_serialization<W>(
is_first_serialization: &mut bool) dest: &mut W,
-> fmt::Result is_first_serialization: &mut bool,
where W: fmt::Write, ) -> fmt::Result
where
W: Write,
{ {
if !*is_first_serialization { if !*is_first_serialization {
dest.write_str(" ") dest.write_str(" ")
@ -980,7 +982,7 @@ where
decl.to_css(dest) decl.to_css(dest)
}, },
AppendableValue::DeclarationsForShorthand(shorthand, decls) => { AppendableValue::DeclarationsForShorthand(shorthand, decls) => {
shorthand.longhands_to_css(decls, dest) shorthand.longhands_to_css(decls, &mut CssWriter::new(dest))
} }
} }
} }
@ -999,7 +1001,7 @@ where
{ {
handle_first_serialization(dest, is_first_serialization)?; handle_first_serialization(dest, is_first_serialization)?;
property_name.to_css(dest)?; property_name.to_css(&mut CssWriter::new(dest))?;
dest.write_char(':')?; dest.write_char(':')?;
// for normal parsed values, add a space between key: and value // for normal parsed values, add a space between key: and value

View file

@ -82,8 +82,8 @@
need_animatable=need_animatable, **kwargs)"> need_animatable=need_animatable, **kwargs)">
#[allow(unused_imports)] #[allow(unused_imports)]
use smallvec::SmallVec; use smallvec::SmallVec;
use std::fmt; use std::fmt::{self, Write};
use style_traits::{Separator, ToCss}; use style_traits::{CssWriter, Separator, ToCss};
pub mod single_value { pub mod single_value {
#[allow(unused_imports)] #[allow(unused_imports)]
@ -154,8 +154,9 @@
} }
impl ToCss for computed_value::T { impl ToCss for computed_value::T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write, where
W: Write,
{ {
let mut iter = self.0.iter(); let mut iter = self.0.iter();
if let Some(val) = iter.next() { if let Some(val) = iter.next() {
@ -180,8 +181,9 @@
pub struct SpecifiedValue(pub Vec<single_value::SpecifiedValue>); pub struct SpecifiedValue(pub Vec<single_value::SpecifiedValue>);
impl ToCss for SpecifiedValue { impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write, where
W: Write,
{ {
let mut iter = self.0.iter(); let mut iter = self.0.iter();
if let Some(val) = iter.next() { if let Some(val) = iter.next() {
@ -682,11 +684,11 @@
#[allow(unused_imports)] #[allow(unused_imports)]
use selectors::parser::SelectorParseErrorKind; use selectors::parser::SelectorParseErrorKind;
#[allow(unused_imports)] #[allow(unused_imports)]
use std::fmt; use std::fmt::{self, Write};
#[allow(unused_imports)] #[allow(unused_imports)]
use style_traits::{ParseError, StyleParseErrorKind}; use style_traits::{ParseError, StyleParseErrorKind};
#[allow(unused_imports)] #[allow(unused_imports)]
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
pub struct Longhands { pub struct Longhands {
% for sub_property in shorthand.sub_properties: % for sub_property in shorthand.sub_properties:
@ -806,7 +808,10 @@
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
let rect = Rect::new( let rect = Rect::new(
% for side in ["top", "right", "bottom", "left"]: % for side in ["top", "right", "bottom", "left"]:
&self.${to_rust_ident(sub_property_pattern % side)}, &self.${to_rust_ident(sub_property_pattern % side)},

View file

@ -27,9 +27,9 @@ use selectors::parser::SelectorParseErrorKind;
use servo_arc::Arc; use servo_arc::Arc;
use smallvec::SmallVec; use smallvec::SmallVec;
use std::cmp; use std::cmp;
use std::fmt; use std::fmt::{self, Write};
#[cfg(feature = "gecko")] use hash::FnvHashMap; #[cfg(feature = "gecko")] use hash::FnvHashMap;
use style_traits::{ParseError, ToCss}; use style_traits::{CssWriter, ParseError, ToCss};
use super::ComputedValues; use super::ComputedValues;
use values::{CSSFloat, CustomIdent, Either}; use values::{CSSFloat, CustomIdent, Either};
use values::animated::{Animate, Procedure, ToAnimatedValue, ToAnimatedZero}; use values::animated::{Animate, Procedure, ToAnimatedValue, ToAnimatedZero};
@ -94,7 +94,10 @@ pub enum TransitionProperty {
} }
impl ToCss for TransitionProperty { impl ToCss for TransitionProperty {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self { match *self {
TransitionProperty::All => dest.write_str("all"), TransitionProperty::All => dest.write_str("all"),
TransitionProperty::Shorthand(ref id) => dest.write_str(id.name()), TransitionProperty::Shorthand(ref id) => dest.write_str(id.name()),

View file

@ -66,8 +66,8 @@ pub mod system_colors {
use cssparser::Parser; use cssparser::Parser;
use gecko_bindings::bindings::Gecko_GetLookAndFeelSystemColor; use gecko_bindings::bindings::Gecko_GetLookAndFeelSystemColor;
use gecko_bindings::structs::root::mozilla::LookAndFeel_ColorID; use gecko_bindings::structs::root::mozilla::LookAndFeel_ColorID;
use std::fmt; use std::fmt::{self, Write};
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use values::computed::{Context, ToComputedValue}; use values::computed::{Context, ToComputedValue};
pub type SystemColor = LookAndFeel_ColorID; pub type SystemColor = LookAndFeel_ColorID;
@ -77,7 +77,10 @@ pub mod system_colors {
malloc_size_of_is_0!(SystemColor); malloc_size_of_is_0!(SystemColor);
impl ToCss for SystemColor { impl ToCss for SystemColor {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
let s = match *self { let s = match *self {
% for color in system_colors + extra_colors: % for color in system_colors + extra_colors:
LookAndFeel_ColorID::eColorID_${to_rust_ident(color)} => "${color}", LookAndFeel_ColorID::eColorID_${to_rust_ident(color)} => "${color}",

View file

@ -23,8 +23,8 @@
pub mod computed_value { pub mod computed_value {
use cssparser; use cssparser;
use std::fmt; use std::fmt::{self, Write};
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
use values::specified::url::SpecifiedUrl; use values::specified::url::SpecifiedUrl;
@ -62,7 +62,10 @@
} }
impl ToCss for ContentItem { impl ToCss for ContentItem {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self { match *self {
ContentItem::String(ref s) => s.to_css(dest), ContentItem::String(ref s) => s.to_css(dest),
ContentItem::Counter(ref s, ref counter_style) => { ContentItem::Counter(ref s, ref counter_style) => {
@ -106,7 +109,10 @@
} }
impl ToCss for T { impl ToCss for T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self { match *self {
T::Normal => dest.write_str("normal"), T::Normal => dest.write_str("normal"),
T::None => dest.write_str("none"), T::None => dest.write_str("none"),
@ -232,8 +238,8 @@
<%helpers:longhand name="counter-increment" animation_value_type="discrete" <%helpers:longhand name="counter-increment" animation_value_type="discrete"
spec="https://drafts.csswg.org/css-lists/#propdef-counter-increment"> spec="https://drafts.csswg.org/css-lists/#propdef-counter-increment">
use std::fmt; use std::fmt::{self, Write};
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use values::CustomIdent; use values::CustomIdent;
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))] #[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
@ -241,16 +247,17 @@
pub struct SpecifiedValue(pub Vec<(CustomIdent, specified::Integer)>); pub struct SpecifiedValue(pub Vec<(CustomIdent, specified::Integer)>);
pub mod computed_value { pub mod computed_value {
use std::fmt; use std::fmt::{self, Write};
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use values::CustomIdent; use values::CustomIdent;
#[derive(Clone, Debug, MallocSizeOf, PartialEq)] #[derive(Clone, Debug, MallocSizeOf, PartialEq)]
pub struct T(pub Vec<(CustomIdent, i32)>); pub struct T(pub Vec<(CustomIdent, i32)>);
impl ToCss for T { impl ToCss for T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write, where
W: Write,
{ {
if self.0.is_empty() { if self.0.is_empty() {
return dest.write_str("none") return dest.write_str("none")
@ -292,10 +299,10 @@
computed_value::T(Vec::new()) computed_value::T(Vec::new())
} }
impl ToCss for SpecifiedValue { impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write, where
W: Write,
{ {
if self.0.is_empty() { if self.0.is_empty() {
return dest.write_str("none"); return dest.write_str("none");

View file

@ -193,8 +193,8 @@ ${helpers.predefined_type(
animation_value_type="discrete" animation_value_type="discrete"
spec="https://drafts.csswg.org/css-text-decor/#propdef-text-emphasis-style"> spec="https://drafts.csswg.org/css-text-decor/#propdef-text-emphasis-style">
use computed_values::writing_mode::T as WritingMode; use computed_values::writing_mode::T as WritingMode;
use std::fmt; use std::fmt::{self, Write};
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use unicode_segmentation::UnicodeSegmentation; use unicode_segmentation::UnicodeSegmentation;
@ -229,7 +229,7 @@ ${helpers.predefined_type(
} }
impl ToCss for KeywordValue { impl ToCss for KeywordValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
if let Some(fill) = self.fill() { if let Some(fill) = self.fill() {
if fill { if fill {
dest.write_str("filled")?; dest.write_str("filled")?;
@ -246,8 +246,12 @@ ${helpers.predefined_type(
Ok(()) Ok(())
} }
} }
impl ToCss for computed_value::KeywordValue { impl ToCss for computed_value::KeywordValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if self.fill { if self.fill {
dest.write_str("filled")?; dest.write_str("filled")?;
} else { } else {

View file

@ -16,10 +16,9 @@ use custom_properties::CustomPropertiesBuilder;
use servo_arc::{Arc, UniqueArc}; use servo_arc::{Arc, UniqueArc};
use smallbitvec::SmallBitVec; use smallbitvec::SmallBitVec;
use std::borrow::Cow; use std::borrow::Cow;
use std::{mem, ops};
use std::cell::RefCell; use std::cell::RefCell;
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use std::mem;
use std::ops;
#[cfg(feature = "servo")] use cssparser::RGBA; #[cfg(feature = "servo")] use cssparser::RGBA;
use cssparser::{CowRcStr, Parser, TokenSerializationType, serialize_identifier}; use cssparser::{CowRcStr, Parser, TokenSerializationType, serialize_identifier};
@ -40,7 +39,7 @@ use selector_parser::PseudoElement;
use selectors::parser::SelectorParseErrorKind; use selectors::parser::SelectorParseErrorKind;
#[cfg(feature = "servo")] use servo_config::prefs::PREFS; #[cfg(feature = "servo")] use servo_config::prefs::PREFS;
use shared_lock::StylesheetGuards; use shared_lock::StylesheetGuards;
use style_traits::{ParsingMode, ToCss, ParseError, StyleParseErrorKind}; use style_traits::{CssWriter, ParseError, ParsingMode, StyleParseErrorKind, ToCss};
use stylesheets::{CssRuleType, Origin, UrlExtraData}; use stylesheets::{CssRuleType, Origin, UrlExtraData};
#[cfg(feature = "servo")] use values::Either; #[cfg(feature = "servo")] use values::Either;
use values::generics::text::LineHeight; use values::generics::text::LineHeight;
@ -855,8 +854,13 @@ impl ShorthandId {
/// ///
/// Returns an error if writing to the stream fails, or if the declarations /// Returns an error if writing to the stream fails, or if the declarations
/// do not map to a shorthand. /// do not map to a shorthand.
pub fn longhands_to_css<'a, W, I>(&self, declarations: I, dest: &mut W) -> fmt::Result pub fn longhands_to_css<'a, W, I>(
where W: fmt::Write, &self,
declarations: I,
dest: &mut CssWriter<W>,
) -> fmt::Result
where
W: Write,
I: Iterator<Item=&'a PropertyDeclaration>, I: Iterator<Item=&'a PropertyDeclaration>,
{ {
match *self { match *self {
@ -1075,8 +1079,9 @@ impl UnparsedValue {
} }
impl<'a, T: ToCss> ToCss for DeclaredValue<'a, T> { impl<'a, T: ToCss> ToCss for DeclaredValue<'a, T> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write, where
W: Write,
{ {
match *self { match *self {
DeclaredValue::Value(ref inner) => inner.to_css(dest), DeclaredValue::Value(ref inner) => inner.to_css(dest),
@ -1104,8 +1109,9 @@ pub enum PropertyDeclarationId<'a> {
} }
impl<'a> ToCss for PropertyDeclarationId<'a> { impl<'a> ToCss for PropertyDeclarationId<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write, where
W: Write,
{ {
match *self { match *self {
PropertyDeclarationId::Longhand(id) => dest.write_str(id.name()), PropertyDeclarationId::Longhand(id) => dest.write_str(id.name()),
@ -1150,7 +1156,6 @@ impl<'a> PropertyDeclarationId<'a> {
match *self { match *self {
PropertyDeclarationId::Longhand(id) => id.name().into(), PropertyDeclarationId::Longhand(id) => id.name().into(),
PropertyDeclarationId::Custom(name) => { PropertyDeclarationId::Custom(name) => {
use std::fmt::Write;
let mut s = String::new(); let mut s = String::new();
write!(&mut s, "--{}", name).unwrap(); write!(&mut s, "--{}", name).unwrap();
s.into() s.into()
@ -1177,13 +1182,14 @@ pub enum PropertyId {
impl fmt::Debug for PropertyId { impl fmt::Debug for PropertyId {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
self.to_css(formatter) self.to_css(&mut CssWriter::new(formatter))
} }
} }
impl ToCss for PropertyId { impl ToCss for PropertyId {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write, where
W: Write,
{ {
match *self { match *self {
PropertyId::Longhand(id) => dest.write_str(id.name()), PropertyId::Longhand(id) => dest.write_str(id.name()),
@ -1331,7 +1337,6 @@ impl PropertyId {
PropertyId::LonghandAlias(id, _) | PropertyId::LonghandAlias(id, _) |
PropertyId::Longhand(id) => id.name().into(), PropertyId::Longhand(id) => id.name().into(),
PropertyId::Custom(ref name) => { PropertyId::Custom(ref name) => {
use std::fmt::Write;
let mut s = String::new(); let mut s = String::new();
write!(&mut s, "--{}", name).unwrap(); write!(&mut s, "--{}", name).unwrap();
s.into() s.into()
@ -1464,7 +1469,7 @@ pub enum PropertyDeclaration {
impl fmt::Debug for PropertyDeclaration { impl fmt::Debug for PropertyDeclaration {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.id().to_css(f)?; self.id().to_css(&mut CssWriter::new(f))?;
f.write_str(": ")?; f.write_str(": ")?;
// Because PropertyDeclaration::to_css requires CssStringWriter, we can't write // Because PropertyDeclaration::to_css requires CssStringWriter, we can't write
@ -1483,10 +1488,13 @@ impl PropertyDeclaration {
pub fn to_css(&self, dest: &mut CssStringWriter) -> fmt::Result { pub fn to_css(&self, dest: &mut CssStringWriter) -> fmt::Result {
match *self { match *self {
% for property in data.longhands: % for property in data.longhands:
PropertyDeclaration::${property.camel_case}(ref value) => PropertyDeclaration::${property.camel_case}(ref value) => {
value.to_css(dest), value.to_css(&mut CssWriter::new(dest))
}
% endfor % endfor
PropertyDeclaration::CSSWideKeyword(_, keyword) => keyword.to_css(dest), PropertyDeclaration::CSSWideKeyword(_, keyword) => {
keyword.to_css(&mut CssWriter::new(dest))
},
PropertyDeclaration::WithVariables(_, ref with_variables) => { PropertyDeclaration::WithVariables(_, ref with_variables) => {
// https://drafts.csswg.org/css-variables/#variables-in-shorthands // https://drafts.csswg.org/css-variables/#variables-in-shorthands
match with_variables.from_shorthand { match with_variables.from_shorthand {
@ -1500,7 +1508,9 @@ impl PropertyDeclaration {
} }
Ok(()) Ok(())
}, },
PropertyDeclaration::Custom(_, ref value) => value.borrow().to_css(dest), PropertyDeclaration::Custom(_, ref value) => {
value.borrow().to_css(&mut CssWriter::new(dest))
},
} }
} }
} }

View file

@ -131,7 +131,7 @@
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
let len = self.background_image.0.len(); let len = self.background_image.0.len();
// There should be at least one declared value // There should be at least one declared value
if len == 0 { if len == 0 {
@ -228,7 +228,7 @@
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
let len = self.background_position_x.0.len(); let len = self.background_position_x.0.len();
if len == 0 || len != self.background_position_y.0.len() { if len == 0 || len != self.background_position_y.0.len() {
return Ok(()); return Ok(());

View file

@ -34,7 +34,7 @@ ${helpers.four_sides_shorthand("border-style", "border-%s-style",
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
% for side in PHYSICAL_SIDES: % for side in PHYSICAL_SIDES:
let ${side} = &self.border_${side}_width; let ${side} = &self.border_${side}_width;
% endfor % endfor
@ -113,7 +113,7 @@ pub fn parse_border<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
super::serialize_directional_border( super::serialize_directional_border(
dest, dest,
self.border_${to_rust_ident(side)}_width, self.border_${to_rust_ident(side)}_width,
@ -156,7 +156,7 @@ pub fn parse_border<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
let all_equal = { let all_equal = {
% for side in PHYSICAL_SIDES: % for side in PHYSICAL_SIDES:
let border_${side}_width = self.border_${side}_width; let border_${side}_width = self.border_${side}_width;
@ -215,7 +215,7 @@ pub fn parse_border<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
let LonghandsToSerialize { let LonghandsToSerialize {
border_top_left_radius: &BorderCornerRadius(ref tl), border_top_left_radius: &BorderCornerRadius(ref tl),
border_top_right_radius: &BorderCornerRadius(ref tr), border_top_right_radius: &BorderCornerRadius(ref tr),
@ -315,7 +315,7 @@ pub fn parse_border<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
self.border_image_source.to_css(dest)?; self.border_image_source.to_css(dest)?;
dest.write_str(" ")?; dest.write_str(" ")?;
self.border_image_slice.to_css(dest)?; self.border_image_slice.to_css(dest)?;

View file

@ -48,7 +48,7 @@
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
if self.overflow_x == self.overflow_y { if self.overflow_x == self.overflow_y {
self.overflow_x.to_css(dest) self.overflow_x.to_css(dest)
} else { } else {
@ -83,7 +83,7 @@
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
self.overflow_clip_box_block.to_css(dest)?; self.overflow_clip_box_block.to_css(dest)?;
if self.overflow_clip_box_block != self.overflow_clip_box_inline { if self.overflow_clip_box_block != self.overflow_clip_box_inline {
@ -203,7 +203,7 @@ macro_rules! try_parse_one {
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
let property_len = self.transition_property.0.len(); let property_len = self.transition_property.0.len();
// There are two cases that we can do shorthand serialization: // There are two cases that we can do shorthand serialization:
@ -327,7 +327,7 @@ macro_rules! try_parse_one {
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
let len = self.animation_name.0.len(); let len = self.animation_name.0.len();
// There should be at least one declared value // There should be at least one declared value
if len == 0 { if len == 0 {
@ -376,7 +376,7 @@ macro_rules! try_parse_one {
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
// Serializes into the single keyword value if both scroll-snap-type-x and scroll-snap-type-y are same. // Serializes into the single keyword value if both scroll-snap-type-x and scroll-snap-type-y are same.
// Otherwise into an empty string. This is done to match Gecko's behaviour. // Otherwise into an empty string. This is done to match Gecko's behaviour.
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
if self.scroll_snap_type_x == self.scroll_snap_type_y { if self.scroll_snap_type_x == self.scroll_snap_type_y {
self.scroll_snap_type_x.to_css(dest) self.scroll_snap_type_x.to_css(dest)
} else { } else {
@ -406,7 +406,7 @@ macro_rules! try_parse_one {
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
// Serializes into the single keyword value if both overscroll-behavior-x and overscroll-behavior-y are same. // Serializes into the single keyword value if both overscroll-behavior-x and overscroll-behavior-y are same.
// Otherwise into two values separated by a space. // Otherwise into two values separated by a space.
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
self.overscroll_behavior_x.to_css(dest)?; self.overscroll_behavior_x.to_css(dest)?;
if self.overscroll_behavior_y != self.overscroll_behavior_x { if self.overscroll_behavior_y != self.overscroll_behavior_x {
dest.write_str(" ")?; dest.write_str(" ")?;

View file

@ -151,9 +151,14 @@
} }
impl<'a> LonghandsToSerialize<'a> { impl<'a> LonghandsToSerialize<'a> {
fn to_css_for<W>(&self, fn to_css_for<W>(
&self,
serialize_for: SerializeFor, serialize_for: SerializeFor,
dest: &mut W) -> fmt::Result where W: fmt::Write { dest: &mut CssWriter<W>,
) -> fmt::Result
where
W: Write,
{
% if product == "gecko": % if product == "gecko":
match self.check_system() { match self.check_system() {
CheckSystemResult::AllSystem(sys) => return sys.to_css(dest), CheckSystemResult::AllSystem(sys) => return sys.to_css(dest),
@ -226,7 +231,7 @@
} }
/// Serialize the shorthand value for canvas font attribute. /// Serialize the shorthand value for canvas font attribute.
pub fn to_css_for_canvas<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { pub fn to_css_for_canvas<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
self.to_css_for(SerializeFor::Canvas, dest) self.to_css_for(SerializeFor::Canvas, dest)
} }
% endif % endif
@ -234,7 +239,7 @@
// This may be a bit off, unsure, possibly needs changes // This may be a bit off, unsure, possibly needs changes
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
self.to_css_for(SerializeFor::Normal, dest) self.to_css_for(SerializeFor::Normal, dest)
} }
} }
@ -309,7 +314,7 @@
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
#[allow(unused_assignments)] #[allow(unused_assignments)]
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
let has_none_ligatures = let has_none_ligatures =
% if product == "gecko": % if product == "gecko":

View file

@ -22,7 +22,7 @@
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
if self.marker_start == self.marker_mid && self.marker_mid == self.marker_end { if self.marker_start == self.marker_mid && self.marker_mid == self.marker_end {
self.marker_start.to_css(dest) self.marker_start.to_css(dest)
} else { } else {

View file

@ -121,7 +121,7 @@
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
use properties::longhands::mask_origin::single_value::computed_value::T as Origin; use properties::longhands::mask_origin::single_value::computed_value::T as Origin;
use properties::longhands::mask_clip::single_value::computed_value::T as Clip; use properties::longhands::mask_clip::single_value::computed_value::T as Clip;
@ -214,7 +214,7 @@
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
let len = self.mask_position_x.0.len(); let len = self.mask_position_x.0.len();
if len == 0 || self.mask_position_y.0.len() != len { if len == 0 || self.mask_position_y.0.len() != len {
return Ok(()); return Ok(());

View file

@ -76,7 +76,7 @@
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
use values::generics::border::BorderCornerRadius; use values::generics::border::BorderCornerRadius;
let LonghandsToSerialize { let LonghandsToSerialize {

View file

@ -119,7 +119,7 @@
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
if self.grid_row_gap == self.grid_column_gap { if self.grid_row_gap == self.grid_column_gap {
self.grid_row_gap.to_css(dest) self.grid_row_gap.to_css(dest)
} else { } else {
@ -163,7 +163,7 @@
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
self.grid_${kind}_start.to_css(dest)?; self.grid_${kind}_start.to_css(dest)?;
dest.write_str(" / ")?; dest.write_str(" / ")?;
self.grid_${kind}_end.to_css(dest) self.grid_${kind}_end.to_css(dest)
@ -224,7 +224,7 @@
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
self.grid_row_start.to_css(dest)?; self.grid_row_start.to_css(dest)?;
let values = [&self.grid_column_start, &self.grid_row_end, &self.grid_column_end]; let values = [&self.grid_column_start, &self.grid_row_end, &self.grid_column_end];
for value in &values { for value in &values {
@ -362,10 +362,14 @@
} }
/// Serialization for `<grid-template>` shorthand (also used by `grid` shorthand). /// Serialization for `<grid-template>` shorthand (also used by `grid` shorthand).
pub fn serialize_grid_template<W>(template_rows: &GridTemplateComponent, pub fn serialize_grid_template<W>(
template_rows: &GridTemplateComponent,
template_columns: &GridTemplateComponent, template_columns: &GridTemplateComponent,
template_areas: &Either<TemplateAreas, None_>, template_areas: &Either<TemplateAreas, None_>,
dest: &mut W) -> fmt::Result where W: fmt::Write { dest: &mut CssWriter<W>,
) -> fmt::Result
where
W: Write {
match *template_areas { match *template_areas {
Either::Second(_none) => { Either::Second(_none) => {
template_rows.to_css(dest)?; template_rows.to_css(dest)?;
@ -451,7 +455,7 @@
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
#[inline] #[inline]
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
serialize_grid_template(self.grid_template_rows, self.grid_template_columns, serialize_grid_template(self.grid_template_rows, self.grid_template_columns,
self.grid_template_areas, dest) self.grid_template_areas, dest)
} }
@ -542,7 +546,7 @@
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
if *self.grid_template_areas != Either::Second(None_) || if *self.grid_template_areas != Either::Second(None_) ||
(*self.grid_template_rows != GridTemplateComponent::None && (*self.grid_template_rows != GridTemplateComponent::None &&
*self.grid_template_columns != GridTemplateComponent::None) || *self.grid_template_columns != GridTemplateComponent::None) ||
@ -635,7 +639,7 @@
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
self.align_content.to_css(dest)?; self.align_content.to_css(dest)?;
if self.align_content != self.justify_content { if self.align_content != self.justify_content {
dest.write_str(" ")?; dest.write_str(" ")?;
@ -670,7 +674,7 @@
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
if self.align_self == self.justify_self { if self.align_self == self.justify_self {
self.align_self.to_css(dest) self.align_self.to_css(dest)
} else { } else {
@ -713,7 +717,7 @@
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
if self.align_items.0 == self.justify_items.0 { if self.align_items.0 == self.justify_items.0 {
self.align_items.to_css(dest) self.align_items.to_css(dest)
} else { } else {

View file

@ -2,15 +2,20 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use values::specified::{BorderStyle, Color}; use values::specified::{BorderStyle, Color};
use std::fmt; use std::fmt::{self, Write};
fn serialize_directional_border<W, I,>(dest: &mut W, fn serialize_directional_border<W, I,>(
dest: &mut CssWriter<W>,
width: &I, width: &I,
style: &BorderStyle, style: &BorderStyle,
color: &Color) color: &Color,
-> fmt::Result where W: fmt::Write, I: ToCss { ) -> fmt::Result
where
W: Write,
I: ToCss,
{
width.to_css(dest)?; width.to_css(dest)?;
dest.write_str(" ")?; dest.write_str(" ")?;
style.to_css(dest)?; style.to_css(dest)?;

View file

@ -62,7 +62,7 @@
} }
impl<'a> ToCss for LonghandsToSerialize<'a> { impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
self.text_decoration_line.to_css(dest)?; self.text_decoration_line.to_css(dest)?;
% if product == "gecko": % if product == "gecko":

View file

@ -9,7 +9,7 @@
use cssparser::{Parser as CssParser, ParserInput}; use cssparser::{Parser as CssParser, ParserInput};
use selectors::parser::SelectorList; use selectors::parser::SelectorList;
use std::fmt::{self, Debug, Write}; use std::fmt::{self, Debug, Write};
use style_traits::{ParseError, ToCss}; use style_traits::{CssWriter, ParseError, ToCss};
use stylesheets::{Origin, Namespaces, UrlExtraData}; use stylesheets::{Origin, Namespaces, UrlExtraData};
/// A convenient alias for the type that represents an attribute value used for /// A convenient alias for the type that represents an attribute value used for
@ -201,7 +201,7 @@ impl Direction {
} }
impl ToCss for Direction { impl ToCss for Direction {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write {
let dir_str = match *self { let dir_str = match *self {
Direction::Rtl => "rtl", Direction::Rtl => "rtl",
Direction::Ltr => "ltr", Direction::Ltr => "ltr",

View file

@ -12,9 +12,9 @@ use media_queries::MediaType;
use parser::ParserContext; use parser::ParserContext;
use properties::ComputedValues; use properties::ComputedValues;
use selectors::parser::SelectorParseErrorKind; use selectors::parser::SelectorParseErrorKind;
use std::fmt; use std::fmt::{self, Write};
use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering}; use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering};
use style_traits::{CSSPixel, DevicePixel, ToCss, ParseError}; use style_traits::{CSSPixel, CssWriter, DevicePixel, ToCss, ParseError};
use style_traits::viewport::ViewportConstraints; use style_traits::viewport::ViewportConstraints;
use values::computed::{self, ToComputedValue}; use values::computed::{self, ToComputedValue};
use values::computed::font::FontSize; use values::computed::font::FontSize;
@ -218,8 +218,9 @@ impl Expression {
} }
impl ToCss for Expression { impl ToCss for Expression {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write, where
W: Write,
{ {
let (s, l) = match self.0 { let (s, l) = match self.0 {
ExpressionKind::Width(Range::Min(ref l)) => ("(min-width: ", l), ExpressionKind::Width(Range::Min(ref l)) => ("(min-width: ", l),

View file

@ -6,12 +6,12 @@
use parser::ParserContext; use parser::ParserContext;
use servo_url::ServoUrl; use servo_url::ServoUrl;
use std::fmt; use std::fmt::{self, Write};
// Note: We use std::sync::Arc rather than servo_arc::Arc here because the // Note: We use std::sync::Arc rather than servo_arc::Arc here because the
// nonzero optimization is important in keeping the size of SpecifiedUrl below // nonzero optimization is important in keeping the size of SpecifiedUrl below
// the threshold. // the threshold.
use std::sync::Arc; use std::sync::Arc;
use style_traits::{ToCss, ParseError}; use style_traits::{CssWriter, ParseError, ToCss};
use values::computed::{Context, ToComputedValue, ComputedUrl}; use values::computed::{Context, ToComputedValue, ComputedUrl};
/// A specified url() value for servo. /// A specified url() value for servo.
@ -111,7 +111,10 @@ impl PartialEq for SpecifiedUrl {
} }
impl ToCss for SpecifiedUrl { impl ToCss for SpecifiedUrl {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
let string = match self.original { let string = match self.original {
Some(ref original) => &**original, Some(ref original) => &**original,
None => match self.resolved { None => match self.resolved {

View file

@ -15,7 +15,7 @@ use servo_arc::Arc;
use shared_lock::{DeepCloneParams, DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard}; use shared_lock::{DeepCloneParams, DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard};
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use str::CssStringWriter; use str::CssStringWriter;
use style_traits::{ToCss, ParseError, StyleParseErrorKind}; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use stylesheets::CssRules; use stylesheets::CssRules;
use values::specified::url::SpecifiedUrl; use values::specified::url::SpecifiedUrl;
@ -43,7 +43,7 @@ impl DocumentRule {
impl ToCssWithGuard for DocumentRule { impl ToCssWithGuard for DocumentRule {
fn to_css(&self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result { fn to_css(&self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result {
dest.write_str("@-moz-document ")?; dest.write_str("@-moz-document ")?;
self.condition.to_css(dest)?; self.condition.to_css(&mut CssWriter::new(dest))?;
dest.write_str(" {")?; dest.write_str(" {")?;
for rule in self.rules.read_with(guard).0.iter() { for rule in self.rules.read_with(guard).0.iter() {
dest.write_str(" ")?; dest.write_str(" ")?;
@ -167,8 +167,10 @@ impl UrlMatchingFunction {
} }
impl ToCss for UrlMatchingFunction { impl ToCss for UrlMatchingFunction {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write { where
W: Write,
{
match *self { match *self {
UrlMatchingFunction::Url(ref url) => { UrlMatchingFunction::Url(ref url) => {
url.to_css(dest) url.to_css(dest)
@ -219,8 +221,10 @@ impl DocumentCondition {
} }
impl ToCss for DocumentCondition { impl ToCss for DocumentCondition {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write { where
W: Write,
{
let mut iter = self.0.iter(); let mut iter = self.0.iter();
let first = iter.next() let first = iter.next()
.expect("Empty DocumentCondition, should contain at least one URL matching function"); .expect("Empty DocumentCondition, should contain at least one URL matching function");

View file

@ -18,7 +18,7 @@ use parser::{ParserContext, ParserErrorContext, Parse};
use shared_lock::{SharedRwLockReadGuard, ToCssWithGuard}; use shared_lock::{SharedRwLockReadGuard, ToCssWithGuard};
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use str::CssStringWriter; use str::CssStringWriter;
use style_traits::{ParseError, StyleParseErrorKind, ToCss}; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use stylesheets::CssRuleType; use stylesheets::CssRuleType;
use values::computed::font::FamilyName; use values::computed::font::FamilyName;
@ -37,7 +37,10 @@ pub struct FFVDeclaration<T> {
} }
impl<T: ToCss> ToCss for FFVDeclaration<T> { impl<T: ToCss> ToCss for FFVDeclaration<T> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
serialize_identifier(&self.name.to_string(), dest)?; serialize_identifier(&self.name.to_string(), dest)?;
dest.write_str(": ")?; dest.write_str(": ")?;
self.value.to_css(dest)?; self.value.to_css(dest)?;
@ -101,7 +104,10 @@ impl Parse for PairValues {
} }
impl ToCss for PairValues { impl ToCss for PairValues {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
self.0.to_css(dest)?; self.0.to_css(dest)?;
if let Some(second) = self.1 { if let Some(second) = self.1 {
dest.write_char(' ')?; dest.write_char(' ')?;
@ -153,7 +159,10 @@ impl Parse for VectorValues {
} }
impl ToCss for VectorValues { impl ToCss for VectorValues {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
let mut iter = self.0.iter(); let mut iter = self.0.iter();
let first = iter.next(); let first = iter.next();
if let Some(first) = first { if let Some(first) = first {
@ -280,7 +289,13 @@ macro_rules! font_feature_values_blocks {
} }
/// Prints font family names. /// Prints font family names.
pub fn font_family_to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { pub fn font_family_to_css<W>(
&self,
dest: &mut CssWriter<W>,
) -> fmt::Result
where
W: Write,
{
let mut iter = self.family_names.iter(); let mut iter = self.family_names.iter();
iter.next().unwrap().to_css(dest)?; iter.next().unwrap().to_css(dest)?;
for val in iter { for val in iter {
@ -291,7 +306,10 @@ macro_rules! font_feature_values_blocks {
} }
/// Prints inside of `@font-feature-values` block. /// Prints inside of `@font-feature-values` block.
pub fn value_to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { pub fn value_to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
$( $(
if self.$ident.len() > 0 { if self.$ident.len() > 0 {
dest.write_str(concat!("@", $name, " {\n"))?; dest.write_str(concat!("@", $name, " {\n"))?;
@ -344,9 +362,9 @@ macro_rules! font_feature_values_blocks {
impl ToCssWithGuard for FontFeatureValuesRule { impl ToCssWithGuard for FontFeatureValuesRule {
fn to_css(&self, _guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result { fn to_css(&self, _guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result {
dest.write_str("@font-feature-values ")?; dest.write_str("@font-feature-values ")?;
self.font_family_to_css(dest)?; self.font_family_to_css(&mut CssWriter::new(dest))?;
dest.write_str(" {\n")?; dest.write_str(" {\n")?;
self.value_to_css(dest)?; self.value_to_css(&mut CssWriter::new(dest))?;
dest.write_str("}") dest.write_str("}")
} }
} }

View file

@ -11,7 +11,7 @@ use media_queries::MediaList;
use shared_lock::{DeepCloneWithLock, DeepCloneParams, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard}; use shared_lock::{DeepCloneWithLock, DeepCloneParams, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard};
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use str::CssStringWriter; use str::CssStringWriter;
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use stylesheets::{StylesheetContents, StylesheetInDocument}; use stylesheets::{StylesheetContents, StylesheetInDocument};
use values::specified::url::SpecifiedUrl; use values::specified::url::SpecifiedUrl;
@ -110,12 +110,12 @@ impl DeepCloneWithLock for ImportRule {
impl ToCssWithGuard for ImportRule { impl ToCssWithGuard for ImportRule {
fn to_css(&self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result { fn to_css(&self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result {
dest.write_str("@import ")?; dest.write_str("@import ")?;
self.url.to_css(dest)?; self.url.to_css(&mut CssWriter::new(dest))?;
match self.stylesheet.media(guard) { match self.stylesheet.media(guard) {
Some(media) if !media.is_empty() => { Some(media) if !media.is_empty() => {
dest.write_str(" ")?; dest.write_str(" ")?;
media.to_css(dest)?; media.to_css(&mut CssWriter::new(dest))?;
} }
_ => {}, _ => {},
}; };

View file

@ -16,7 +16,7 @@ use servo_arc::Arc;
use shared_lock::{DeepCloneParams, DeepCloneWithLock, SharedRwLock, SharedRwLockReadGuard, Locked, ToCssWithGuard}; use shared_lock::{DeepCloneParams, DeepCloneWithLock, SharedRwLock, SharedRwLockReadGuard, Locked, ToCssWithGuard};
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use str::CssStringWriter; use str::CssStringWriter;
use style_traits::{ParsingMode, ToCss, ParseError, StyleParseErrorKind}; use style_traits::{CssWriter, ParseError, ParsingMode, StyleParseErrorKind, ToCss};
use stylesheets::{CssRuleType, StylesheetContents}; use stylesheets::{CssRuleType, StylesheetContents};
use stylesheets::rule_parser::VendorPrefix; use stylesheets::rule_parser::VendorPrefix;
use values::{KeyframesName, serialize_percentage}; use values::{KeyframesName, serialize_percentage};
@ -40,7 +40,7 @@ impl ToCssWithGuard for KeyframesRule {
// Serialization of KeyframesRule is not specced. // Serialization of KeyframesRule is not specced.
fn to_css(&self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result { fn to_css(&self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result {
dest.write_str("@keyframes ")?; dest.write_str("@keyframes ")?;
self.name.to_css(dest)?; self.name.to_css(&mut CssWriter::new(dest))?;
dest.write_str(" {")?; dest.write_str(" {")?;
let iter = self.keyframes.iter(); let iter = self.keyframes.iter();
for lock in iter { for lock in iter {
@ -109,7 +109,10 @@ impl ::std::cmp::Ord for KeyframePercentage {
impl ::std::cmp::Eq for KeyframePercentage { } impl ::std::cmp::Eq for KeyframePercentage { }
impl ToCss for KeyframePercentage { impl ToCss for KeyframePercentage {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
serialize_percentage(self.0, dest) serialize_percentage(self.0, dest)
} }
} }
@ -146,7 +149,10 @@ impl KeyframePercentage {
pub struct KeyframeSelector(Vec<KeyframePercentage>); pub struct KeyframeSelector(Vec<KeyframePercentage>);
impl ToCss for KeyframeSelector { impl ToCss for KeyframeSelector {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
let mut iter = self.0.iter(); let mut iter = self.0.iter();
iter.next().unwrap().to_css(dest)?; iter.next().unwrap().to_css(dest)?;
for percentage in iter { for percentage in iter {
@ -194,7 +200,7 @@ pub struct Keyframe {
impl ToCssWithGuard for Keyframe { impl ToCssWithGuard for Keyframe {
fn to_css(&self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result { fn to_css(&self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result {
self.selector.to_css(dest)?; self.selector.to_css(&mut CssWriter::new(dest))?;
dest.write_str(" { ")?; dest.write_str(" { ")?;
self.block.read_with(guard).to_css(dest)?; self.block.read_with(guard).to_css(dest)?;
dest.write_str(" }")?; dest.write_str(" }")?;

View file

@ -14,7 +14,7 @@ use servo_arc::Arc;
use shared_lock::{DeepCloneParams, DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard}; use shared_lock::{DeepCloneParams, DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard};
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use str::CssStringWriter; use str::CssStringWriter;
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use stylesheets::CssRules; use stylesheets::CssRules;
/// An [`@media`][media] urle. /// An [`@media`][media] urle.
@ -45,7 +45,7 @@ impl ToCssWithGuard for MediaRule {
// https://drafts.csswg.org/cssom/#serialize-a-css-rule CSSMediaRule // https://drafts.csswg.org/cssom/#serialize-a-css-rule CSSMediaRule
fn to_css(&self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result { fn to_css(&self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result {
dest.write_str("@media ")?; dest.write_str("@media ")?;
self.media_queries.read_with(guard).to_css(dest)?; self.media_queries.read_with(guard).to_css(&mut CssWriter::new(dest))?;
self.rules.read_with(guard).to_css_block(guard, dest) self.rules.read_with(guard).to_css_block(guard, dest)
} }
} }

View file

@ -18,7 +18,7 @@ use std::ffi::{CStr, CString};
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use std::str; use std::str;
use str::CssStringWriter; use str::CssStringWriter;
use style_traits::{ToCss, ParseError}; use style_traits::{CssWriter, ParseError, ToCss};
use stylesheets::{CssRuleType, CssRules}; use stylesheets::{CssRuleType, CssRules};
/// An [`@supports`][supports] rule. /// An [`@supports`][supports] rule.
@ -49,7 +49,7 @@ impl SupportsRule {
impl ToCssWithGuard for SupportsRule { impl ToCssWithGuard for SupportsRule {
fn to_css(&self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result { fn to_css(&self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result {
dest.write_str("@supports ")?; dest.write_str("@supports ")?;
self.condition.to_css(dest)?; self.condition.to_css(&mut CssWriter::new(dest))?;
self.rules.read_with(guard).to_css_block(guard, dest) self.rules.read_with(guard).to_css_block(guard, dest)
} }
} }
@ -219,8 +219,9 @@ pub fn parse_condition_or_declaration<'i, 't>(input: &mut Parser<'i, 't>)
} }
impl ToCss for SupportsCondition { impl ToCss for SupportsCondition {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write, where
W: Write,
{ {
match *self { match *self {
SupportsCondition::Not(ref cond) => { SupportsCondition::Not(ref cond) => {
@ -276,7 +277,10 @@ impl ToCss for SupportsCondition {
pub struct Declaration(pub String); pub struct Declaration(pub String);
impl ToCss for Declaration { impl ToCss for Declaration {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str(&self.0) dest.write_str(&self.0)
} }
} }

View file

@ -27,7 +27,7 @@ use std::fmt::{self, Write};
use std::iter::Enumerate; use std::iter::Enumerate;
use std::str::Chars; use std::str::Chars;
use str::CssStringWriter; use str::CssStringWriter;
use style_traits::{PinchZoomFactor, ToCss, ParseError, StyleParseErrorKind}; use style_traits::{CssWriter, ParseError, PinchZoomFactor, StyleParseErrorKind, ToCss};
use style_traits::viewport::{Orientation, UserZoom, ViewportConstraints, Zoom}; use style_traits::viewport::{Orientation, UserZoom, ViewportConstraints, Zoom};
use stylesheets::{StylesheetInDocument, Origin}; use stylesheets::{StylesheetInDocument, Origin};
use values::computed::{Context, ToComputedValue}; use values::computed::{Context, ToComputedValue};
@ -101,7 +101,10 @@ macro_rules! declare_viewport_descriptor_inner {
} }
impl ToCss for ViewportDescriptor { impl ToCss for ViewportDescriptor {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self { match *self {
$( $(
ViewportDescriptor::$assigned_variant(ref val) => { ViewportDescriptor::$assigned_variant(ref val) => {
@ -149,8 +152,9 @@ pub enum ViewportLength {
} }
impl ToCss for ViewportLength { impl ToCss for ViewportLength {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write, where
W: Write,
{ {
match *self { match *self {
ViewportLength::Specified(ref length) => length.to_css(dest), ViewportLength::Specified(ref length) => length.to_css(dest),
@ -255,7 +259,10 @@ impl ViewportDescriptorDeclaration {
} }
impl ToCss for ViewportDescriptorDeclaration { impl ToCss for ViewportDescriptorDeclaration {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
self.descriptor.to_css(dest)?; self.descriptor.to_css(dest)?;
if self.important { if self.important {
dest.write_str(" !important")?; dest.write_str(" !important")?;
@ -524,10 +531,10 @@ impl ToCssWithGuard for ViewportRule {
fn to_css(&self, _guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result { fn to_css(&self, _guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result {
dest.write_str("@viewport { ")?; dest.write_str("@viewport { ")?;
let mut iter = self.declarations.iter(); let mut iter = self.declarations.iter();
iter.next().unwrap().to_css(dest)?; iter.next().unwrap().to_css(&mut CssWriter::new(dest))?;
for declaration in iter { for declaration in iter {
dest.write_str(" ")?; dest.write_str(" ")?;
declaration.to_css(dest)?; declaration.to_css(&mut CssWriter::new(dest))?;
} }
dest.write_str(" }") dest.write_str(" }")
} }

View file

@ -7,7 +7,7 @@
//! https://drafts.csswg.org/css-align/ //! https://drafts.csswg.org/css-align/
use std::fmt; use std::fmt;
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use values::computed::{Context, ToComputedValue}; use values::computed::{Context, ToComputedValue};
use values::specified; use values::specified;
@ -26,7 +26,7 @@ pub struct JustifyItems {
} }
impl ToCss for JustifyItems { impl ToCss for JustifyItems {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write, where W: fmt::Write,
{ {
self.computed.to_css(dest) self.computed.to_css(dest)

View file

@ -6,8 +6,8 @@
use properties::animated_properties::RepeatableListAnimatable; use properties::animated_properties::RepeatableListAnimatable;
use properties::longhands::background_size::computed_value::T as BackgroundSizeList; use properties::longhands::background_size::computed_value::T as BackgroundSizeList;
use std::fmt; use std::fmt::{self, Write};
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use values::animated::{ToAnimatedValue, ToAnimatedZero}; use values::animated::{ToAnimatedValue, ToAnimatedZero};
use values::computed::{Context, ToComputedValue}; use values::computed::{Context, ToComputedValue};
use values::computed::length::LengthOrPercentageOrAuto; use values::computed::length::LengthOrPercentageOrAuto;
@ -96,9 +96,9 @@ impl BackgroundRepeat {
} }
impl ToCss for BackgroundRepeat { impl ToCss for BackgroundRepeat {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where where
W: fmt::Write, W: Write,
{ {
match (self.0, self.1) { match (self.0, self.1) {
(RepeatKeyword::Repeat, RepeatKeyword::NoRepeat) => dest.write_str("repeat-x"), (RepeatKeyword::Repeat, RepeatKeyword::NoRepeat) => dest.write_str("repeat-x"),

View file

@ -7,8 +7,8 @@
//! //!
//! [basic-shape]: https://drafts.csswg.org/css-shapes/#typedef-basic-shape //! [basic-shape]: https://drafts.csswg.org/css-shapes/#typedef-basic-shape
use std::fmt; use std::fmt::{self, Write};
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use values::computed::{LengthOrPercentage, ComputedUrl, Image}; use values::computed::{LengthOrPercentage, ComputedUrl, Image};
use values::generics::basic_shape::{BasicShape as GenericBasicShape}; use values::generics::basic_shape::{BasicShape as GenericBasicShape};
use values::generics::basic_shape::{Circle as GenericCircle, ClippingShape as GenericClippingShape}; use values::generics::basic_shape::{Circle as GenericCircle, ClippingShape as GenericClippingShape};
@ -37,7 +37,10 @@ pub type Ellipse = GenericEllipse<LengthOrPercentage, LengthOrPercentage, Length
pub type ShapeRadius = GenericShapeRadius<LengthOrPercentage>; pub type ShapeRadius = GenericShapeRadius<LengthOrPercentage>;
impl ToCss for Circle { impl ToCss for Circle {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("circle(")?; dest.write_str("circle(")?;
self.radius.to_css(dest)?; self.radius.to_css(dest)?;
dest.write_str(" at ")?; dest.write_str(" at ")?;
@ -47,7 +50,10 @@ impl ToCss for Circle {
} }
impl ToCss for Ellipse { impl ToCss for Ellipse {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("ellipse(")?; dest.write_str("ellipse(")?;
if (self.semiaxis_x, self.semiaxis_y) != Default::default() { if (self.semiaxis_x, self.semiaxis_y) != Default::default() {
self.semiaxis_x.to_css(dest)?; self.semiaxis_x.to_css(dest)?;

View file

@ -6,7 +6,7 @@
use cssparser::{Color as CSSParserColor, RGBA}; use cssparser::{Color as CSSParserColor, RGBA};
use std::fmt; use std::fmt;
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use values::animated::ToAnimatedValue; use values::animated::ToAnimatedValue;
use values::animated::color::{Color as AnimatedColor, RGBA as AnimatedRGBA}; use values::animated::color::{Color as AnimatedColor, RGBA as AnimatedRGBA};
@ -138,7 +138,7 @@ impl From<RGBA> for Color {
} }
impl ToCss for Color { impl ToCss for Color {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
if self.is_numeric() { if self.is_numeric() {
self.color.to_css(dest) self.color.to_css(dest)
} else if self.is_currentcolor() { } else if self.is_currentcolor() {

View file

@ -19,7 +19,7 @@ use std::fmt::{self, Write};
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
#[cfg(feature = "servo")] #[cfg(feature = "servo")]
use std::slice; use std::slice;
use style_traits::{ToCss, ParseError}; use style_traits::{CssWriter, ParseError, ToCss};
use values::CSSFloat; use values::CSSFloat;
use values::animated::{ToAnimatedValue, ToAnimatedZero}; use values::animated::{ToAnimatedValue, ToAnimatedZero};
use values::computed::{Context, NonNegativeLength, ToComputedValue}; use values::computed::{Context, NonNegativeLength, ToComputedValue};
@ -201,7 +201,7 @@ impl FontSize {
} }
impl ToCss for FontSize { impl ToCss for FontSize {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
self.size.to_css(dest) self.size.to_css(dest)
} }
} }
@ -257,7 +257,7 @@ impl MallocSizeOf for FontFamily {
} }
impl ToCss for FontFamily { impl ToCss for FontFamily {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
let mut iter = self.0.iter(); let mut iter = self.0.iter();
iter.next().unwrap().to_css(dest)?; iter.next().unwrap().to_css(dest)?;
for family in iter { for family in iter {
@ -279,7 +279,7 @@ pub struct FamilyName {
} }
impl ToCss for FamilyName { impl ToCss for FamilyName {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
match self.syntax { match self.syntax {
FamilyNameSyntax::Quoted => { FamilyNameSyntax::Quoted => {
dest.write_char('"')?; dest.write_char('"')?;
@ -488,7 +488,7 @@ impl SingleFontFamily {
} }
impl ToCss for SingleFontFamily { impl ToCss for SingleFontFamily {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
match *self { match *self {
SingleFontFamily::FamilyName(ref name) => name.to_css(dest), SingleFontFamily::FamilyName(ref name) => name.to_css(dest),
@ -731,7 +731,7 @@ impl FontLanguageOverride {
} }
impl ToCss for FontLanguageOverride { impl ToCss for FontLanguageOverride {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
use std::str; use std::str;
if self.0 == 0 { if self.0 == 0 {

View file

@ -9,8 +9,8 @@
use cssparser::RGBA; use cssparser::RGBA;
use std::f32::consts::PI; use std::f32::consts::PI;
use std::fmt; use std::fmt::{self, Write};
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use values::{Either, None_}; use values::{Either, None_};
use values::computed::{Angle, ComputedUrl, Context, Length, LengthOrPercentage, NumberOrPercentage, ToComputedValue}; use values::computed::{Angle, ComputedUrl, Context, Length, LengthOrPercentage, NumberOrPercentage, ToComputedValue};
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
@ -99,8 +99,13 @@ impl GenericLineDirection for LineDirection {
} }
} }
fn to_css<W>(&self, dest: &mut W, compat_mode: CompatMode) -> fmt::Result fn to_css<W>(
where W: fmt::Write &self,
dest: &mut CssWriter<W>,
compat_mode: CompatMode,
) -> fmt::Result
where
W: Write,
{ {
match *self { match *self {
LineDirection::Angle(ref angle) => angle.to_css(dest), LineDirection::Angle(ref angle) => angle.to_css(dest),

View file

@ -4,8 +4,8 @@
//! Computed values for inherited box //! Computed values for inherited box
use std::fmt; use std::fmt::{self, Write};
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use values::specified::Angle; use values::specified::Angle;
/// An angle rounded and normalized per https://drafts.csswg.org/css-images/#propdef-image-orientation /// An angle rounded and normalized per https://drafts.csswg.org/css-images/#propdef-image-orientation
@ -31,7 +31,10 @@ impl Orientation {
} }
impl ToCss for Orientation { impl ToCss for Orientation {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
// Should agree with Angle::to_css. // Should agree with Angle::to_css.
match *self { match *self {
Orientation::Angle0 => dest.write_str("0deg"), Orientation::Angle0 => dest.write_str("0deg"),
@ -60,7 +63,10 @@ impl ImageOrientation {
} }
impl ToCss for ImageOrientation { impl ToCss for ImageOrientation {
fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self { match *self {
ImageOrientation::FromImage => dest.write_str("from-image"), ImageOrientation::FromImage => dest.write_str("from-image"),
ImageOrientation::AngleWithFlipped(angle, flipped) => { ImageOrientation::AngleWithFlipped(angle, flipped) => {

View file

@ -6,9 +6,9 @@
use app_units::Au; use app_units::Au;
use ordered_float::NotNaN; use ordered_float::NotNaN;
use std::fmt; use std::fmt::{self, Write};
use std::ops::{Add, Neg}; use std::ops::{Add, Neg};
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use style_traits::values::specified::AllowedNumericType; use style_traits::values::specified::AllowedNumericType;
use super::{Number, ToComputedValue, Context, Percentage}; use super::{Number, ToComputedValue, Context, Percentage};
use values::{Auto, CSSFloat, Either, ExtremumLength, None_, Normal, specified}; use values::{Auto, CSSFloat, Either, ExtremumLength, None_, Normal, specified};
@ -203,7 +203,10 @@ impl From<LengthOrPercentageOrNone> for Option<CalcLengthOrPercentage> {
} }
impl ToCss for CalcLengthOrPercentage { impl ToCss for CalcLengthOrPercentage {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
use num_traits::Zero; use num_traits::Zero;
let (length, percentage) = match (self.length, self.percentage) { let (length, percentage) = match (self.length, self.percentage) {
@ -738,7 +741,10 @@ impl CSSPixelLength {
impl ToCss for CSSPixelLength { impl ToCss for CSSPixelLength {
#[inline] #[inline]
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
self.0.to_css(dest)?; self.0.to_css(dest)?;
dest.write_str("px") dest.write_str("px")
} }

View file

@ -15,11 +15,12 @@ use properties::{ComputedValues, LonghandId, StyleBuilder};
use rule_cache::RuleCacheConditions; use rule_cache::RuleCacheConditions;
#[cfg(feature = "servo")] #[cfg(feature = "servo")]
use servo_url::ServoUrl; use servo_url::ServoUrl;
use std::{f32, fmt};
use std::cell::RefCell; use std::cell::RefCell;
use std::f32;
use std::fmt::{self, Write};
#[cfg(feature = "servo")] #[cfg(feature = "servo")]
use std::sync::Arc; use std::sync::Arc;
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use style_traits::cursor::CursorKind; use style_traits::cursor::CursorKind;
use super::{CSSFloat, CSSInteger}; use super::{CSSFloat, CSSInteger};
use super::generics::{GreaterThanOrEqualToOne, NonNegative}; use super::generics::{GreaterThanOrEqualToOne, NonNegative};
@ -531,7 +532,10 @@ pub struct ClipRect {
} }
impl ToCss for ClipRect { impl ToCss for ClipRect {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("rect(")?; dest.write_str("rect(")?;
if let Some(top) = self.top { if let Some(top) = self.top {
top.to_css(dest)?; top.to_css(dest)?;
@ -627,7 +631,10 @@ impl ComputedUrl {
#[cfg(feature = "servo")] #[cfg(feature = "servo")]
impl ToCss for ComputedUrl { impl ToCss for ComputedUrl {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
let string = match *self { let string = match *self {
ComputedUrl::Valid(ref url) => url.as_str(), ComputedUrl::Valid(ref url) => url.as_str(),
ComputedUrl::Invalid(ref invalid_string) => invalid_string, ComputedUrl::Invalid(ref invalid_string) => invalid_string,

View file

@ -5,7 +5,7 @@
//! Computed percentages. //! Computed percentages.
use std::fmt; use std::fmt;
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use values::{CSSFloat, serialize_percentage}; use values::{CSSFloat, serialize_percentage};
/// A computed percentage. /// A computed percentage.
@ -35,7 +35,7 @@ impl Percentage {
} }
impl ToCss for Percentage { impl ToCss for Percentage {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where where
W: fmt::Write, W: fmt::Write,
{ {

View file

@ -10,10 +10,10 @@ use cssparser::Parser;
use parser::{Parse, ParserContext}; use parser::{Parse, ParserContext};
use selectors::parser::SelectorParseErrorKind; use selectors::parser::SelectorParseErrorKind;
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
use std::fmt; use std::fmt::{self, Write};
use style_traits::ParseError;
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use style_traits::ParseError;
use style_traits::cursor::CursorKind; use style_traits::cursor::CursorKind;
/// The computed value for the `cursor` property. /// The computed value for the `cursor` property.
@ -80,8 +80,9 @@ impl Parse for Cursor {
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
impl ToCss for Cursor { impl ToCss for Cursor {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write where
W: Write,
{ {
for url in &*self.images { for url in &*self.images {
url.to_css(dest)?; url.to_css(dest)?;
@ -123,8 +124,9 @@ impl CursorImage {
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
impl ToCss for CursorImage { impl ToCss for CursorImage {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write where
W: Write,
{ {
self.url.to_css(dest)?; self.url.to_css(dest)?;
if let Some((x, y)) = self.hotspot { if let Some((x, y)) = self.hotspot {

View file

@ -7,8 +7,8 @@
//! //!
//! [position]: https://drafts.csswg.org/css-backgrounds-3/#position //! [position]: https://drafts.csswg.org/css-backgrounds-3/#position
use std::fmt; use std::fmt::{self, Write};
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use values::computed::{LengthOrPercentage, Percentage}; use values::computed::{LengthOrPercentage, Percentage};
use values::generics::position::Position as GenericPosition; use values::generics::position::Position as GenericPosition;
pub use values::specified::position::{GridAutoFlow, GridTemplateAreas}; pub use values::specified::position::{GridAutoFlow, GridTemplateAreas};
@ -40,7 +40,10 @@ impl Position {
} }
impl ToCss for Position { impl ToCss for Position {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
self.horizontal.to_css(dest)?; self.horizontal.to_css(dest)?;
dest.write_str(" ")?; dest.write_str(" ")?;
self.vertical.to_css(dest) self.vertical.to_css(dest)

View file

@ -6,8 +6,8 @@
#[cfg(feature = "servo")] #[cfg(feature = "servo")]
use properties::StyleBuilder; use properties::StyleBuilder;
use std::fmt; use std::fmt::{self, Write};
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use values::{CSSInteger, CSSFloat}; use values::{CSSInteger, CSSFloat};
use values::animated::ToAnimatedZero; use values::animated::ToAnimatedZero;
use values::computed::{NonNegativeLength, NonNegativeNumber}; use values::computed::{NonNegativeLength, NonNegativeNumber};
@ -66,7 +66,10 @@ impl TextOverflow {
} }
impl ToCss for TextOverflow { impl ToCss for TextOverflow {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if self.sides_are_logical { if self.sides_are_logical {
debug_assert!(self.first == TextOverflowSide::Clip); debug_assert!(self.first == TextOverflowSide::Clip);
self.second.to_css(dest)?; self.second.to_css(dest)?;
@ -80,7 +83,10 @@ impl ToCss for TextOverflow {
} }
impl ToCss for TextDecorationLine { impl ToCss for TextDecorationLine {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
let mut has_any = false; let mut has_any = false;
macro_rules! write_value { macro_rules! write_value {

View file

@ -4,8 +4,8 @@
//! Computed time values. //! Computed time values.
use std::fmt; use std::fmt::{self, Write};
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use values::CSSFloat; use values::CSSFloat;
/// A computed `<time>` value. /// A computed `<time>` value.
@ -36,9 +36,9 @@ impl Time {
} }
impl ToCss for Time { impl ToCss for Time {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where where
W: fmt::Write, W: Write,
{ {
self.seconds().to_css(dest)?; self.seconds().to_css(dest)?;
dest.write_str("s") dest.write_str("s")

View file

@ -5,8 +5,8 @@
//! CSS handling for the [`basic-shape`](https://drafts.csswg.org/css-shapes/#typedef-basic-shape) //! CSS handling for the [`basic-shape`](https://drafts.csswg.org/css-shapes/#typedef-basic-shape)
//! types that are generic over their `ToCss` implementations. //! types that are generic over their `ToCss` implementations.
use std::fmt; use std::fmt::{self, Write};
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use values::animated::{Animate, Procedure, ToAnimatedZero}; use values::animated::{Animate, Procedure, ToAnimatedZero};
use values::distance::{ComputeSquaredDistance, SquaredDistance}; use values::distance::{ComputeSquaredDistance, SquaredDistance};
use values::generics::border::BorderRadius; use values::generics::border::BorderRadius;
@ -152,7 +152,10 @@ impl<B, T, U> ToAnimatedZero for ShapeSource<B, T, U> {
impl<L> ToCss for InsetRect<L> impl<L> ToCss for InsetRect<L>
where L: ToCss + PartialEq where L: ToCss + PartialEq
{ {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("inset(")?; dest.write_str("inset(")?;
self.rect.to_css(dest)?; self.rect.to_css(dest)?;
if let Some(ref radius) = self.round { if let Some(ref radius) = self.round {
@ -210,7 +213,10 @@ where
} }
impl<L: ToCss> ToCss for Polygon<L> { impl<L: ToCss> ToCss for Polygon<L> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("polygon(")?; dest.write_str("polygon(")?;
if self.fill != FillRule::default() { if self.fill != FillRule::default() {
self.fill.to_css(dest)?; self.fill.to_css(dest)?;

View file

@ -4,8 +4,8 @@
//! Generic types for CSS values related to borders. //! Generic types for CSS values related to borders.
use std::fmt; use std::fmt::{self, Write};
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use values::generics::rect::Rect; use values::generics::rect::Rect;
use values::generics::size::Size; use values::generics::size::Size;
@ -84,8 +84,9 @@ impl<N> From<N> for BorderImageSlice<N>
impl<N> ToCss for BorderImageSlice<N> impl<N> ToCss for BorderImageSlice<N>
where N: PartialEq + ToCss, where N: PartialEq + ToCss,
{ {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write where
W: Write,
{ {
self.offsets.to_css(dest)?; self.offsets.to_css(dest)?;
if self.fill { if self.fill {
@ -118,8 +119,13 @@ impl<L> BorderRadius<L>
{ {
/// Serialises two given rects following the syntax of the `border-radius`` /// Serialises two given rects following the syntax of the `border-radius``
/// property. /// property.
pub fn serialize_rects<W>(widths: Rect<&L>, heights: Rect<&L>, dest: &mut W) -> fmt::Result pub fn serialize_rects<W>(
where W: fmt::Write, widths: Rect<&L>,
heights: Rect<&L>,
dest: &mut CssWriter<W>,
) -> fmt::Result
where
W: Write,
{ {
widths.to_css(dest)?; widths.to_css(dest)?;
if widths.0 != heights.0 || widths.1 != heights.1 || widths.2 != heights.2 || widths.3 != heights.3 { if widths.0 != heights.0 || widths.1 != heights.1 || widths.2 != heights.2 || widths.3 != heights.3 {
@ -133,7 +139,10 @@ impl<L> BorderRadius<L>
impl<L> ToCss for BorderRadius<L> impl<L> ToCss for BorderRadius<L>
where L: PartialEq + ToCss where L: PartialEq + ToCss
{ {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
let BorderRadius { let BorderRadius {
top_left: BorderCornerRadius(ref tl), top_left: BorderCornerRadius(ref tl),
top_right: BorderCornerRadius(ref tr), top_right: BorderCornerRadius(ref tr),

View file

@ -5,7 +5,7 @@
//! Generic types for counters-related CSS values. //! Generic types for counters-related CSS values.
use std::fmt; use std::fmt;
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use values::CustomIdent; use values::CustomIdent;
/// A generic value for the `counter-increment` property. /// A generic value for the `counter-increment` property.
@ -27,7 +27,7 @@ where
I: ToCss, I: ToCss,
{ {
#[inline] #[inline]
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where where
W: fmt::Write, W: fmt::Write,
{ {

View file

@ -4,8 +4,8 @@
//! Generic types for CSS values related to effects. //! Generic types for CSS values related to effects.
use std::fmt; use std::fmt::{self, Write};
use style_traits::values::{SequenceWriter, ToCss}; use style_traits::values::{CssWriter, SequenceWriter, ToCss};
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
use values::specified::url::SpecifiedUrl; use values::specified::url::SpecifiedUrl;
@ -88,9 +88,9 @@ where
BlurShapeLength: ToCss, BlurShapeLength: ToCss,
ShapeLength: ToCss, ShapeLength: ToCss,
{ {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where where
W: fmt::Write, W: Write,
{ {
{ {
let mut writer = SequenceWriter::new(&mut *dest, " "); let mut writer = SequenceWriter::new(&mut *dest, " ");

View file

@ -7,8 +7,9 @@
use cssparser::Parser; use cssparser::Parser;
use parser::{Parse, ParserContext}; use parser::{Parse, ParserContext};
use std::{fmt, mem, usize}; use std::{mem, usize};
use style_traits::{ToCss, ParseError, StyleParseErrorKind}; use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use values::{CSSFloat, CustomIdent}; use values::{CSSFloat, CustomIdent};
use values::computed::{Context, ToComputedValue}; use values::computed::{Context, ToComputedValue};
use values::specified; use values::specified;
@ -49,7 +50,10 @@ impl<Integer> ToCss for GridLine<Integer>
where where
Integer: ToCss, Integer: ToCss,
{ {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if self.is_auto() { if self.is_auto() {
return dest.write_str("auto") return dest.write_str("auto")
} }
@ -230,7 +234,10 @@ impl<L: PartialEq> TrackSize<L> {
} }
impl<L: ToCss> ToCss for TrackSize<L> { impl<L: ToCss> ToCss for TrackSize<L> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self { match *self {
TrackSize::Breadth(ref breadth) => breadth.to_css(dest), TrackSize::Breadth(ref breadth) => breadth.to_css(dest),
TrackSize::Minmax(ref min, ref max) => { TrackSize::Minmax(ref min, ref max) => {
@ -315,10 +322,10 @@ pub fn concat_serialize_idents<W>(
suffix: &str, suffix: &str,
slice: &[CustomIdent], slice: &[CustomIdent],
sep: &str, sep: &str,
dest: &mut W, dest: &mut CssWriter<W>,
) -> fmt::Result ) -> fmt::Result
where where
W: fmt::Write W: Write,
{ {
if let Some((ref first, rest)) = slice.split_first() { if let Some((ref first, rest)) = slice.split_first() {
dest.write_str(prefix)?; dest.write_str(prefix)?;
@ -385,7 +392,10 @@ pub struct TrackRepeat<L, I> {
} }
impl<L: ToCss, I: ToCss> ToCss for TrackRepeat<L, I> { impl<L: ToCss, I: ToCss> ToCss for TrackRepeat<L, I> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("repeat(")?; dest.write_str("repeat(")?;
self.count.to_css(dest)?; self.count.to_css(dest)?;
dest.write_str(", ")?; dest.write_str(", ")?;
@ -503,7 +513,10 @@ pub struct TrackList<LengthOrPercentage, Integer> {
} }
impl<L: ToCss, I: ToCss> ToCss for TrackList<L, I> { impl<L: ToCss, I: ToCss> ToCss for TrackList<L, I> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
let auto_idx = match self.list_type { let auto_idx = match self.list_type {
TrackListType::Auto(i) => i as usize, TrackListType::Auto(i) => i as usize,
_ => usize::MAX, _ => usize::MAX,
@ -614,7 +627,10 @@ impl Parse for LineNameList {
} }
impl ToCss for LineNameList { impl ToCss for LineNameList {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("subgrid")?; dest.write_str("subgrid")?;
let fill_idx = self.fill_idx.map(|v| v as usize).unwrap_or(usize::MAX); let fill_idx = self.fill_idx.map(|v| v as usize).unwrap_or(usize::MAX);
for (i, names) in self.names.iter().enumerate() { for (i, names) in self.names.iter().enumerate() {

View file

@ -10,8 +10,8 @@ use Atom;
use cssparser::serialize_identifier; use cssparser::serialize_identifier;
use custom_properties; use custom_properties;
use servo_arc::Arc; use servo_arc::Arc;
use std::fmt; use std::fmt::{self, Write};
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
/// An [image]. /// An [image].
/// ///
@ -143,7 +143,10 @@ pub struct PaintWorklet {
trivial_to_computed_value!(PaintWorklet); trivial_to_computed_value!(PaintWorklet);
impl ToCss for PaintWorklet { impl ToCss for PaintWorklet {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("paint(")?; dest.write_str("paint(")?;
serialize_identifier(&*self.name.to_string(), dest)?; serialize_identifier(&*self.name.to_string(), dest)?;
for argument in &self.arguments { for argument in &self.arguments {
@ -169,17 +172,23 @@ pub struct MozImageRect<NumberOrPercentage, MozImageRectUrl> {
} }
impl<G, R, U> fmt::Debug for Image<G, R, U> impl<G, R, U> fmt::Debug for Image<G, R, U>
where G: fmt::Debug, R: fmt::Debug, U: fmt::Debug + ToCss where
G: ToCss,
R: ToCss,
U: ToCss,
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.to_css(f) self.to_css(&mut CssWriter::new(f))
} }
} }
impl<G, R, U> ToCss for Image<G, R, U> impl<G, R, U> ToCss for Image<G, R, U>
where G: ToCss, R: ToCss, U: ToCss where G: ToCss, R: ToCss, U: ToCss
{ {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self { match *self {
Image::Url(ref url) => url.to_css(dest), Image::Url(ref url) => url.to_css(dest),
Image::Gradient(ref gradient) => gradient.to_css(dest), Image::Gradient(ref gradient) => gradient.to_css(dest),
@ -198,7 +207,10 @@ impl<G, R, U> ToCss for Image<G, R, U>
impl<D, L, LoP, P, C, A> ToCss for Gradient<D, L, LoP, P, C, A> impl<D, L, LoP, P, C, A> ToCss for Gradient<D, L, LoP, P, C, A>
where D: LineDirection, L: ToCss, LoP: ToCss, P: ToCss, C: ToCss, A: ToCss where D: LineDirection, L: ToCss, LoP: ToCss, P: ToCss, C: ToCss, A: ToCss
{ {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match self.compat_mode { match self.compat_mode {
CompatMode::WebKit => dest.write_str("-webkit-")?, CompatMode::WebKit => dest.write_str("-webkit-")?,
CompatMode::Moz => dest.write_str("-moz-")?, CompatMode::Moz => dest.write_str("-moz-")?,
@ -272,17 +284,17 @@ pub trait LineDirection {
fn points_downwards(&self, compat_mode: CompatMode) -> bool; fn points_downwards(&self, compat_mode: CompatMode) -> bool;
/// Serialises this direction according to the compatibility mode. /// Serialises this direction according to the compatibility mode.
fn to_css<W>(&self, dest: &mut W, compat_mode: CompatMode) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>, compat_mode: CompatMode) -> fmt::Result
where W: fmt::Write; where W: Write;
} }
impl<L> ToCss for Circle<L> impl<L> ToCss for Circle<L>
where where
L: ToCss, L: ToCss,
{ {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where where
W: fmt::Write, W: Write,
{ {
match *self { match *self {
Circle::Extent(ShapeExtent::FarthestCorner) | Circle::Extent(ShapeExtent::FarthestCorner) |

View file

@ -8,8 +8,9 @@
use counter_style::{Symbols, parse_counter_style_name}; use counter_style::{Symbols, parse_counter_style_name};
use cssparser::Parser; use cssparser::Parser;
use parser::{Parse, ParserContext}; use parser::{Parse, ParserContext};
use std::fmt; use std::fmt::{self, Write};
use style_traits::{Comma, OneOrMoreSeparated, ParseError, StyleParseErrorKind, ToCss}; use style_traits::{Comma, CssWriter, OneOrMoreSeparated, ParseError};
use style_traits::{StyleParseErrorKind, ToCss};
use super::CustomIdent; use super::CustomIdent;
pub mod background; pub mod background;
@ -144,7 +145,10 @@ impl<T> OneOrMoreSeparated for FontSettingTag<T> {
} }
impl<T: ToCss> ToCss for FontSettingTag<T> { impl<T: ToCss> ToCss for FontSettingTag<T> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
use byteorder::{BigEndian, ByteOrder}; use byteorder::{BigEndian, ByteOrder};
use std::str; use std::str;
@ -231,7 +235,10 @@ pub struct FontSettingTagInt(pub u32);
pub struct FontSettingTagFloat(pub f32); pub struct FontSettingTagFloat(pub f32);
impl ToCss for FontSettingTagInt { impl ToCss for FontSettingTagInt {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match self.0 { match self.0 {
1 => Ok(()), 1 => Ok(()),
0 => dest.write_str(" off"), 0 => dest.write_str(" off"),
@ -273,7 +280,10 @@ impl Parse for FontSettingTagFloat {
} }
impl ToCss for FontSettingTagFloat { impl ToCss for FontSettingTagFloat {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str(" ")?; dest.write_str(" ")?;
self.0.to_css(dest) self.0.to_css(dest)
} }

View file

@ -6,8 +6,8 @@
use cssparser::Parser; use cssparser::Parser;
use parser::{Parse, ParserContext}; use parser::{Parse, ParserContext};
use std::fmt; use std::fmt::{self, Write};
use style_traits::{ToCss, ParseError}; use style_traits::{CssWriter, ParseError, ToCss};
/// A CSS value made of four components, where its `ToCss` impl will try to /// A CSS value made of four components, where its `ToCss` impl will try to
/// serialize as few components as possible, like for example in `border-width`. /// serialize as few components as possible, like for example in `border-width`.
@ -68,8 +68,9 @@ impl<T> Parse for Rect<T>
impl<T> ToCss for Rect<T> impl<T> ToCss for Rect<T>
where T: PartialEq + ToCss where T: PartialEq + ToCss
{ {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write, where
W: Write,
{ {
self.0.to_css(dest)?; self.0.to_css(dest)?;
let same_vertical = self.0 == self.2; let same_vertical = self.0 == self.2;

View file

@ -7,8 +7,8 @@
use cssparser::Parser; use cssparser::Parser;
use euclid::Size2D; use euclid::Size2D;
use parser::ParserContext; use parser::ParserContext;
use std::fmt; use std::fmt::{self, Write};
use style_traits::{ToCss, ParseError}; use style_traits::{CssWriter, ParseError, ToCss};
use values::animated::ToAnimatedValue; use values::animated::ToAnimatedValue;
/// A generic size, for `border-*-radius` longhand properties, or /// A generic size, for `border-*-radius` longhand properties, or
@ -56,9 +56,9 @@ impl<L> ToCss for Size<L>
where L: where L:
ToCss + PartialEq, ToCss + PartialEq,
{ {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: where
fmt::Write W: Write,
{ {
self.0.width.to_css(dest)?; self.0.width.to_css(dest)?;

View file

@ -6,8 +6,8 @@
use cssparser::Parser; use cssparser::Parser;
use parser::{Parse, ParserContext}; use parser::{Parse, ParserContext};
use std::fmt; use std::fmt::{self, Write};
use style_traits::{ParseError, StyleParseErrorKind, ToCss}; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use values::{Either, None_}; use values::{Either, None_};
use values::computed::NumberOrPercentage; use values::computed::NumberOrPercentage;
use values::computed::length::LengthOrPercentage; use values::computed::length::LengthOrPercentage;
@ -209,7 +209,10 @@ pub enum SVGStrokeDashArray<LengthType> {
} }
impl<LengthType> ToCss for SVGStrokeDashArray<LengthType> where LengthType: ToCss { impl<LengthType> ToCss for SVGStrokeDashArray<LengthType> where LengthType: ToCss {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match self { match self {
&SVGStrokeDashArray::Values(ref values) => { &SVGStrokeDashArray::Values(ref values) => {
let mut iter = values.iter(); let mut iter = values.iter();

View file

@ -7,8 +7,8 @@
use app_units::Au; use app_units::Au;
use euclid::{self, Rect, Transform3D}; use euclid::{self, Rect, Transform3D};
use num_traits::Zero; use num_traits::Zero;
use std::fmt; use std::fmt::{self, Write};
use style_traits::ToCss; use style_traits::{CssWriter, ToCss};
use values::{computed, CSSFloat}; use values::{computed, CSSFloat};
use values::computed::length::Length as ComputedLength; use values::computed::length::Length as ComputedLength;
use values::computed::length::LengthOrPercentage as ComputedLengthOrPercentage; use values::computed::length::LengthOrPercentage as ComputedLengthOrPercentage;
@ -136,9 +136,9 @@ where
Integer: ToCss, Integer: ToCss,
Number: ToCss, Number: ToCss,
{ {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where where
W: fmt::Write, W: Write,
{ {
match *self { match *self {
TimingFunction::Keyword(keyword) => keyword.to_css(dest), TimingFunction::Keyword(keyword) => keyword.to_css(dest),
@ -546,7 +546,10 @@ impl<Angle: ToCss + Copy, Number: ToCss + Copy, Length: ToCss,
Integer: ToCss + Copy, LengthOrNumber: ToCss, LengthOrPercentage: ToCss, LoPoNumber: ToCss> Integer: ToCss + Copy, LengthOrNumber: ToCss, LengthOrPercentage: ToCss, LoPoNumber: ToCss>
ToCss for ToCss for
TransformOperation<Angle, Number, Length, Integer, LengthOrNumber, LengthOrPercentage, LoPoNumber> { TransformOperation<Angle, Number, Length, Integer, LengthOrNumber, LengthOrPercentage, LoPoNumber> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self { match *self {
TransformOperation::Matrix(ref m) => m.to_css(dest), TransformOperation::Matrix(ref m) => m.to_css(dest),
TransformOperation::PrefixedMatrix(ref m) => m.to_css(dest), TransformOperation::PrefixedMatrix(ref m) => m.to_css(dest),
@ -653,9 +656,9 @@ impl<Angle: ToCss + Copy, Number: ToCss + Copy, Length: ToCss,
} }
impl<T: ToCss> ToCss for Transform<T> { impl<T: ToCss> ToCss for Transform<T> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where where
W: fmt::Write, W: Write,
{ {
if self.0.is_empty() { if self.0.is_empty() {
return dest.write_str("none"); return dest.write_str("none");

View file

@ -13,9 +13,9 @@ pub use cssparser::{RGBA, Token, Parser, serialize_identifier, CowRcStr, SourceL
use parser::{Parse, ParserContext}; use parser::{Parse, ParserContext};
use selectors::parser::SelectorParseErrorKind; use selectors::parser::SelectorParseErrorKind;
#[allow(unused_imports)] use std::ascii::AsciiExt; #[allow(unused_imports)] use std::ascii::AsciiExt;
use std::fmt::{self, Debug}; use std::fmt::{self, Debug, Write};
use std::hash; use std::hash;
use style_traits::{ToCss, ParseError, StyleParseErrorKind}; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
pub mod animated; pub mod animated;
pub mod computed; pub mod computed;
@ -34,8 +34,9 @@ define_keyword_type!(Auto, "auto");
define_keyword_type!(Normal, "normal"); define_keyword_type!(Normal, "normal");
/// Serialize a normalized value into percentage. /// Serialize a normalized value into percentage.
pub fn serialize_percentage<W>(value: CSSFloat, dest: &mut W) pub fn serialize_percentage<W>(value: CSSFloat, dest: &mut CssWriter<W>) -> fmt::Result
-> fmt::Result where W: fmt::Write where
W: Write,
{ {
(value * 100.).to_css(dest)?; (value * 100.).to_css(dest)?;
dest.write_str("%") dest.write_str("%")
@ -109,7 +110,10 @@ impl CustomIdent {
} }
impl ToCss for CustomIdent { impl ToCss for CustomIdent {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
serialize_identifier(&self.0.to_string(), dest) serialize_identifier(&self.0.to_string(), dest)
} }
} }
@ -180,7 +184,10 @@ impl Parse for KeyframesName {
} }
impl ToCss for KeyframesName { impl ToCss for KeyframesName {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self { match *self {
KeyframesName::Ident(ref ident) => ident.to_css(dest), KeyframesName::Ident(ref ident) => ident.to_css(dest),
KeyframesName::QuotedString(ref atom) => atom.to_string().to_css(dest), KeyframesName::QuotedString(ref atom) => atom.to_string().to_css(dest),

View file

@ -11,8 +11,8 @@ use gecko_bindings::structs;
use parser::{Parse, ParserContext}; use parser::{Parse, ParserContext};
use selectors::parser::SelectorParseErrorKind; use selectors::parser::SelectorParseErrorKind;
#[allow(unused_imports)] use std::ascii::AsciiExt; #[allow(unused_imports)] use std::ascii::AsciiExt;
use std::fmt; use std::fmt::{self, Write};
use style_traits::{ToCss, ParseError, StyleParseErrorKind}; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
bitflags! { bitflags! {
/// Constants shared by multiple CSS Box Alignment properties /// Constants shared by multiple CSS Box Alignment properties
@ -71,7 +71,10 @@ bitflags! {
} }
impl ToCss for AlignFlags { impl ToCss for AlignFlags {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
let s = match *self & !AlignFlags::FLAG_BITS { let s = match *self & !AlignFlags::FLAG_BITS {
AlignFlags::AUTO => "auto", AlignFlags::AUTO => "auto",
AlignFlags::NORMAL => "normal", AlignFlags::NORMAL => "normal",
@ -209,7 +212,10 @@ impl AlignJustifyContent {
} }
impl ToCss for AlignJustifyContent { impl ToCss for AlignJustifyContent {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
self.primary().to_css(dest)?; self.primary().to_css(dest)?;
match self.fallback() { match self.fallback() {
AlignFlags::AUTO => {} AlignFlags::AUTO => {}

View file

@ -7,8 +7,8 @@
use cssparser::{Parser, Token}; use cssparser::{Parser, Token};
use parser::{ParserContext, Parse}; use parser::{ParserContext, Parse};
#[allow(unused_imports)] use std::ascii::AsciiExt; #[allow(unused_imports)] use std::ascii::AsciiExt;
use std::fmt; use std::fmt::{self, Write};
use style_traits::{ToCss, ParseError}; use style_traits::{CssWriter, ParseError, ToCss};
use values::CSSFloat; use values::CSSFloat;
use values::computed::{Context, ToComputedValue}; use values::computed::{Context, ToComputedValue};
use values::computed::angle::Angle as ComputedAngle; use values::computed::angle::Angle as ComputedAngle;
@ -27,7 +27,10 @@ pub struct Angle {
} }
impl ToCss for Angle { impl ToCss for Angle {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if self.was_calc { if self.was_calc {
dest.write_str("calc(")?; dest.write_str("calc(")?;
} }

View file

@ -10,8 +10,8 @@
use cssparser::Parser; use cssparser::Parser;
use parser::{Parse, ParserContext}; use parser::{Parse, ParserContext};
use std::borrow::Cow; use std::borrow::Cow;
use std::fmt; use std::fmt::{self, Write};
use style_traits::{ToCss, ParseError, StyleParseErrorKind}; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use values::computed::Percentage; use values::computed::Percentage;
use values::generics::basic_shape::{Circle as GenericCircle}; use values::generics::basic_shape::{Circle as GenericCircle};
use values::generics::basic_shape::{ClippingShape as GenericClippingShape, Ellipse as GenericEllipse}; use values::generics::basic_shape::{ClippingShape as GenericClippingShape, Ellipse as GenericEllipse};
@ -171,7 +171,10 @@ impl Circle {
} }
impl ToCss for Circle { impl ToCss for Circle {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("circle(")?; dest.write_str("circle(")?;
if GenericShapeRadius::ClosestSide != self.radius { if GenericShapeRadius::ClosestSide != self.radius {
self.radius.to_css(dest)?; self.radius.to_css(dest)?;
@ -213,7 +216,10 @@ impl Ellipse {
} }
impl ToCss for Ellipse { impl ToCss for Ellipse {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("ellipse(")?; dest.write_str("ellipse(")?;
if self.semiaxis_x != ShapeRadius::default() || self.semiaxis_y != ShapeRadius::default() { if self.semiaxis_x != ShapeRadius::default() || self.semiaxis_y != ShapeRadius::default() {
self.semiaxis_x.to_css(dest)?; self.semiaxis_x.to_css(dest)?;
@ -248,8 +254,12 @@ impl Parse for ShapeRadius {
/// are converted to percentages where possible. Only the two or four /// are converted to percentages where possible. Only the two or four
/// value forms are used. In case of two keyword-percentage pairs, /// value forms are used. In case of two keyword-percentage pairs,
/// the keywords are folded into the percentages /// the keywords are folded into the percentages
fn serialize_basicshape_position<W>(position: &Position, dest: &mut W) -> fmt::Result fn serialize_basicshape_position<W>(
where W: fmt::Write position: &Position,
dest: &mut CssWriter<W>,
) -> fmt::Result
where
W: Write,
{ {
fn to_keyword_and_lop<S>(component: &PositionComponent<S>) -> (S, Cow<LengthOrPercentage>) fn to_keyword_and_lop<S>(component: &PositionComponent<S>) -> (S, Cow<LengthOrPercentage>)
where S: Copy + Side where S: Copy + Side
@ -289,8 +299,11 @@ fn serialize_basicshape_position<W>(position: &Position, dest: &mut W) -> fmt::R
} }
} }
fn write_pair<A, B, W>(a: &A, b: &B, dest: &mut W) -> fmt::Result fn write_pair<A, B, W>(a: &A, b: &B, dest: &mut CssWriter<W>) -> fmt::Result
where A: ToCss, B: ToCss, W: fmt::Write where
A: ToCss,
B: ToCss,
W: Write,
{ {
a.to_css(dest)?; a.to_css(dest)?;
dest.write_str(" ")?; dest.write_str(" ")?;

View file

@ -8,8 +8,8 @@ use Atom;
use cssparser::Parser; use cssparser::Parser;
use parser::{Parse, ParserContext}; use parser::{Parse, ParserContext};
use selectors::parser::SelectorParseErrorKind; use selectors::parser::SelectorParseErrorKind;
use std::fmt; use std::fmt::{self, Write};
use style_traits::{ParseError, ToCss, StyleParseErrorKind}; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use values::CustomIdent; use values::CustomIdent;
use values::KeyframesName; use values::KeyframesName;
use values::generics::box_::AnimationIterationCount as GenericAnimationIterationCount; use values::generics::box_::AnimationIterationCount as GenericAnimationIterationCount;
@ -289,9 +289,9 @@ impl AnimationName {
} }
impl ToCss for AnimationName { impl ToCss for AnimationName {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where where
W: fmt::Write, W: Write,
{ {
match self.0 { match self.0 {
Some(ref name) => name.to_css(dest), Some(ref name) => name.to_css(dest),
@ -407,7 +407,10 @@ impl TouchAction {
} }
impl ToCss for TouchAction { impl ToCss for TouchAction {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self { match *self {
TouchAction::TOUCH_ACTION_NONE => dest.write_str("none"), TouchAction::TOUCH_ACTION_NONE => dest.write_str("none"),
TouchAction::TOUCH_ACTION_AUTO => dest.write_str("auto"), TouchAction::TOUCH_ACTION_AUTO => dest.write_str("auto"),
@ -497,7 +500,10 @@ bitflags! {
} }
impl ToCss for Contain { impl ToCss for Contain {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if self.is_empty() { if self.is_empty() {
return dest.write_str("none") return dest.write_str("none")
} }

View file

@ -9,8 +9,8 @@
use cssparser::{Parser, Token, NumberOrPercentage, AngleOrNumber}; use cssparser::{Parser, Token, NumberOrPercentage, AngleOrNumber};
use parser::ParserContext; use parser::ParserContext;
#[allow(unused_imports)] use std::ascii::AsciiExt; #[allow(unused_imports)] use std::ascii::AsciiExt;
use std::fmt; use std::fmt::{self, Write};
use style_traits::{ToCss, ParseError, StyleParseErrorKind}; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use style_traits::values::specified::AllowedNumericType; use style_traits::values::specified::AllowedNumericType;
use values::{CSSInteger, CSSFloat}; use values::{CSSInteger, CSSFloat};
use values::computed; use values::computed;
@ -89,7 +89,10 @@ impl ToCss for CalcLengthOrPercentage {
/// ///
/// FIXME(emilio): Should this simplify away zeros? /// FIXME(emilio): Should this simplify away zeros?
#[allow(unused_assignments)] #[allow(unused_assignments)]
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
use num_traits::Zero; use num_traits::Zero;
let mut first_value = true; let mut first_value = true;

View file

@ -12,9 +12,9 @@ use itoa;
use parser::{ParserContext, Parse}; use parser::{ParserContext, Parse};
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
use properties::longhands::system_colors::SystemColor; use properties::longhands::system_colors::SystemColor;
use std::fmt; use std::fmt::{self, Write};
use std::io::Write; use std::io::Write as IoWrite;
use style_traits::{ToCss, ParseError, StyleParseErrorKind, ValueParseErrorKind}; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss, ValueParseErrorKind};
use super::AllowQuirks; use super::AllowQuirks;
use values::computed::{Color as ComputedColor, Context, ToComputedValue}; use values::computed::{Color as ComputedColor, Context, ToComputedValue};
use values::specified::calc::CalcNode; use values::specified::calc::CalcNode;
@ -187,7 +187,10 @@ impl Parse for Color {
} }
impl ToCss for Color { impl ToCss for Color {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self { match *self {
Color::CurrentColor => CSSParserColor::CurrentColor.to_css(dest), Color::CurrentColor => CSSParserColor::CurrentColor.to_css(dest),
Color::Numeric { authored: Some(ref authored), .. } => dest.write_str(authored), Color::Numeric { authored: Some(ref authored), .. } => dest.write_str(authored),

View file

@ -16,8 +16,8 @@ use parser::{Parse, ParserContext};
use properties::longhands::system_font::SystemFont; use properties::longhands::system_font::SystemFont;
#[allow(unused_imports)] #[allow(unused_imports)]
use std::ascii::AsciiExt; use std::ascii::AsciiExt;
use std::fmt; use std::fmt::{self, Write};
use style_traits::{ToCss, StyleParseErrorKind, ParseError}; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use values::CustomIdent; use values::CustomIdent;
use values::computed::{font as computed, Context, Length, NonNegativeLength, ToComputedValue}; use values::computed::{font as computed, Context, Length, NonNegativeLength, ToComputedValue};
use values::computed::font::{SingleFontFamily, FontFamilyList, FamilyName}; use values::computed::font::{SingleFontFamily, FontFamilyList, FamilyName};
@ -144,7 +144,10 @@ pub enum FontSize {
} }
impl ToCss for FontSize { impl ToCss for FontSize {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self { match *self {
FontSize::Length(ref lop) => lop.to_css(dest), FontSize::Length(ref lop) => lop.to_css(dest),
FontSize::Keyword(info) => info.kw.to_css(dest), FontSize::Keyword(info) => info.kw.to_css(dest),
@ -243,7 +246,10 @@ impl MallocSizeOf for FontFamily {
} }
impl ToCss for FontFamily { impl ToCss for FontFamily {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self { match *self {
FontFamily::Values(ref v) => { FontFamily::Values(ref v) => {
let mut iter = v.iter(); let mut iter = v.iter();
@ -408,7 +414,10 @@ impl Default for KeywordSize {
} }
impl ToCss for KeywordSize { impl ToCss for KeywordSize {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str(match *self { dest.write_str(match *self {
KeywordSize::XXSmall => "xx-small", KeywordSize::XXSmall => "xx-small",
KeywordSize::XSmall => "x-small", KeywordSize::XSmall => "x-small",
@ -824,7 +833,10 @@ impl VariantAlternatesList {
} }
impl ToCss for VariantAlternatesList { impl ToCss for VariantAlternatesList {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if self.0.is_empty() { if self.0.is_empty() {
return dest.write_str("normal"); return dest.write_str("normal");
} }
@ -1031,7 +1043,10 @@ impl VariantEastAsian {
} }
impl ToCss for VariantEastAsian { impl ToCss for VariantEastAsian {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if self.is_empty() { if self.is_empty() {
return dest.write_str("normal") return dest.write_str("normal")
} }
@ -1265,7 +1280,10 @@ impl VariantLigatures {
} }
impl ToCss for VariantLigatures { impl ToCss for VariantLigatures {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if self.is_empty() { if self.is_empty() {
return dest.write_str("normal") return dest.write_str("normal")
} }
@ -1506,7 +1524,10 @@ impl VariantNumeric {
} }
impl ToCss for VariantNumeric { impl ToCss for VariantNumeric {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if self.is_empty() { if self.is_empty() {
return dest.write_str("normal") return dest.write_str("normal")
} }
@ -1801,7 +1822,10 @@ impl Parse for FontSynthesis {
} }
impl ToCss for FontSynthesis { impl ToCss for FontSynthesis {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if self.weight && self.style { if self.weight && self.style {
dest.write_str("weight style") dest.write_str("weight style")
} else if self.style { } else if self.style {
@ -1953,7 +1977,10 @@ impl Parse for XTextZoom {
} }
impl ToCss for XTextZoom { impl ToCss for XTextZoom {
fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, _: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
Ok(()) Ok(())
} }
} }
@ -1981,7 +2008,10 @@ impl Parse for XLang {
} }
impl ToCss for XLang { impl ToCss for XLang {
fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, _: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
Ok(()) Ok(())
} }
} }

View file

@ -16,8 +16,8 @@ use selectors::parser::SelectorParseErrorKind;
use servo_url::ServoUrl; use servo_url::ServoUrl;
use std::cmp::Ordering; use std::cmp::Ordering;
use std::f32::consts::PI; use std::f32::consts::PI;
use std::fmt; use std::fmt::{self, Write};
use style_traits::{ToCss, ParseError, StyleParseErrorKind}; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use values::{Either, None_}; use values::{Either, None_};
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
use values::computed::{Context, Position as ComputedPosition, ToComputedValue}; use values::computed::{Context, Position as ComputedPosition, ToComputedValue};
@ -659,8 +659,13 @@ impl GenericsLineDirection for LineDirection {
} }
} }
fn to_css<W>(&self, dest: &mut W, compat_mode: CompatMode) -> fmt::Result fn to_css<W>(
where W: fmt::Write &self,
dest: &mut CssWriter<W>,
compat_mode: CompatMode,
) -> fmt::Result
where
W: Write,
{ {
match *self { match *self {
LineDirection::Angle(angle) => { LineDirection::Angle(angle) => {

View file

@ -7,8 +7,8 @@
use cssparser::Parser; use cssparser::Parser;
use parser::{Parse, ParserContext}; use parser::{Parse, ParserContext};
use std::f64::consts::PI; use std::f64::consts::PI;
use std::fmt; use std::fmt::{self, Write};
use style_traits::{ParseError, StyleParseErrorKind, ToCss}; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use values::computed; use values::computed;
use values::computed::{Context, Orientation, ToComputedValue}; use values::computed::{Context, Orientation, ToComputedValue};
use values::specified::Angle; use values::specified::Angle;
@ -25,7 +25,10 @@ pub struct ImageOrientation {
} }
impl ToCss for ImageOrientation { impl ToCss for ImageOrientation {
fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if let Some(angle) = self.angle { if let Some(angle) = self.angle {
angle.to_css(dest)?; angle.to_css(dest)?;
if self.flipped { if self.flipped {

View file

@ -6,8 +6,8 @@
use cssparser::{Parser, Token}; use cssparser::{Parser, Token};
use parser::{Parse, ParserContext}; use parser::{Parse, ParserContext};
use std::fmt; use std::fmt::{self, Write};
use style_traits::{ParseError, StyleParseErrorKind, ToCss}; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use values::{Either, None_}; use values::{Either, None_};
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
use values::CustomIdent; use values::CustomIdent;
@ -114,7 +114,10 @@ impl Parse for ListStyleImage {
pub struct Quotes(pub Box<[(Box<str>, Box<str>)]>); pub struct Quotes(pub Box<[(Box<str>, Box<str>)]>);
impl ToCss for Quotes { impl ToCss for Quotes {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
let mut iter = self.0.iter(); let mut iter = self.0.iter();
match iter.next() { match iter.next() {

View file

@ -13,8 +13,8 @@ use parser::{ParserContext, Parse};
use self::url::SpecifiedUrl; use self::url::SpecifiedUrl;
#[allow(unused_imports)] use std::ascii::AsciiExt; #[allow(unused_imports)] use std::ascii::AsciiExt;
use std::f32; use std::f32;
use std::fmt; use std::fmt::{self, Write};
use style_traits::{ToCss, ParseError, StyleParseErrorKind}; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use style_traits::values::specified::AllowedNumericType; use style_traits::values::specified::AllowedNumericType;
use super::{Auto, CSSFloat, CSSInteger, Either, None_}; use super::{Auto, CSSFloat, CSSInteger, Either, None_};
use super::computed::{Context, ToComputedValue}; use super::computed::{Context, ToComputedValue};
@ -250,8 +250,9 @@ impl ToComputedValue for Number {
} }
impl ToCss for Number { impl ToCss for Number {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write, where
W: Write,
{ {
if self.calc_clamping_mode.is_some() { if self.calc_clamping_mode.is_some() {
dest.write_str("calc(")?; dest.write_str("calc(")?;
@ -476,8 +477,9 @@ impl ToComputedValue for Integer {
} }
impl ToCss for Integer { impl ToCss for Integer {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write, where
W: Write,
{ {
if self.was_calc { if self.was_calc {
dest.write_str("calc(")?; dest.write_str("calc(")?;
@ -560,7 +562,10 @@ pub struct ClipRect {
impl ToCss for ClipRect { impl ToCss for ClipRect {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("rect(")?; dest.write_str("rect(")?;
if let Some(ref top) = self.top { if let Some(ref top) = self.top {
@ -805,7 +810,10 @@ impl Attr {
} }
impl ToCss for Attr { impl ToCss for Attr {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("attr(")?; dest.write_str("attr(")?;
if let Some(ref ns) = self.namespace { if let Some(ref ns) = self.namespace {
serialize_identifier(&ns.0.to_string(), dest)?; serialize_identifier(&ns.0.to_string(), dest)?;

View file

@ -7,8 +7,8 @@
use cssparser::{Parser, Token}; use cssparser::{Parser, Token};
use parser::{Parse, ParserContext}; use parser::{Parse, ParserContext};
#[allow(unused_imports)] use std::ascii::AsciiExt; #[allow(unused_imports)] use std::ascii::AsciiExt;
use std::fmt; use std::fmt::{self, Write};
use style_traits::{ParseError, ToCss}; use style_traits::{CssWriter, ParseError, ToCss};
use style_traits::values::specified::AllowedNumericType; use style_traits::values::specified::AllowedNumericType;
use values::{CSSFloat, serialize_percentage}; use values::{CSSFloat, serialize_percentage};
use values::computed::{Context, ToComputedValue}; use values::computed::{Context, ToComputedValue};
@ -29,8 +29,9 @@ pub struct Percentage {
impl ToCss for Percentage { impl ToCss for Percentage {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write, where
W: Write,
{ {
if self.calc_clamping_mode.is_some() { if self.calc_clamping_mode.is_some() {
dest.write_str("calc(")?; dest.write_str("calc(")?;

View file

@ -11,10 +11,10 @@ use cssparser::Parser;
use hash::FnvHashMap; use hash::FnvHashMap;
use parser::{Parse, ParserContext}; use parser::{Parse, ParserContext};
use selectors::parser::SelectorParseErrorKind; use selectors::parser::SelectorParseErrorKind;
use std::fmt; use std::fmt::{self, Write};
use std::ops::Range; use std::ops::Range;
use str::HTML_SPACE_CHARACTERS; use str::HTML_SPACE_CHARACTERS;
use style_traits::{ToCss, StyleParseErrorKind, ParseError}; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use values::{Either, None_}; use values::{Either, None_};
use values::computed::{CalcLengthOrPercentage, LengthOrPercentage as ComputedLengthOrPercentage}; use values::computed::{CalcLengthOrPercentage, LengthOrPercentage as ComputedLengthOrPercentage};
use values::computed::{Context, Percentage, ToComputedValue}; use values::computed::{Context, Percentage, ToComputedValue};
@ -142,7 +142,10 @@ impl Position {
} }
impl ToCss for Position { impl ToCss for Position {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match (&self.horizontal, &self.vertical) { match (&self.horizontal, &self.vertical) {
(x_pos @ &PositionComponent::Side(_, Some(_)), &PositionComponent::Length(ref y_lop)) => { (x_pos @ &PositionComponent::Side(_, Some(_)), &PositionComponent::Length(ref y_lop)) => {
x_pos.to_css(dest)?; x_pos.to_css(dest)?;
@ -369,7 +372,10 @@ impl LegacyPosition {
} }
impl ToCss for LegacyPosition { impl ToCss for LegacyPosition {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
self.horizontal.to_css(dest)?; self.horizontal.to_css(dest)?;
dest.write_str(" ")?; dest.write_str(" ")?;
self.vertical.to_css(dest) self.vertical.to_css(dest)
@ -409,7 +415,10 @@ impl GridAutoFlow {
} }
impl ToCss for GridAutoFlow { impl ToCss for GridAutoFlow {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
self.autoflow.to_css(dest)?; self.autoflow.to_css(dest)?;
if self.dense { dest.write_str(" dense")?; } if self.dense { dest.write_str(" dense")?; }
@ -584,7 +593,10 @@ impl TemplateAreas {
} }
impl ToCss for TemplateAreas { impl ToCss for TemplateAreas {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
for (i, string) in self.strings.iter().enumerate() { for (i, string) in self.strings.iter().enumerate() {
if i != 0 { if i != 0 {
dest.write_str(" ")?; dest.write_str(" ")?;

View file

@ -6,8 +6,9 @@
use cssparser::Parser; use cssparser::Parser;
use parser::{Parse, ParserContext}; use parser::{Parse, ParserContext};
use std::fmt; use std::fmt::{self, Write};
use style_traits::{CommaWithSpace, ParseError, Separator, StyleParseErrorKind, ToCss}; use style_traits::{CommaWithSpace, CssWriter, ParseError, Separator};
use style_traits::{StyleParseErrorKind, ToCss};
use values::CustomIdent; use values::CustomIdent;
use values::generics::svg as generic; use values::generics::svg as generic;
use values::specified::{LengthOrPercentage, NonNegativeLengthOrPercentage, NonNegativeNumber}; use values::specified::{LengthOrPercentage, NonNegativeLengthOrPercentage, NonNegativeNumber};
@ -237,7 +238,10 @@ impl Parse for SVGPaintOrder {
} }
impl ToCss for SVGPaintOrder { impl ToCss for SVGPaintOrder {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if self.0 == 0 { if self.0 == 0 {
return dest.write_str("normal") return dest.write_str("normal")
} }

View file

@ -7,7 +7,7 @@
use cssparser::Parser; use cssparser::Parser;
use parser::{Parse, ParserContext}; use parser::{Parse, ParserContext};
use std::fmt; use std::fmt;
use style_traits::{ToCss, StyleParseErrorKind, ParseError}; use style_traits::{CssWriter, ToCss, StyleParseErrorKind, ParseError};
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)] #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)]
/// span. for `<col span>` pres attr /// span. for `<col span>` pres attr
@ -21,7 +21,7 @@ impl Parse for XSpan {
} }
impl ToCss for XSpan { impl ToCss for XSpan {
fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, _: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
Ok(()) Ok(())
} }
} }

View file

@ -8,8 +8,8 @@ use cssparser::{Parser, Token};
use parser::{Parse, ParserContext}; use parser::{Parse, ParserContext};
use selectors::parser::SelectorParseErrorKind; use selectors::parser::SelectorParseErrorKind;
#[allow(unused_imports)] use std::ascii::AsciiExt; #[allow(unused_imports)] use std::ascii::AsciiExt;
use std::fmt; use std::fmt::{self, Write};
use style_traits::{ParseError, StyleParseErrorKind, ToCss}; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use values::computed::{Context, ToComputedValue}; use values::computed::{Context, ToComputedValue};
use values::computed::text::LineHeight as ComputedLineHeight; use values::computed::text::LineHeight as ComputedLineHeight;
use values::computed::text::TextOverflow as ComputedTextOverflow; use values::computed::text::TextOverflow as ComputedTextOverflow;
@ -440,7 +440,10 @@ impl Parse for TextAlign {
} }
impl ToCss for TextAlign { impl ToCss for TextAlign {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self { match *self {
TextAlign::Keyword(key) => key.to_css(dest), TextAlign::Keyword(key) => key.to_css(dest),
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]

View file

@ -7,8 +7,8 @@
use cssparser::{Parser, Token}; use cssparser::{Parser, Token};
use parser::{ParserContext, Parse}; use parser::{ParserContext, Parse};
#[allow(unused_imports)] use std::ascii::AsciiExt; #[allow(unused_imports)] use std::ascii::AsciiExt;
use std::fmt; use std::fmt::{self, Write};
use style_traits::{ToCss, ParseError, StyleParseErrorKind}; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use style_traits::values::specified::AllowedNumericType; use style_traits::values::specified::AllowedNumericType;
use values::CSSFloat; use values::CSSFloat;
use values::computed::{Context, ToComputedValue}; use values::computed::{Context, ToComputedValue};
@ -133,9 +133,9 @@ impl Parse for Time {
} }
impl ToCss for Time { impl ToCss for Time {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where where
W: fmt::Write, W: Write,
{ {
if self.was_calc { if self.was_calc {
dest.write_str("calc(")?; dest.write_str("calc(")?;

View file

@ -6,8 +6,8 @@
use cssparser::Parser; use cssparser::Parser;
use parser::{Parse, ParserContext}; use parser::{Parse, ParserContext};
use std::fmt; use std::fmt::{self, Write};
use style_traits::{ParseError, StyleParseErrorKind, ToCss}; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
/// Specified value of `-moz-force-broken-image-icon` /// Specified value of `-moz-force-broken-image-icon`
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)] #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)]
@ -36,7 +36,10 @@ impl Parse for MozForceBrokenImageIcon {
} }
impl ToCss for MozForceBrokenImageIcon { impl ToCss for MozForceBrokenImageIcon {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str(if self.0 { "1" } else { "0" }) dest.write_str(if self.0 { "1" } else { "0" })
} }
} }

View file

@ -48,7 +48,7 @@ pub fn derive(input: DeriveInput) -> Tokens {
} }
quote! {{ quote! {{
let mut writer = ::style_traits::values::SequenceWriter::new(&mut *dest, #separator); let mut writer = ::style_traits::values::SequenceWriter::new(dest, #separator);
#expr #expr
Ok(()) Ok(())
}} }}
@ -78,7 +78,10 @@ pub fn derive(input: DeriveInput) -> Tokens {
impl #impl_generics ::style_traits::ToCss for #name #ty_generics #where_clause { impl #impl_generics ::style_traits::ToCss for #name #ty_generics #where_clause {
#[allow(unused_variables)] #[allow(unused_variables)]
#[inline] #[inline]
fn to_css<W>(&self, dest: &mut W) -> ::std::fmt::Result fn to_css<W>(
&self,
dest: &mut ::style_traits::CssWriter<W>,
) -> ::std::fmt::Result
where where
W: ::std::fmt::Write W: ::std::fmt::Write
{ {
@ -93,7 +96,10 @@ pub fn derive(input: DeriveInput) -> Tokens {
impls.append(quote! { impls.append(quote! {
impl #impl_generics ::std::fmt::Debug for #name #ty_generics #where_clause { impl #impl_generics ::std::fmt::Debug for #name #ty_generics #where_clause {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::style_traits::ToCss::to_css(self, f) ::style_traits::ToCss::to_css(
self,
&mut ::style_traits::CssWriter::new(f),
)
} }
} }
}); });

View file

@ -4,7 +4,7 @@
//! A list of common mouse cursors per CSS3-UI § 8.1.1. //! A list of common mouse cursors per CSS3-UI § 8.1.1.
use super::ToCss; use super::{CssWriter, ToCss};
macro_rules! define_cursor { macro_rules! define_cursor {
( (
@ -46,10 +46,14 @@ macro_rules! define_cursor {
} }
impl ToCss for CursorKind { impl ToCss for CursorKind {
fn to_css<W>(&self, dest: &mut W) -> ::std::fmt::Result where W: ::std::fmt::Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> ::std::fmt::Result where W: ::std::fmt::Write {
match *self { match *self {
$( CursorKind::$c_variant => dest.write_str($c_css), )+ $(CursorKind::$c_variant => {
$( #[cfg(feature = "gecko")] CursorKind::$g_variant => dest.write_str($g_css), )+ ::std::fmt::Write::write_str(dest, $c_css)
})+
$(#[cfg(feature = "gecko")] CursorKind::$g_variant => {
::std::fmt::Write::write_str(dest, $g_css)
})+
} }
} }
} }

View file

@ -78,7 +78,7 @@ pub mod values;
#[macro_use] #[macro_use]
pub mod viewport; pub mod viewport;
pub use values::{Comma, CommaWithSpace, OneOrMoreSeparated, Separator, Space, ToCss}; pub use values::{Comma, CommaWithSpace, CssWriter, OneOrMoreSeparated, Separator, Space, ToCss};
/// The error type for all CSS parsing routines. /// The error type for all CSS parsing routines.
pub type ParseError<'i> = cssparser::ParseError<'i, StyleParseErrorKind<'i>>; pub type ParseError<'i> = cssparser::ParseError<'i, StyleParseErrorKind<'i>>;

View file

@ -34,7 +34,7 @@ use std::fmt::{self, Write};
/// implement `Debug` by a single call to `ToCss::to_css`. /// implement `Debug` by a single call to `ToCss::to_css`.
pub trait ToCss { pub trait ToCss {
/// Serialize `self` in CSS syntax, writing to `dest`. /// Serialize `self` in CSS syntax, writing to `dest`.
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: Write; fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write;
/// Serialize `self` in CSS syntax and return a string. /// Serialize `self` in CSS syntax and return a string.
/// ///
@ -42,27 +42,27 @@ pub trait ToCss {
#[inline] #[inline]
fn to_css_string(&self) -> String { fn to_css_string(&self) -> String {
let mut s = String::new(); let mut s = String::new();
self.to_css(&mut s).unwrap(); self.to_css(&mut CssWriter::new(&mut s)).unwrap();
s s
} }
} }
impl<'a, T> ToCss for &'a T where T: ToCss + ?Sized { impl<'a, T> ToCss for &'a T where T: ToCss + ?Sized {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write {
(*self).to_css(dest) (*self).to_css(dest)
} }
} }
impl ToCss for str { impl ToCss for str {
#[inline] #[inline]
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write {
serialize_string(self, dest) serialize_string(self, dest)
} }
} }
impl ToCss for String { impl ToCss for String {
#[inline] #[inline]
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write {
serialize_string(self, dest) serialize_string(self, dest)
} }
} }
@ -72,11 +72,62 @@ where
T: ToCss, T: ToCss,
{ {
#[inline] #[inline]
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write {
self.as_ref().map_or(Ok(()), |value| value.to_css(dest)) self.as_ref().map_or(Ok(()), |value| value.to_css(dest))
} }
} }
/// A writer tailored for serialising CSS.
///
/// Coupled with SequenceWriter, this allows callers to transparently handle
/// things like comma-separated values etc.
pub struct CssWriter<'w, W: 'w> {
inner: &'w mut W,
prefix: Option<&'static str>,
}
impl<'w, W> CssWriter<'w, W>
where
W: Write,
{
/// Creates a new `CssWriter`.
#[inline]
pub fn new(inner: &'w mut W) -> Self {
Self { inner, prefix: Some("") }
}
}
impl<'w, W> Write for CssWriter<'w, W>
where
W: Write,
{
#[inline]
fn write_str(&mut self, s: &str) -> fmt::Result {
if s.is_empty() {
return Ok(());
}
if let Some(prefix) = self.prefix.take() {
// We are going to write things, but first we need to write
// the prefix that was set by `SequenceWriter::item`.
if !prefix.is_empty() {
self.inner.write_str(prefix)?;
}
}
self.inner.write_str(s)
}
#[inline]
fn write_char(&mut self, c: char) -> fmt::Result {
if let Some(prefix) = self.prefix.take() {
// See comment in `write_str`.
if !prefix.is_empty() {
self.inner.write_str(prefix)?;
}
}
self.inner.write_char(c)
}
}
#[macro_export] #[macro_export]
macro_rules! serialize_function { macro_rules! serialize_function {
($dest: expr, $name: ident($( $arg: expr, )+)) => { ($dest: expr, $name: ident($( $arg: expr, )+)) => {
@ -96,22 +147,23 @@ macro_rules! serialize_function {
} }
/// Convenience wrapper to serialise CSS values separated by a given string. /// Convenience wrapper to serialise CSS values separated by a given string.
pub struct SequenceWriter<'a, W> { pub struct SequenceWriter<'a, 'b: 'a, W: 'b> {
writer: TrackedWriter<W>, inner: &'a mut CssWriter<'b, W>,
separator: &'a str, separator: &'static str,
} }
impl<'a, W> SequenceWriter<'a, W> impl<'a, 'b, W> SequenceWriter<'a, 'b, W>
where where
W: Write, W: Write + 'b,
{ {
/// Create a new sequence writer. /// Create a new sequence writer.
#[inline] #[inline]
pub fn new(writer: W, separator: &'a str) -> Self { pub fn new(inner: &'a mut CssWriter<'b, W>, separator: &'static str) -> Self {
SequenceWriter { if inner.prefix.is_none() {
writer: TrackedWriter::new(writer), // See comment in `item`.
separator: separator, inner.prefix = Some("");
} }
Self { inner, separator }
} }
/// Serialises a CSS value, writing any separator as necessary. /// Serialises a CSS value, writing any separator as necessary.
@ -125,89 +177,34 @@ where
where where
T: ToCss, T: ToCss,
{ {
if self.writer.has_written { let old_prefix = self.inner.prefix;
item.to_css(&mut PrefixedWriter::new(&mut self.writer, self.separator)) if old_prefix.is_none() {
} else { // If there is no prefix in the inner writer, a previous
item.to_css(&mut self.writer) // call to this method produced output, which means we need
// to write the separator next time we produce output again.
self.inner.prefix = Some(self.separator);
}
item.to_css(&mut self.inner)?;
match (old_prefix, self.inner.prefix) {
(_, None) => {
// This call produced output and cleaned up after itself.
}
(None, Some(p)) => {
// Some previous call to `item` produced output,
// but this one did not, prefix should be the same as
// the one we set.
debug_assert_eq!(self.separator, p);
// We clean up here even though it's not necessary just
// to be able to do all these assertion checks.
self.inner.prefix = None;
}
(Some(old), Some(new)) => {
// No previous call to `item` produced output, and this one
// either.
debug_assert_eq!(old, new);
} }
} }
} Ok(())
struct TrackedWriter<W> {
writer: W,
has_written: bool,
}
impl<W> TrackedWriter<W>
where
W: Write,
{
#[inline]
fn new(writer: W) -> Self {
TrackedWriter {
writer: writer,
has_written: false,
}
}
}
impl<W> Write for TrackedWriter<W>
where
W: Write,
{
#[inline]
fn write_str(&mut self, s: &str) -> fmt::Result {
if !s.is_empty() {
self.has_written = true;
}
self.writer.write_str(s)
}
#[inline]
fn write_char(&mut self, c: char) -> fmt::Result {
self.has_written = true;
self.writer.write_char(c)
}
}
struct PrefixedWriter<'a, W> {
writer: W,
prefix: Option<&'a str>,
}
impl<'a, W> PrefixedWriter<'a, W>
where
W: Write,
{
#[inline]
fn new(writer: W, prefix: &'a str) -> Self {
PrefixedWriter {
writer: writer,
prefix: Some(prefix),
}
}
}
impl<'a, W> Write for PrefixedWriter<'a, W>
where
W: Write,
{
#[inline]
fn write_str(&mut self, s: &str) -> fmt::Result {
if !s.is_empty() {
if let Some(prefix) = self.prefix.take() {
self.writer.write_str(prefix)?;
}
}
self.writer.write_str(s)
}
#[inline]
fn write_char(&mut self, c: char) -> fmt::Result {
if let Some(prefix) = self.prefix.take() {
self.writer.write_str(prefix)?;
}
self.writer.write_char(c)
} }
} }
@ -332,7 +329,7 @@ impl OneOrMoreSeparated for UnicodeRange {
} }
impl<T> ToCss for Vec<T> where T: ToCss + OneOrMoreSeparated { impl<T> ToCss for Vec<T> where T: ToCss + OneOrMoreSeparated {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write {
let mut iter = self.iter(); let mut iter = self.iter();
iter.next().unwrap().to_css(dest)?; iter.next().unwrap().to_css(dest)?;
for item in iter { for item in iter {
@ -344,7 +341,7 @@ impl<T> ToCss for Vec<T> where T: ToCss + OneOrMoreSeparated {
} }
impl<T> ToCss for Box<T> where T: ?Sized + ToCss { impl<T> ToCss for Box<T> where T: ?Sized + ToCss {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: Write, where W: Write,
{ {
(**self).to_css(dest) (**self).to_css(dest)
@ -352,7 +349,7 @@ impl<T> ToCss for Box<T> where T: ?Sized + ToCss {
} }
impl<T> ToCss for Arc<T> where T: ?Sized + ToCss { impl<T> ToCss for Arc<T> where T: ?Sized + ToCss {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: Write, where W: Write,
{ {
(**self).to_css(dest) (**self).to_css(dest)
@ -360,7 +357,7 @@ impl<T> ToCss for Arc<T> where T: ?Sized + ToCss {
} }
impl ToCss for Au { impl ToCss for Au {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write {
self.to_f64_px().to_css(dest)?; self.to_f64_px().to_css(dest)?;
dest.write_str("px") dest.write_str("px")
} }
@ -369,7 +366,7 @@ impl ToCss for Au {
macro_rules! impl_to_css_for_predefined_type { macro_rules! impl_to_css_for_predefined_type {
($name: ty) => { ($name: ty) => {
impl<'a> ToCss for $name { impl<'a> ToCss for $name {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: Write { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write {
::cssparser::ToCss::to_css(self, dest) ::cssparser::ToCss::to_css(self, dest)
} }
} }
@ -479,11 +476,11 @@ macro_rules! __define_css_keyword_enum__actual {
} }
impl $crate::ToCss for $name { impl $crate::ToCss for $name {
fn to_css<W>(&self, dest: &mut W) -> ::std::fmt::Result fn to_css<W>(&self, dest: &mut $crate::CssWriter<W>) -> ::std::fmt::Result
where W: ::std::fmt::Write where W: ::std::fmt::Write
{ {
match *self { match *self {
$( $name::$variant => dest.write_str($css) ),+ $( $name::$variant => ::std::fmt::Write::write_str(dest, $css) ),+
} }
} }
} }

View file

@ -4,11 +4,11 @@
//! Helper types for the `@viewport` rule. //! Helper types for the `@viewport` rule.
use {CSSPixel, PinchZoomFactor, ParseError, ToCss}; use {CSSPixel, CssWriter, ParseError, PinchZoomFactor, ToCss};
use cssparser::Parser; use cssparser::Parser;
use euclid::TypedSize2D; use euclid::TypedSize2D;
#[allow(unused_imports)] use std::ascii::AsciiExt; #[allow(unused_imports)] use std::ascii::AsciiExt;
use std::fmt; use std::fmt::{self, Write};
define_css_keyword_enum!(UserZoom: define_css_keyword_enum!(UserZoom:
"zoom" => Zoom, "zoom" => Zoom,
@ -42,8 +42,9 @@ pub struct ViewportConstraints {
} }
impl ToCss for ViewportConstraints { impl ToCss for ViewportConstraints {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write where
W: Write,
{ {
dest.write_str("@viewport { width: ")?; dest.write_str("@viewport { width: ")?;
self.size.width.to_css(dest)?; self.size.width.to_css(dest)?;
@ -86,7 +87,7 @@ pub enum Zoom {
} }
impl ToCss for Zoom { impl ToCss for Zoom {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where W: fmt::Write, where W: fmt::Write,
{ {
match *self { match *self {

View file

@ -155,7 +155,7 @@ use style::values::distance::ComputeSquaredDistance;
use style::values::specified; use style::values::specified;
use style::values::specified::gecko::IntersectionObserverRootMargin; use style::values::specified::gecko::IntersectionObserverRootMargin;
use style::values::specified::source_size_list::SourceSizeList; use style::values::specified::source_size_list::SourceSizeList;
use style_traits::{ParsingMode, StyleParseErrorKind, ToCss}; use style_traits::{CssWriter, ParsingMode, StyleParseErrorKind, ToCss};
use super::error_reporter::ErrorReporter; use super::error_reporter::ErrorReporter;
use super::stylesheet_loader::StylesheetLoader; use super::stylesheet_loader::StylesheetLoader;
@ -731,7 +731,7 @@ pub extern "C" fn Servo_Shorthand_AnimationValues_Serialize(shorthand_property:
values.iter().map(|v| AnimationValue::as_arc(unsafe { &&*v.mRawPtr }).uncompute()).collect(); values.iter().map(|v| AnimationValue::as_arc(unsafe { &&*v.mRawPtr }).uncompute()).collect();
let mut string = String::new(); let mut string = String::new();
let rv = shorthand.longhands_to_css(declarations.iter(), &mut string); let rv = shorthand.longhands_to_css(declarations.iter(), &mut CssWriter::new(&mut string));
if rv.is_ok() { if rv.is_ok() {
let buffer = unsafe { buffer.as_mut().unwrap() }; let buffer = unsafe { buffer.as_mut().unwrap() };
buffer.assign_utf8(&string); buffer.assign_utf8(&string);
@ -1826,7 +1826,7 @@ pub extern "C" fn Servo_Keyframe_GetKeyText(
result: *mut nsAString result: *mut nsAString
) { ) {
read_locked_arc(keyframe, |keyframe: &Keyframe| { read_locked_arc(keyframe, |keyframe: &Keyframe| {
keyframe.selector.to_css(unsafe { result.as_mut().unwrap() }).unwrap() keyframe.selector.to_css(&mut CssWriter::new(unsafe { result.as_mut().unwrap() })).unwrap()
}) })
} }
@ -1966,7 +1966,7 @@ pub extern "C" fn Servo_PageRule_SetStyle(rule: RawServoPageRuleBorrowed,
pub extern "C" fn Servo_SupportsRule_GetConditionText(rule: RawServoSupportsRuleBorrowed, pub extern "C" fn Servo_SupportsRule_GetConditionText(rule: RawServoSupportsRuleBorrowed,
result: *mut nsAString) { result: *mut nsAString) {
read_locked_arc(rule, |rule: &SupportsRule| { read_locked_arc(rule, |rule: &SupportsRule| {
rule.condition.to_css(unsafe { result.as_mut().unwrap() }).unwrap(); rule.condition.to_css(&mut CssWriter::new(unsafe { result.as_mut().unwrap() })).unwrap();
}) })
} }
@ -1974,7 +1974,7 @@ pub extern "C" fn Servo_SupportsRule_GetConditionText(rule: RawServoSupportsRule
pub extern "C" fn Servo_DocumentRule_GetConditionText(rule: RawServoDocumentRuleBorrowed, pub extern "C" fn Servo_DocumentRule_GetConditionText(rule: RawServoDocumentRuleBorrowed,
result: *mut nsAString) { result: *mut nsAString) {
read_locked_arc(rule, |rule: &DocumentRule| { read_locked_arc(rule, |rule: &DocumentRule| {
rule.condition.to_css(unsafe { result.as_mut().unwrap() }).unwrap(); rule.condition.to_css(&mut CssWriter::new(unsafe { result.as_mut().unwrap() })).unwrap();
}) })
} }
@ -1982,7 +1982,7 @@ pub extern "C" fn Servo_DocumentRule_GetConditionText(rule: RawServoDocumentRule
pub extern "C" fn Servo_FontFeatureValuesRule_GetFontFamily(rule: RawServoFontFeatureValuesRuleBorrowed, pub extern "C" fn Servo_FontFeatureValuesRule_GetFontFamily(rule: RawServoFontFeatureValuesRuleBorrowed,
result: *mut nsAString) { result: *mut nsAString) {
read_locked_arc(rule, |rule: &FontFeatureValuesRule| { read_locked_arc(rule, |rule: &FontFeatureValuesRule| {
rule.font_family_to_css(unsafe { result.as_mut().unwrap() }).unwrap(); rule.font_family_to_css(&mut CssWriter::new(unsafe { result.as_mut().unwrap() })).unwrap();
}) })
} }
@ -1990,7 +1990,7 @@ pub extern "C" fn Servo_FontFeatureValuesRule_GetFontFamily(rule: RawServoFontFe
pub extern "C" fn Servo_FontFeatureValuesRule_GetValueText(rule: RawServoFontFeatureValuesRuleBorrowed, pub extern "C" fn Servo_FontFeatureValuesRule_GetValueText(rule: RawServoFontFeatureValuesRuleBorrowed,
result: *mut nsAString) { result: *mut nsAString) {
read_locked_arc(rule, |rule: &FontFeatureValuesRule| { read_locked_arc(rule, |rule: &FontFeatureValuesRule| {
rule.value_to_css(unsafe { result.as_mut().unwrap() }).unwrap(); rule.value_to_css(&mut CssWriter::new(unsafe { result.as_mut().unwrap() })).unwrap();
}) })
} }
@ -2698,7 +2698,7 @@ pub extern "C" fn Servo_SerializeFontValueForCanvas(
}; };
let mut string = String::new(); let mut string = String::new();
let rv = longhands.to_css_for_canvas(&mut string); let rv = longhands.to_css_for_canvas(&mut CssWriter::new(&mut string));
debug_assert!(rv.is_ok()); debug_assert!(rv.is_ok());
let buffer = unsafe { buffer.as_mut().unwrap() }; let buffer = unsafe { buffer.as_mut().unwrap() };
@ -2925,7 +2925,7 @@ pub extern "C" fn Servo_DeclarationBlock_HasCSSWideKeyword(
#[no_mangle] #[no_mangle]
pub extern "C" fn Servo_MediaList_GetText(list: RawServoMediaListBorrowed, result: *mut nsAString) { pub extern "C" fn Servo_MediaList_GetText(list: RawServoMediaListBorrowed, result: *mut nsAString) {
read_locked_arc(list, |list: &MediaList| { read_locked_arc(list, |list: &MediaList| {
list.to_css(unsafe { result.as_mut().unwrap() }).unwrap(); list.to_css(&mut CssWriter::new(unsafe { result.as_mut().unwrap() })).unwrap();
}) })
} }
@ -2981,7 +2981,7 @@ pub extern "C" fn Servo_MediaList_GetMediumAt(
) -> bool { ) -> bool {
read_locked_arc(list, |list: &MediaList| { read_locked_arc(list, |list: &MediaList| {
if let Some(media_query) = list.media_queries.get(index as usize) { if let Some(media_query) = list.media_queries.get(index as usize) {
media_query.to_css(unsafe { result.as_mut().unwrap() }).unwrap(); media_query.to_css(&mut CssWriter::new(unsafe { result.as_mut().unwrap() })).unwrap();
true true
} else { } else {
false false
@ -4394,7 +4394,7 @@ pub extern "C" fn Servo_GetCustomPropertyValue(
None => return false, None => return false,
}; };
computed_value.to_css(unsafe { value.as_mut().unwrap() }).unwrap(); computed_value.to_css(&mut CssWriter::new(unsafe { value.as_mut().unwrap() })).unwrap();
true true
} }

View file

@ -279,8 +279,7 @@ fn test_mq_expressions() {
fn test_to_css() { fn test_to_css() {
test_media_rule("@media print and (width: 43px) { }", |list, _| { test_media_rule("@media print and (width: 43px) { }", |list, _| {
let q = &list.media_queries[0]; let q = &list.media_queries[0];
let mut dest = String::new(); let dest = q.to_css_string();
assert_eq!(Ok(()), q.to_css(&mut dest));
assert_eq!(dest, "print and (width: 43px)"); assert_eq!(dest, "print and (width: 43px)");
}); });
} }