Skip to content

Commit

Permalink
Remove leading 0s before parsing into serde_json::Number.
Browse files Browse the repository at this point in the history
We previously decided to allow leading 0s, per this discussion:
#5762 (comment)

However, since we use the parsing logic of `serde_json::Number` to
produce the internal representation, and that logic fails given leading
zeros, we need to normalize the input `&str` a bit before calling
`number.parse()`. We already perform some similar normalizations, e.g.
ensuring the fractional part is at least a 0 (not empty after the `.`),
so there's precedent.
  • Loading branch information
benjamn committed Feb 11, 2025
1 parent b76bf11 commit 0535bfe
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion apollo-federation/src/sources/connect/json_selection/lit_expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,14 @@ impl LitExpr {
);

let mut s = String::new();
s.push_str(int.fragment());
let int_str = int.fragment();
// Remove leading zeros to avoid failing the stricter
// number.parse() below, but allow a single zero.
if let Some(first_non_zero) = int_str.chars().position(|c| c != '0') {
s.push_str(&int_str[first_non_zero..]);
} else {
s.push('0');
}

let full_range = if let Some((_, dot, _, frac)) = frac {
let frac_range = merge_ranges(
Expand Down Expand Up @@ -277,6 +284,7 @@ mod tests {
use crate::sources::connect::json_selection::location::new_span;
use crate::sources::connect::json_selection::PathList;

#[track_caller]
fn check_parse(input: &str, expected: LitExpr) {
match LitExpr::parse(new_span(input)) {
Ok((remainder, parsed)) => {
Expand Down Expand Up @@ -317,6 +325,24 @@ mod tests {
"-123.",
LitExpr::Number(serde_json::Number::from_f64(-123.0).unwrap()),
);
check_parse("00", LitExpr::Number(serde_json::Number::from(0)));
check_parse(
"-00",
LitExpr::Number(serde_json::Number::from_f64(-0.0).unwrap()),
);
check_parse("0", LitExpr::Number(serde_json::Number::from(0)));
check_parse(
"-0",
LitExpr::Number(serde_json::Number::from_f64(-0.0).unwrap()),
);
check_parse(" 00 ", LitExpr::Number(serde_json::Number::from(0)));
check_parse(" 0 ", LitExpr::Number(serde_json::Number::from(0)));
check_parse(
" - 0 ",
LitExpr::Number(serde_json::Number::from_f64(-0.0).unwrap()),
);
check_parse("001", LitExpr::Number(serde_json::Number::from(1)));
check_parse("0010", LitExpr::Number(serde_json::Number::from(10)));

check_parse("true", LitExpr::Bool(true));
check_parse(" true ", LitExpr::Bool(true));
Expand Down

0 comments on commit 0535bfe

Please sign in to comment.