Skip to main content

leptos_css/
serialization.rs

1use std::fmt;
2
3/// Open serialization trait for CSS-like values.
4///
5/// This powers both [`fmt::Display`]-style formatting and the zero-allocation
6/// [`write_to`](CssWriteTo::write_to) method through a single implementation. Downstream types
7/// may implement this trait for application-specific serialization, but doing so does not make a
8/// type eligible for checked declarations; that capability is represented by the sealed
9/// [`CheckedCssValue`](crate::CheckedCssValue) trait.
10///
11/// ```rust
12/// use std::fmt;
13/// use leptos_css::CssWriteTo;
14///
15/// struct ExternalValue(&'static str);
16///
17/// impl CssWriteTo for ExternalValue {
18///     fn css_fmt<W: fmt::Write>(&self, output: &mut W) -> fmt::Result {
19///         output.write_str(self.0)
20///     }
21/// }
22///
23/// let mut output = String::new();
24/// ExternalValue("application-specific").write_to(&mut output);
25/// assert_eq!(output, "application-specific");
26/// ```
27///
28/// Serialization alone cannot enter the checked custom-property API:
29///
30/// ```compile_fail
31/// use std::fmt;
32/// use leptos_css::{CssCustomProperty, CssWriteTo};
33///
34/// struct Raw(&'static str);
35///
36/// impl CssWriteTo for Raw {
37///     fn css_fmt<W: fmt::Write>(&self, output: &mut W) -> fmt::Result {
38///         output.write_str(self.0)
39///     }
40/// }
41///
42/// let property = CssCustomProperty::<Raw>::new("--unsafe");
43/// let _ = property.declare(Raw("red;color:lime"));
44/// ```
45pub trait CssWriteTo {
46    /// Write the CSS representation to a `fmt::Write` target.
47    fn css_fmt<W: fmt::Write>(&self, w: &mut W) -> fmt::Result;
48
49    /// Write the CSS representation directly to a `String` buffer.
50    ///
51    /// This is infallible because `fmt::Write` for `String` never fails.
52    fn write_to(&self, buf: &mut String) {
53        let _ = self.css_fmt(buf);
54    }
55}