Skip to content

Commit

Permalink
Avoid allocation in JsonEmitter::emit_footer
Browse files Browse the repository at this point in the history
Write directly to the output instead of creating an intermediate `String`.
  • Loading branch information
Rawk authored and ytmimi committed Sep 20, 2024
1 parent b23b699 commit 0339b96
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/emitter/json.rs
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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(
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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());
}
}

0 comments on commit 0339b96

Please sign in to comment.