Skip to content

Commit a7d6247

Browse files
authored
chore: speed up JSON float rendering (#806)
Avoid allocating new String for each float number rendering, and de-dup the code a bit.
1 parent 16363f4 commit a7d6247

File tree

1 file changed

+15
-22
lines changed

1 file changed

+15
-22
lines changed

insta/src/content/json.rs

Lines changed: 15 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,6 @@ use crate::content::Content;
66
/// when [`to_string_pretty`] is used.
77
const COMPACT_MAX_CHARS: usize = 120;
88

9-
pub fn format_float<T: Display>(value: T) -> String {
10-
let mut rv = format!("{value}");
11-
if !rv.contains('.') {
12-
rv.push_str(".0");
13-
}
14-
rv
15-
}
16-
179
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
1810
pub enum Format {
1911
Condensed,
@@ -126,20 +118,8 @@ impl Serializer {
126118
Content::I32(n) => write!(self.out, "{n}").unwrap(),
127119
Content::I64(n) => write!(self.out, "{n}").unwrap(),
128120
Content::I128(n) => write!(self.out, "{n}").unwrap(),
129-
Content::F32(f) => {
130-
if f.is_finite() {
131-
self.write_str(&format_float(f));
132-
} else {
133-
self.write_str("null")
134-
}
135-
}
136-
Content::F64(f) => {
137-
if f.is_finite() {
138-
self.write_str(&format_float(f));
139-
} else {
140-
self.write_str("null")
141-
}
142-
}
121+
Content::F32(f) => self.write_float(f, f.is_finite()),
122+
Content::F64(f) => self.write_float(f, f.is_finite()),
143123
Content::Char(c) => self.write_escaped_str(&(*c).to_string()),
144124
Content::String(s) => self.write_escaped_str(s),
145125
Content::Bytes(bytes) => {
@@ -206,6 +186,19 @@ impl Serializer {
206186
}
207187
}
208188

189+
fn write_float(&mut self, n: impl Display, is_finite: bool) {
190+
if is_finite {
191+
let start = self.out.len();
192+
write!(self.out, "{n}").unwrap();
193+
// ensure the result has .0 for whole numbers to be round-trip safe
194+
if !self.out[start..].contains('.') {
195+
self.out.push_str(".0");
196+
}
197+
} else {
198+
self.write_str("null");
199+
}
200+
}
201+
209202
fn write_str(&mut self, s: &str) {
210203
self.out.push_str(s);
211204
}

0 commit comments

Comments
 (0)