Skip to content

Commit 31214a7

Browse files
committed
Print special floats (e.g. NaN, Infinity) like JavaScript.
1 parent 474eb20 commit 31214a7

File tree

3 files changed

+10
-12
lines changed

3 files changed

+10
-12
lines changed

jaq-json/src/json.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ pub(crate) fn write_with(w: &mut dyn io::Write, v: &Val, f: WriteFn<Val>) -> io:
103103
/// Note that unlike jq, this may actually produce invalid JSON.
104104
/// In particular, this may yield:
105105
///
106-
/// - literals for special floating-point values (nan, inf, -inf)
106+
/// - literals for special floating-point values (NaN, Infinity, -Infinity)
107107
/// - invalid UTF-8 characters
108108
/// - byte strings with `\xXX` sequences
109109
/// - objects with non-string keys

jaq-json/src/num.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -329,8 +329,10 @@ impl fmt::Display for Num {
329329
match self {
330330
Self::Int(i) => write!(f, "{i}"),
331331
Self::BigInt(i) => write!(f, "{i}"),
332-
Self::Float(x) if x.is_finite() => ryu::Buffer::new().format_finite(*x).fmt(f),
333-
Self::Float(_) => write!(f, "null"),
332+
Self::Float(x) if x.is_nan() => write!(f, "NaN"),
333+
Self::Float(f64::INFINITY) => write!(f, "Infinity"),
334+
Self::Float(f64::NEG_INFINITY) => write!(f, "-Infinity"),
335+
Self::Float(x) => ryu::Buffer::new().format_finite(*x).fmt(f),
334336
Self::Dec(n) => write!(f, "{n}"),
335337
}
336338
}

jaq-json/tests/funs.rs

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -108,15 +108,11 @@ yields!(length_int_neg, "-2 | length", 2);
108108
yields!(length_float_pos, " 2.5 | length", 2.5);
109109
yields!(length_float_neg, "-2.5 | length", 2.5);
110110

111-
#[test]
112-
fn tojson() {
113-
// TODO: correct this
114-
give(json!(1.0), "tojson", json!("1.0"));
115-
give(json!(0), "1.0 | tojson", json!("1.0"));
116-
give(json!(0), "1.1 | tojson", json!("1.1"));
117-
give(json!(0), "0.0 / 0.0 | tojson", json!("null"));
118-
give(json!(0), "1.0 / 0.0 | tojson", json!("null"));
119-
}
111+
yields!(tojson_fl0, "1.0 | tojson", "1.0");
112+
yields!(tojson_fl1, "1.1 | tojson", "1.1");
113+
yields!(tojson_nan, "0.0 / 0.0 | tojson", "NaN");
114+
yields!(tojson_inf, "1.0 / 0.0 | tojson", "Infinity");
115+
yields!(tojson_ninf, "-1.0 / 0.0 | tojson", "-Infinity");
120116

121117
#[test]
122118
fn tonumber() {

0 commit comments

Comments
 (0)