Skip to content

Commit

Permalink
perf: improve code generation performance
Browse files Browse the repository at this point in the history
Use `BufWriter` and avoid formatting generated code for faster build
times
  • Loading branch information
GabrielDertoni authored and patrickelectric committed Mar 21, 2023
1 parent 2f23925 commit 240551b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ heapless = "0.7"
"common",
]

"format-generated-code" = []
"emit-description" = []
"emit-extensions" = []
"std" = ["byteorder/std"]
Expand All @@ -81,4 +82,4 @@ default= ["std", "tcp", "udp", "direct-serial", "serial", "serde", "ardupilotmeg
# build with all features on docs.rs so that users viewing documentation
# can see everything
[package.metadata.docs.rs]
features = ["default", "all-dialects", "emit-description", "emit-extensions"]
features = ["default", "all-dialects", "emit-description", "emit-extensions", "format-generated-code"]
14 changes: 10 additions & 4 deletions build/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use crate::util::to_module_name;
use std::env;
use std::ffi::OsStr;
use std::fs::{read_dir, File};
use std::io::BufWriter;
use std::path::{Path, PathBuf};
use std::process::Command;

Expand Down Expand Up @@ -63,15 +64,15 @@ pub fn main() {
modules.push(module_name);

let dest_path = Path::new(&out_dir).join(definition_rs);
let mut outf = File::create(&dest_path).unwrap();
let mut outf = BufWriter::new(File::create(&dest_path).unwrap());

// generate code
parser::generate(
&definitions_dir,
&definition_file.into_string().unwrap(),
&mut outf,
);
format_code(&out_dir, &dest_path);
dbg_format_code(&out_dir, &dest_path);

// Re-run build if definition file changes
println!("cargo:rerun-if-changed={}", entry.path().to_string_lossy());
Expand All @@ -84,12 +85,17 @@ pub fn main() {

// generate code
binder::generate(modules, &mut outf);
format_code(out_dir, dest_path);
dbg_format_code(out_dir, dest_path);
}
}

fn format_code(cwd: impl AsRef<Path>, path: impl AsRef<OsStr>) {
#[cfg(feature = "format-generated-code")]
fn dbg_format_code(cwd: impl AsRef<Path>, path: impl AsRef<OsStr>) {
if let Err(error) = Command::new("rustfmt").arg(path).current_dir(cwd).status() {
eprintln!("{error}");
}
}

// Does nothing
#[cfg(not(feature = "format-generated-code"))]
fn dbg_format_code(_: impl AsRef<Path>, _: impl AsRef<OsStr>) {}

0 comments on commit 240551b

Please sign in to comment.