Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactoring, better ability to use cssparser-color as a separate crate. #377

Closed
wants to merge 13 commits into from
Closed
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "cssparser"
version = "0.33.0"
authors = [ "Simon Sapin <[email protected]>" ]
version = "0.34.0"
authors = ["Simon Sapin <[email protected]>"]

description = "Rust implementation of CSS Syntax Level 3"
documentation = "https://docs.rs/cssparser/"
Expand All @@ -20,11 +20,11 @@ difference = "2.0"
encoding_rs = "0.8"

[dependencies]
cssparser-macros = {path = "./macros", version = "0.6.1"}
cssparser-macros = { path = "./macros", version = "0.6.1" }
dtoa-short = "0.3"
itoa = "1.0"
phf = {version = "0.11.2", features = ["macros"]}
serde = {version = "1.0", optional = true}
phf = { version = "0.11.2", features = ["macros"] }
serde = { version = "1.0", features = ["derive"], optional = true }
smallvec = "1.0"

[features]
Expand Down
8 changes: 6 additions & 2 deletions color/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "cssparser-color"
version = "0.1.0"
version = "0.2.0"
authors = ["Emilio Cobos Álvarez <[email protected]>"]
description = "Color implementation based on cssparser"
documentation = "https://docs.rs/cssparser-color/"
Expand All @@ -12,7 +12,11 @@ edition = "2021"
path = "lib.rs"

[dependencies]
cssparser = { version = "0.33", path = ".." }
cssparser = { path = ".." }
serde = { version = "1.0", features = ["derive"], optional = true }

[features]
serde = ["cssparser/serde", "dep:serde"]

[dev-dependencies]
serde_json = "1.0.25"
Expand Down
129 changes: 15 additions & 114 deletions color/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ use cssparser::color::{
PredefinedColorSpace, OPAQUE,
};
use cssparser::{match_ignore_ascii_case, CowRcStr, ParseError, Parser, ToCss, Token};
#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::f32::consts::PI;
use std::fmt;
use std::str::FromStr;
Expand Down Expand Up @@ -52,13 +50,11 @@ where
P: ColorParser<'i>,
{
let location = input.current_source_location();
let token = input.next()?;
let token = input.try_next()?;
match *token {
Token::Hash(ref value) | Token::IDHash(ref value) => {
parse_hash_color(value.as_bytes()).map(|(r, g, b, a)| {
P::Output::from_rgba(r, g, b, a)
})
},
parse_hash_color(value.as_bytes()).map(|(r, g, b, a)| P::Output::from_rgba(r, g, b, a))
}
Token::Ident(ref value) => parse_color_keyword(value),
Token::Function(ref name) => {
let name = name.clone();
Expand Down Expand Up @@ -506,6 +502,7 @@ fn normalize_hue(hue: f32) -> f32 {
}

/// A color with red, green, blue, and alpha components, in a byte each.
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct RgbaLegacy {
/// The red component.
Expand Down Expand Up @@ -544,27 +541,6 @@ impl RgbaLegacy {
}
}

#[cfg(feature = "serde")]
impl Serialize for RgbaLegacy {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
(self.red, self.green, self.blue, self.alpha).serialize(serializer)
}
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for RgbaLegacy {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let (r, g, b, a) = Deserialize::deserialize(deserializer)?;
Ok(RgbaLegacy::new(r, g, b, a))
}
}

impl ToCss for RgbaLegacy {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where
Expand All @@ -588,6 +564,7 @@ impl ToCss for RgbaLegacy {

/// Color specified by hue, saturation and lightness components.
#[derive(Clone, Copy, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Hsl {
/// The hue component.
pub hue: Option<f32>,
Expand Down Expand Up @@ -632,29 +609,9 @@ impl ToCss for Hsl {
}
}

#[cfg(feature = "serde")]
impl Serialize for Hsl {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
(self.hue, self.saturation, self.lightness, self.alpha).serialize(serializer)
}
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Hsl {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let (lightness, a, b, alpha) = Deserialize::deserialize(deserializer)?;
Ok(Self::new(lightness, a, b, alpha))
}
}

/// Color specified by hue, whiteness and blackness components.
#[derive(Clone, Copy, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Hwb {
/// The hue component.
pub hue: Option<f32>,
Expand Down Expand Up @@ -699,32 +656,12 @@ impl ToCss for Hwb {
}
}

