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

Implement the optional space parameter in JSON.stringify #961

Merged
merged 10 commits into from
Dec 17, 2020
3 changes: 3 additions & 0 deletions boa/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,14 @@ bench = false
[[bench]]
name = "parser"
harness = false
required-features = ["serde"]

[[bench]]
name = "exec"
harness = false
required-features = ["serde"]

[[bench]]
name = "full"
harness = false
required-features = ["serde"]
68 changes: 63 additions & 5 deletions boa/src/builtins/json/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ use crate::{
property::{Attribute, DataDescriptor, PropertyKey},
BoaProfiler, Context, Result, Value,
};
use serde_json::{self, Value as JSONValue};
use serde::Serialize;
use serde_json::{self, ser::PrettyFormatter, Serializer, Value as JSONValue};

#[cfg(test)]
mod tests;
Expand Down Expand Up @@ -140,9 +141,42 @@ impl Json {
None => return Ok(Value::undefined()),
Some(obj) => obj,
};
const SPACE_INDENT: &str = " ";
let space = match args.get(2) {
Some(indent) if indent.is_number() => {
if let Some(indent_length) = indent.as_number() {
let indent_length = if indent_length > 10.0 {
10.0
} else {
indent_length
};
let indent_length = if indent_length < 0.0 || indent_length.is_nan() {
0.0
} else {
indent_length
};
&SPACE_INDENT[..indent_length as usize]
} else {
""
}
}
Some(space) if space.is_string() => {
if let Some(space) = space.as_string() {
&space[..std::cmp::min(space.len(), 10)]
} else {
""
}
}
_ => "",
};
let replacer = match args.get(1) {
Some(replacer) if replacer.is_object() => replacer,
_ => return Ok(Value::from(object.to_json(context)?.to_string())),
_ => {
return Ok(Value::from(json_to_pretty_string(
&object.to_json(context)?,
space,
)))
}
};

let replacer_as_object = replacer
Expand Down Expand Up @@ -172,7 +206,10 @@ impl Json {
),
);
}
Ok(Value::from(object_to_return.to_json(context)?.to_string()))
Ok(Value::from(json_to_pretty_string(
&object_to_return.to_json(context)?,
space,
)))
})
.ok_or_else(Value::undefined)?
} else if replacer_as_object.is_array() {
Expand All @@ -195,9 +232,30 @@ impl Json {
obj_to_return.insert(field.to_string(context)?.to_string(), value);
}
}
Ok(Value::from(JSONValue::Object(obj_to_return).to_string()))
Ok(Value::from(json_to_pretty_string(
&JSONValue::Object(obj_to_return),
space,
)))
} else {
Ok(Value::from(object.to_json(context)?.to_string()))
Ok(Value::from(json_to_pretty_string(
&object.to_json(context)?,
space,
)))
}
}
}

fn json_to_pretty_string(json: &JSONValue, space: &str) -> String {
if space.is_empty() {
return json.to_string();
}
let formatter = PrettyFormatter::with_indent(space.as_bytes());
let mut writer = Vec::with_capacity(128);
let mut serializer = Serializer::with_formatter(&mut writer, formatter);
json.serialize(&mut serializer)
.expect("JSON serialization failed");
unsafe {
// The serde json serializer always produce correct UTF-8
String::from_utf8_unchecked(writer)
}
}
99 changes: 99 additions & 0 deletions boa/src/builtins/json/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,105 @@ fn json_stringify_fractional_numbers() {
assert_eq!(actual, expected);
}

#[test]
fn json_stringify_pretty_print() {
let mut context = Context::new();

let actual = forward(&mut context, r#"JSON.stringify({a: "b", b: "c"}, undefined, 4)"#);
let expected = forward(
&mut context,
r#"'{
"a": "b",
"b": "c"
}'"#,
);
assert_eq!(actual, expected);
}

#[test]
fn json_stringify_pretty_print_four_spaces() {
let mut context = Context::new();

let actual = forward(
&mut context,
r#"JSON.stringify({a: "b", b: "c"}, undefined, 4.3)"#,
);
let expected = forward(
&mut context,
r#"'{
"a": "b",
"b": "c"
}'"#,
);
assert_eq!(actual, expected);
}

#[test]
fn json_stringify_pretty_print_twenty_spaces() {
let mut context = Context::new();

let actual = forward(
&mut context,
r#"JSON.stringify({a: "b", b: "c"}, ["a", "b"], 20)"#,
);
let expected = forward(
&mut context,
r#"'{
"a": "b",
"b": "c"
}'"#,
);
assert_eq!(actual, expected);
}

#[test]
fn json_stringify_pretty_print_bad_space_argument() {
let mut context = Context::new();

let actual = forward(
&mut context,
r#"JSON.stringify({a: "b", b: "c"}, ["a", "b"], [])"#,
);
let expected = forward(&mut context, r#"'{"a":"b","b":"c"}'"#);
assert_eq!(actual, expected);
}

#[test]
fn json_stringify_pretty_print_with_string() {
let mut context = Context::new();

let actual = forward(
&mut context,
r#"JSON.stringify({a: "b", b: "c"}, undefined, "abcd")"#,
);
let expected = forward(
&mut context,
r#"'{
abcd"a": "b",
abcd"b": "c"
}'"#,
);
assert_eq!(actual, expected);
}

#[test]
fn json_stringify_pretty_print_with_too_long_string() {
let mut context = Context::new();

let actual = forward(
&mut context,
r#"JSON.stringify({a: "b", b: "c"}, undefined, "abcdefghijklmn")"#,
);
let expected = forward(
&mut context,
r#"'{
abcdefghij"a": "b",
abcdefghij"b": "c"
}'"#,
);
assert_eq!(actual, expected);
}

#[test]
fn json_parse_array_with_reviver() {
let mut context = Context::new();
Expand Down