From 0339b963414ee7468614f6519183f08d390f03dd Mon Sep 17 00:00:00 2001 From: Mattias Wallin Date: Thu, 19 Sep 2024 18:31:07 +0200 Subject: [PATCH] Avoid allocation in `JsonEmitter::emit_footer` Write directly to the output instead of creating an intermediate `String`. --- src/emitter/json.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/emitter/json.rs b/src/emitter/json.rs index a99626f783d..39eae1ab0f2 100644 --- a/src/emitter/json.rs +++ b/src/emitter/json.rs @@ -1,7 +1,7 @@ use super::*; use crate::rustfmt_diff::{DiffLine, Mismatch, make_diff}; use serde::Serialize; -use serde_json::to_string as to_json_string; +use serde_json::to_writer as to_json_writer; #[derive(Debug, Default)] pub(crate) struct JsonEmitter { @@ -26,7 +26,8 @@ struct MismatchedFile { impl Emitter for JsonEmitter { fn emit_footer(&self, output: &mut dyn Write) -> Result<(), io::Error> { - writeln!(output, "{}", &to_json_string(&self.mismatched_files)?) + to_json_writer(&mut *output, &self.mismatched_files)?; + writeln!(output) } fn emit_formatted_file( @@ -252,7 +253,7 @@ mod tests { ) .unwrap(); let _ = emitter.emit_footer(&mut writer); - let exp_json = to_json_string(&vec![MismatchedFile { + let exp_json = serde_json::to_string(&vec![MismatchedFile { name: String::from(file_name), mismatches: vec![ MismatchedBlock { @@ -338,7 +339,7 @@ mod tests { }], }; - let exp_json = to_json_string(&vec![exp_bin, exp_lib]).unwrap(); + let exp_json = serde_json::to_string(&vec![exp_bin, exp_lib]).unwrap(); assert_eq!(&writer[..], format!("{exp_json}\n").as_bytes()); } }