#[cfg(feature = "serde")]
impl Serialize for Hwb {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
(self.hue, self.whiteness, self.blackness, self.alpha).serialize(serializer)
}
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Hwb {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let (lightness, whiteness, blackness, alpha) = Deserialize::deserialize(deserializer)?;
Ok(Self::new(lightness, whiteness, blackness, alpha))
}
}

// NOTE: LAB and OKLAB is not declared inside the [impl_lab_like] macro,
// because it causes cbindgen to ignore them.

/// Color specified by lightness, a- and b-axis components.
#[derive(Clone, Copy, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Lab {
/// The lightness component.
pub lightness: Option<f32>,
Expand All @@ -738,6 +675,7 @@ pub struct Lab {

/// Color specified by lightness, a- and b-axis components.
#[derive(Clone, Copy, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Oklab {
/// The lightness component.
pub lightness: Option<f32>,
Expand Down Expand Up @@ -768,27 +706,6 @@ macro_rules! impl_lab_like {
}
}

#[cfg(feature = "serde")]
impl Serialize for $cls {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
(self.lightness, self.a, self.b, self.alpha).serialize(serializer)
}
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for $cls {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let (lightness, a, b, alpha) = Deserialize::deserialize(deserializer)?;
Ok(Self::new(lightness, a, b, alpha))
}
}

impl ToCss for $cls {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where
Expand Down Expand Up @@ -816,6 +733,7 @@ impl_lab_like!(Oklab, "oklab");

/// Color specified by lightness, chroma and hue components.
#[derive(Clone, Copy, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Lch {
/// The lightness component.
pub lightness: Option<f32>,
Expand All @@ -829,6 +747,7 @@ pub struct Lch {

/// Color specified by lightness, chroma and hue components.
#[derive(Clone, Copy, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Oklch {
/// The lightness component.
pub lightness: Option<f32>,
Expand Down Expand Up @@ -859,27 +778,6 @@ macro_rules! impl_lch_like {
}
}

#[cfg(feature = "serde")]
impl Serialize for $cls {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
(self.lightness, self.chroma, self.hue, self.alpha).serialize(serializer)
}
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for $cls {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let (lightness, chroma, hue, alpha) = Deserialize::deserialize(deserializer)?;
Ok(Self::new(lightness, chroma, hue, alpha))
}
}

