Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 546df5f

Browse files
committedJul 17, 2019
Switch from rustc-serialize to serde_json
1 parent e4cb8f1 commit 546df5f

File tree

3 files changed

+103
-76
lines changed

3 files changed

+103
-76
lines changed
 

‎Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ build = "build.rs"
1414
exclude = ["src/css-parsing-tests/**", "src/big-data-url.css"]
1515

1616
[dev-dependencies]
17-
rustc-serialize = "0.3"
17+
serde_json = "1.0"
1818
difference = "2.0"
1919
encoding_rs = "0.8"
2020

‎src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ extern crate encoding_rs;
8282
#[doc(hidden)]
8383
pub extern crate phf as _internal__phf;
8484
#[cfg(test)]
85-
extern crate rustc_serialize;
85+
extern crate serde_json;
8686
#[cfg(feature = "serde")]
8787
extern crate serde;
8888
#[cfg(feature = "heapsize")]

‎src/tests.rs

Lines changed: 101 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
extern crate test;
77

88
use encoding_rs;
9-
use rustc_serialize::json::{self, Json, ToJson};
9+
use serde_json::{self, Value, json, Map};
1010

1111
#[cfg(feature = "bench")]
1212
use self::test::Bencher;
@@ -21,40 +21,39 @@ use super::{
2121

2222
macro_rules! JArray {
2323
($($e: expr,)*) => { JArray![ $( $e ),* ] };
24-
($($e: expr),*) => { Json::Array(vec!( $( $e.to_json() ),* )) }
24+
($($e: expr),*) => { Value::Array(vec!( $( $e.to_json() ),* )) }
2525
}
2626

27-
fn almost_equals(a: &Json, b: &Json) -> bool {
27+
fn almost_equals(a: &Value, b: &Value) -> bool {
2828
match (a, b) {
29-
(&Json::I64(a), _) => almost_equals(&Json::F64(a as f64), b),
30-
(&Json::U64(a), _) => almost_equals(&Json::F64(a as f64), b),
31-
(_, &Json::I64(b)) => almost_equals(a, &Json::F64(b as f64)),
32-
(_, &Json::U64(b)) => almost_equals(a, &Json::F64(b as f64)),
33-
34-
(&Json::F64(a), &Json::F64(b)) => (a - b).abs() <= a.abs() * 1e-6,
29+
(&Value::Number(ref a), &Value::Number(ref b)) => {
30+
let a = a.as_f64().unwrap();
31+
let b = b.as_f64().unwrap();
32+
(a - b).abs() <= a.abs() * 1e-6
33+
},
3534

36-
(&Json::Boolean(a), &Json::Boolean(b)) => a == b,
37-
(&Json::String(ref a), &Json::String(ref b)) => a == b,
38-
(&Json::Array(ref a), &Json::Array(ref b)) => {
35+
(&Value::Bool(a), &Value::Bool(b)) => a == b,
36+
(&Value::String(ref a), &Value::String(ref b)) => a == b,
37+
(&Value::Array(ref a), &Value::Array(ref b)) => {
3938
a.len() == b.len()
4039
&& a.iter()
4140
.zip(b.iter())
4241
.all(|(ref a, ref b)| almost_equals(*a, *b))
4342
}
44-
(&Json::Object(_), &Json::Object(_)) => panic!("Not implemented"),
45-
(&Json::Null, &Json::Null) => true,
43+
(&Value::Object(_), &Value::Object(_)) => panic!("Not implemented"),
44+
(&Value::Null, &Value::Null) => true,
4645
_ => false,
4746
}
4847
}
4948

50-
fn normalize(json: &mut Json) {
49+
fn normalize(json: &mut Value) {
5150
match *json {
52-
Json::Array(ref mut list) => {
51+
Value::Array(ref mut list) => {
5352
for item in list.iter_mut() {
5453
normalize(item)
5554
}
5655
}
57-
Json::String(ref mut s) => {
56+
Value::String(ref mut s) => {
5857
if *s == "extra-input" || *s == "empty" {
5958
*s = "invalid".to_string()
6059
}
@@ -63,24 +62,24 @@ fn normalize(json: &mut Json) {
6362
}
6463
}
6564

66-
fn assert_json_eq(results: json::Json, mut expected: json::Json, message: &str) {
65+
fn assert_json_eq(results: Value, mut expected: Value, message: &str) {
6766
normalize(&mut expected);
6867
if !almost_equals(&results, &expected) {
6968
println!(
7069
"{}",
7170
::difference::Changeset::new(
72-
&results.pretty().to_string(),
73-
&expected.pretty().to_string(),
71+
&serde_json::to_string_pretty(&results).unwrap(),
72+
&serde_json::to_string_pretty(&expected).unwrap(),
7473
"\n",
7574
)
7675
);
7776
panic!("{}", message)
7877
}
7978
}
8079

81-
fn run_raw_json_tests<F: Fn(Json, Json) -> ()>(json_data: &str, run: F) {
82-
let items = match Json::from_str(json_data) {
83-
Ok(Json::Array(items)) => items,
80+
fn run_raw_json_tests<F: Fn(Value, Value) -> ()>(json_data: &str, run: F) {
81+
let items = match serde_json::from_str(json_data) {
82+
Ok(Value::Array(items)) => items,
8483
_ => panic!("Invalid JSON"),
8584
};
8685
assert!(items.len() % 2 == 0);
@@ -96,9 +95,9 @@ fn run_raw_json_tests<F: Fn(Json, Json) -> ()>(json_data: &str, run: F) {
9695
}
9796
}
9897

99-
fn run_json_tests<F: Fn(&mut Parser) -> Json>(json_data: &str, parse: F) {
98+
fn run_json_tests<F: Fn(&mut Parser) -> Value>(json_data: &str, parse: F) {
10099
run_raw_json_tests(json_data, |input, expected| match input {
101-
Json::String(input) => {
100+
Value::String(input) => {
102101
let mut parse_input = ParserInput::new(&input);
103102
let result = parse(&mut Parser::new(&mut parse_input));
104103
assert_json_eq(result, expected, &input);
@@ -111,7 +110,7 @@ fn run_json_tests<F: Fn(&mut Parser) -> Json>(json_data: &str, parse: F) {
111110
fn component_value_list() {
112111
run_json_tests(
113112
include_str!("css-parsing-tests/component_value_list.json"),
114-
|input| Json::Array(component_values_to_json(input)),
113+
|input| Value::Array(component_values_to_json(input)),
115114
);
116115
}
117116

@@ -120,7 +119,7 @@ fn one_component_value() {
120119
run_json_tests(
121120
include_str!("css-parsing-tests/one_component_value.json"),
122121
|input| {
123-
let result: Result<Json, ParseError<()>> = input.parse_entirely(|input| {
122+
let result: Result<Value, ParseError<()>> = input.parse_entirely(|input| {
124123
Ok(one_component_value_to_json(input.next()?.clone(), input))
125124
});
126125
result.unwrap_or(JArray!["error", "invalid"])
@@ -133,7 +132,7 @@ fn declaration_list() {
133132
run_json_tests(
134133
include_str!("css-parsing-tests/declaration_list.json"),
135134
|input| {
136-
Json::Array(
135+
Value::Array(
137136
DeclarationListParser::new(input, JsonParser)
138137
.map(|result| result.unwrap_or(JArray!["error", "invalid"]))
139138
.collect(),
@@ -155,7 +154,7 @@ fn one_declaration() {
155154
#[test]
156155
fn rule_list() {
157156
run_json_tests(include_str!("css-parsing-tests/rule_list.json"), |input| {
158-
Json::Array(
157+
Value::Array(
159158
RuleListParser::new_for_nested_rule(input, JsonParser)
160159
.map(|result| result.unwrap_or(JArray!["error", "invalid"]))
161160
.collect(),
@@ -166,7 +165,7 @@ fn rule_list() {
166165
#[test]
167166
fn stylesheet() {
168167
run_json_tests(include_str!("css-parsing-tests/stylesheet.json"), |input| {
169-
Json::Array(
168+
Value::Array(
170169
RuleListParser::new_for_stylesheet(input, JsonParser)
171170
.map(|result| result.unwrap_or(JArray!["error", "invalid"]))
172171
.collect(),
@@ -205,7 +204,7 @@ fn stylesheet_from_bytes() {
205204
include_str!("css-parsing-tests/stylesheet_bytes.json"),
206205
|input, expected| {
207206
let map = match input {
208-
Json::Object(map) => map,
207+
Value::Object(map) => map,
209208
_ => panic!("Unexpected JSON"),
210209
};
211210

@@ -237,14 +236,14 @@ fn stylesheet_from_bytes() {
237236
.collect::<Vec<_>>();
238237
JArray![rules, used_encoding.name().to_lowercase()]
239238
};
240-
assert_json_eq(result, expected, &Json::Object(map).to_string());
239+
assert_json_eq(result, expected, &Value::Object(map).to_string());
241240
},
242241
);
243242

244-
fn get_string<'a>(map: &'a json::Object, key: &str) -> Option<&'a str> {
243+
fn get_string<'a>(map: &'a Map<String, Value>, key: &str) -> Option<&'a str> {
245244
match map.get(key) {
246-
Some(&Json::String(ref s)) => Some(s),
247-
Some(&Json::Null) => None,
245+
Some(&Value::String(ref s)) => Some(s),
246+
Some(&Value::Null) => None,
248247
None => None,
249248
_ => panic!("Unexpected JSON"),
250249
}
@@ -354,7 +353,7 @@ fn test_expect_url() {
354353
assert!(parse(&mut input).is_err());
355354
}
356355

357-
fn run_color_tests<F: Fn(Result<Color, ()>) -> Json>(json_data: &str, to_json: F) {
356+
fn run_color_tests<F: Fn(Result<Color, ()>) -> Value>(json_data: &str, to_json: F) {
358357
run_json_tests(json_data, |input| {
359358
let result: Result<_, ParseError<()>> =
360359
input.parse_entirely(|i| Color::parse(i).map_err(Into::into));
@@ -365,14 +364,14 @@ fn run_color_tests<F: Fn(Result<Color, ()>) -> Json>(json_data: &str, to_json: F
365364
#[test]
366365
fn color3() {
367366
run_color_tests(include_str!("css-parsing-tests/color3.json"), |c| {
368-
c.ok().to_json()
367+
c.ok().map(|v| v.to_json()).unwrap_or(Value::Null)
369368
})
370369
}
371370

372371
#[test]
373372
fn color3_hsl() {
374373
run_color_tests(include_str!("css-parsing-tests/color3_hsl.json"), |c| {
375-
c.ok().to_json()
374+
c.ok().map(|v| v.to_json()).unwrap_or(Value::Null)
376375
})
377376
}
378377

@@ -381,7 +380,7 @@ fn color3_hsl() {
381380
fn color3_keywords() {
382381
run_color_tests(
383382
include_str!("css-parsing-tests/color3_keywords.json"),
384-
|c| c.ok().to_json(),
383+
|c| c.ok().map(|v| v.to_json()).unwrap_or(Value::Null),
385384
)
386385
}
387386

@@ -394,7 +393,8 @@ fn nth() {
394393
result
395394
})
396395
.ok()
397-
.to_json()
396+
.map(|(v0, v1)| json!([v0, v1]))
397+
.unwrap_or(Value::Null)
398398
});
399399
}
400400

@@ -410,7 +410,17 @@ fn unicode_range() {
410410
Ok(None)
411411
}
412412
});
413-
result.unwrap().to_json()
413+
result.unwrap()
414+
.iter()
415+
.map(|v|
416+
if let Some((v0, v1)) = v{
417+
json!([v0, v1])
418+
} else {
419+
Value::Null
420+
}
421+
)
422+
.collect::<Vec<_>>()
423+
.to_json()
414424
});
415425
}
416426

@@ -475,7 +485,7 @@ fn serializer(preserve_comments: bool) {
475485
);
476486
let mut input = ParserInput::new(&serialized);
477487
let parser = &mut Parser::new(&mut input);
478-
Json::Array(component_values_to_json(parser))
488+
Value::Array(component_values_to_json(parser))
479489
},
480490
);
481491
}
@@ -795,15 +805,32 @@ fn identifier_serialization() {
795805
);
796806
}
797807

808+
trait ToJson {
809+
fn to_json(&self) -> Value;
810+
}
811+
812+
impl<T> ToJson for T where T: Clone, Value: From<T> {
813+
fn to_json(&self) -> Value {
814+
Value::from(self.clone())
815+
}
816+
}
817+
798818
impl ToJson for Color {
799-
fn to_json(&self) -> json::Json {
819+
fn to_json(&self) -> Value {
800820
match *self {
801-
Color::RGBA(ref rgba) => [rgba.red, rgba.green, rgba.blue, rgba.alpha].to_json(),
821+
Color::RGBA(ref rgba) => json!([rgba.red, rgba.green, rgba.blue, rgba.alpha]),
802822
Color::CurrentColor => "currentcolor".to_json(),
803823
}
804824
}
805825
}
806826

827+
impl<'a> ToJson for CowRcStr<'a> {
828+
fn to_json(&self) -> Value {
829+
let s: &str = &*self;
830+
s.to_json()
831+
}
832+
}
833+
807834
#[cfg(feature = "bench")]
808835
const BACKGROUND_IMAGE: &'static str = include_str!("big-data-url.css");
809836

@@ -851,14 +878,14 @@ fn no_stack_overflow_multiple_nested_blocks() {
851878
}
852879

853880
impl<'i> DeclarationParser<'i> for JsonParser {
854-
type Declaration = Json;
881+
type Declaration = Value;
855882
type Error = ();
856883

857884
fn parse_value<'t>(
858885
&mut self,
859886
name: CowRcStr<'i>,
860887
input: &mut Parser<'i, 't>,
861-
) -> Result<Json, ParseError<'i, ()>> {
888+
) -> Result<Value, ParseError<'i, ()>> {
862889
let mut value = vec![];
863890
let mut important = false;
864891
loop {
@@ -889,20 +916,20 @@ impl<'i> DeclarationParser<'i> for JsonParser {
889916
}
890917

891918
impl<'i> AtRuleParser<'i> for JsonParser {
892-
type PreludeNoBlock = Vec<Json>;
893-
type PreludeBlock = Vec<Json>;
894-
type AtRule = Json;
919+
type PreludeNoBlock = Vec<Value>;
920+
type PreludeBlock = Vec<Value>;
921+
type AtRule = Value;
895922
type Error = ();
896923

897924
fn parse_prelude<'t>(
898925
&mut self,
899926
name: CowRcStr<'i>,
900927
input: &mut Parser<'i, 't>,
901-
) -> Result<AtRuleType<Vec<Json>, Vec<Json>>, ParseError<'i, ()>> {
928+
) -> Result<AtRuleType<Vec<Value>, Vec<Value>>, ParseError<'i, ()>> {
902929
let prelude = vec![
903930
"at-rule".to_json(),
904931
name.to_json(),
905-
Json::Array(component_values_to_json(input)),
932+
Value::Array(component_values_to_json(input)),
906933
];
907934
match_ignore_ascii_case! { &*name,
908935
"media" | "foo-with-block" => Ok(AtRuleType::WithBlock(prelude)),
@@ -913,40 +940,40 @@ impl<'i> AtRuleParser<'i> for JsonParser {
913940
}
914941
}
915942

916-
fn rule_without_block(&mut self, mut prelude: Vec<Json>, _location: SourceLocation) -> Json {
917-
prelude.push(Json::Null);
918-
Json::Array(prelude)
943+
fn rule_without_block(&mut self, mut prelude: Vec<Value>, _location: SourceLocation) -> Value {
944+
prelude.push(Value::Null);
945+
Value::Array(prelude)
919946
}
920947

921948
fn parse_block<'t>(
922949
&mut self,
923-
mut prelude: Vec<Json>,
950+
mut prelude: Vec<Value>,
924951
_location: SourceLocation,
925952
input: &mut Parser<'i, 't>,
926-
) -> Result<Json, ParseError<'i, ()>> {
927-
prelude.push(Json::Array(component_values_to_json(input)));
928-
Ok(Json::Array(prelude))
953+
) -> Result<Value, ParseError<'i, ()>> {
954+
prelude.push(Value::Array(component_values_to_json(input)));
955+
Ok(Value::Array(prelude))
929956
}
930957
}
931958

932959
impl<'i> QualifiedRuleParser<'i> for JsonParser {
933-
type Prelude = Vec<Json>;
934-
type QualifiedRule = Json;
960+
type Prelude = Vec<Value>;
961+
type QualifiedRule = Value;
935962
type Error = ();
936963

937964
fn parse_prelude<'t>(
938965
&mut self,
939966
input: &mut Parser<'i, 't>,
940-
) -> Result<Vec<Json>, ParseError<'i, ()>> {
967+
) -> Result<Vec<Value>, ParseError<'i, ()>> {
941968
Ok(component_values_to_json(input))
942969
}
943970

944971
fn parse_block<'t>(
945972
&mut self,
946-
prelude: Vec<Json>,
973+
prelude: Vec<Value>,
947974
_location: SourceLocation,
948975
input: &mut Parser<'i, 't>,
949-
) -> Result<Json, ParseError<'i, ()>> {
976+
) -> Result<Value, ParseError<'i, ()>> {
950977
Ok(JArray![
951978
"qualified rule",
952979
prelude,
@@ -955,16 +982,16 @@ impl<'i> QualifiedRuleParser<'i> for JsonParser {
955982
}
956983
}
957984

958-
fn component_values_to_json(input: &mut Parser) -> Vec<Json> {
985+
fn component_values_to_json(input: &mut Parser) -> Vec<Value> {
959986
let mut values = vec![];
960987
while let Ok(token) = input.next_including_whitespace().map(|t| t.clone()) {
961988
values.push(one_component_value_to_json(token, input));
962989
}
963990
values
964991
}
965992

966-
fn one_component_value_to_json(token: Token, input: &mut Parser) -> Json {
967-
fn numeric(value: f32, int_value: Option<i32>, has_sign: bool) -> Vec<json::Json> {
993+
fn one_component_value_to_json(token: Token, input: &mut Parser) -> Value {
994+
fn numeric(value: f32, int_value: Option<i32>, has_sign: bool) -> Vec<Value> {
968995
vec![
969996
Token::Number {
970997
value: value,
@@ -985,7 +1012,7 @@ fn one_component_value_to_json(token: Token, input: &mut Parser) -> Json {
9851012
]
9861013
}
9871014

988-
fn nested(input: &mut Parser) -> Vec<Json> {
1015+
fn nested(input: &mut Parser) -> Vec<Value> {
9891016
let result: Result<_, ParseError<()>> =
9901017
input.parse_nested_block(|input| Ok(component_values_to_json(input)));
9911018
result.unwrap()
@@ -1005,7 +1032,7 @@ fn one_component_value_to_json(token: Token, input: &mut Parser) -> Json {
10051032
value,
10061033
int_value,
10071034
has_sign,
1008-
} => Json::Array({
1035+
} => Value::Array({
10091036
let mut v = vec!["number".to_json()];
10101037
v.extend(numeric(value, int_value, has_sign));
10111038
v
@@ -1014,7 +1041,7 @@ fn one_component_value_to_json(token: Token, input: &mut Parser) -> Json {
10141041
unit_value,
10151042
int_value,
10161043
has_sign,
1017-
} => Json::Array({
1044+
} => Value::Array({
10181045
let mut v = vec!["percentage".to_json()];
10191046
v.extend(numeric(unit_value * 100., int_value, has_sign));
10201047
v
@@ -1024,7 +1051,7 @@ fn one_component_value_to_json(token: Token, input: &mut Parser) -> Json {
10241051
int_value,
10251052
has_sign,
10261053
unit,
1027-
} => Json::Array({
1054+
} => Value::Array({
10281055
let mut v = vec!["dimension".to_json()];
10291056
v.extend(numeric(value, int_value, has_sign));
10301057
v.push(unit.to_json());
@@ -1044,22 +1071,22 @@ fn one_component_value_to_json(token: Token, input: &mut Parser) -> Json {
10441071
Token::CDO => "<!--".to_json(),
10451072
Token::CDC => "-->".to_json(),
10461073

1047-
Token::Function(name) => Json::Array({
1074+
Token::Function(name) => Value::Array({
10481075
let mut v = vec!["function".to_json(), name.to_json()];
10491076
v.extend(nested(input));
10501077
v
10511078
}),
1052-
Token::ParenthesisBlock => Json::Array({
1079+
Token::ParenthesisBlock => Value::Array({
10531080
let mut v = vec!["()".to_json()];
10541081
v.extend(nested(input));
10551082
v
10561083
}),
1057-
Token::SquareBracketBlock => Json::Array({
1084+
Token::SquareBracketBlock => Value::Array({
10581085
let mut v = vec!["[]".to_json()];
10591086
v.extend(nested(input));
10601087
v
10611088
}),
1062-
Token::CurlyBracketBlock => Json::Array({
1089+
Token::CurlyBracketBlock => Value::Array({
10631090
let mut v = vec!["{}".to_json()];
10641091
v.extend(nested(input));
10651092
v

0 commit comments

Comments
 (0)
Please sign in to comment.