impl ToCss for $cls {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where
Expand All @@ -905,6 +803,7 @@ impl_lch_like!(Oklch, "oklch");
/// A color specified by the color() function.
/// <https://drafts.csswg.org/css-color-4/#color-function>
#[derive(Clone, Copy, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct ColorFunction {
/// The color space for this color.
pub color_space: PredefinedColorSpace,
Expand Down Expand Up @@ -966,6 +865,8 @@ impl ToCss for ColorFunction {
///
/// <https://drafts.csswg.org/css-color-4/#color-type>
#[derive(Clone, Copy, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(tag = "type"))]
pub enum Color {
/// The 'currentcolor' keyword.
CurrentColor,
Expand Down Expand Up @@ -1090,7 +991,7 @@ pub trait ColorParser<'i> {
input: &mut Parser<'i, 't>,
) -> Result<AngleOrNumber, ParseError<'i, Self::Error>> {
let location = input.current_source_location();
Ok(match *input.next()? {
Ok(match *input.try_next()? {
Token::Number { value, .. } => AngleOrNumber::Number { value },
Token::Dimension {
value: v, ref unit, ..
Expand Down Expand Up @@ -1135,7 +1036,7 @@ pub trait ColorParser<'i> {
input: &mut Parser<'i, 't>,
) -> Result<NumberOrPercentage, ParseError<'i, Self::Error>> {
let location = input.current_source_location();
Ok(match *input.next()? {
Ok(match *input.try_next()? {
Token::Number { value, .. } => NumberOrPercentage::Number { value },
Token::Percentage { unit_value, .. } => NumberOrPercentage::Percentage { unit_value },
ref t => return Err(location.new_unexpected_token_error(t.clone())),
Expand Down
47 changes: 24 additions & 23 deletions color/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,21 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use super::*;
use crate::{ColorParser, PredefinedColorSpace, Color, RgbaLegacy};
use cssparser::{Parser, ParserInput};
use serde_json::{self, json, Value};
use cssparser::ParserInput;
use serde_json::{json, Value};

fn almost_equals(a: &Value, b: &Value) -> bool {
match (a, b) {
(&Value::Number(ref a), &Value::Number(ref b)) => {
(Value::Number(a), Value::Number(b)) => {
let a = a.as_f64().unwrap();
let b = b.as_f64().unwrap();
(a - b).abs() <= a.abs() * 1e-6
}

(&Value::Bool(a), &Value::Bool(b)) => a == b,
(&Value::String(ref a), &Value::String(ref b)) => a == b,
(&Value::Array(ref a), &Value::Array(ref b)) => {
a.len() == b.len()
&& a.iter()
.zip(b.iter())
.all(|(ref a, ref b)| almost_equals(*a, *b))
(Value::String(a), Value::String(b)) => a == b,
(Value::Array(a), Value::Array(b)) => {
a.len() == b.len() && a.iter().zip(b.iter()).all(|(a, b)| almost_equals(a, b))
}
(&Value::Object(_), &Value::Object(_)) => panic!("Not implemented"),
(&Value::Null, &Value::Null) => true,
Expand All @@ -43,8 +39,7 @@ fn assert_json_eq(results: Value, expected: Value, message: &str) {
}
}


fn run_raw_json_tests<F: Fn(Value, Value) -> ()>(json_data: &str, run: F) {
fn run_raw_json_tests<F: Fn(Value, Value)>(json_data: &str, run: F) {
let items = match serde_json::from_str(json_data) {
Ok(Value::Array(items)) => items,
other => panic!("Invalid JSON: {:?}", other),
Expand Down Expand Up @@ -92,11 +87,14 @@ fn color3() {
#[cfg_attr(all(miri, feature = "skip_long_tests"), ignore)]
#[test]
fn color3_hsl() {
run_color_tests(include_str!("../src/css-parsing-tests/color3_hsl.json"), |c| {
c.ok()
.map(|v| v.to_css_string().to_json())
.unwrap_or(Value::Null)
})
run_color_tests(
include_str!("../src/css-parsing-tests/color3_hsl.json"),
|c| {
c.ok()
.map(|v| v.to_css_string().to_json())
.unwrap_or(Value::Null)
},
)
}

/// color3_keywords.json is different: R, G and B are in 0..255 rather than 0..1
Expand All @@ -115,11 +113,14 @@ fn color3_keywords() {
#[cfg_attr(all(miri, feature = "skip_long_tests"), ignore)]
#[test]
fn color4_hwb() {
run_color_tests(include_str!("../src/css-parsing-tests/color4_hwb.json"), |c| {
c.ok()
.map(|v| v.to_css_string().to_json())
.unwrap_or(Value::Null)
})
run_color_tests(
include_str!("../src/css-parsing-tests/color4_hwb.json"),
|c| {
c.ok()
.map(|v| v.to_css_string().to_json())
.unwrap_or(Value::Null)
},
)
}

#[cfg_attr(all(miri, feature = "skip_long_tests"), ignore)]
Expand Down Expand Up @@ -355,7 +356,7 @@ fn generic_parser() {
];

for (input, expected) in TESTS {
let mut input = ParserInput::new(*input);
let mut input = ParserInput::new(input);
let mut input = Parser::new(&mut input);

let actual: OutputType = parse_color_with(&TestColorParser, &mut input).unwrap();
Expand Down
Loading
Loading