Better cxx binding codegen

This commit is contained in:
topjohnwu 2023-05-19 15:59:40 -07:00
parent 2e77a426b2
commit 655f778171

View File

@ -3,7 +3,8 @@
use std::fmt::Display; use std::fmt::Display;
use std::fs::File; use std::fs::File;
use std::io::Write; use std::io::Write;
use std::process; use std::path::Path;
use std::{fs, io, process};
use cxx_gen::Opt; use cxx_gen::Opt;
@ -23,16 +24,22 @@ impl<T, E: Display> ResultExt<T> for Result<T, E> {
} }
} }
fn write_if_diff<P: AsRef<Path>>(path: P, bytes: &[u8]) -> io::Result<()> {
let path = path.as_ref();
if let Ok(orig) = fs::read(path) {
// Do not modify the file if content is the same to make incremental build more optimal
if orig.as_slice() == bytes {
return Ok(());
}
}
let mut f = File::create(path)?;
f.write_all(bytes)
}
pub fn gen_cxx_binding(name: &str) { pub fn gen_cxx_binding(name: &str) {
println!("cargo:rerun-if-changed=lib.rs"); println!("cargo:rerun-if-changed=lib.rs");
let opt = Opt::default(); let opt = Opt::default();
let gen = cxx_gen::generate_header_and_cc_with_path("lib.rs", &opt); let gen = cxx_gen::generate_header_and_cc_with_path("lib.rs", &opt);
{ write_if_diff(format!("{}.cpp", name), gen.implementation.as_slice()).ok_or_exit();
let mut cpp = File::create(format!("{}.cpp", name)).unwrap(); write_if_diff(format!("{}.hpp", name), gen.header.as_slice()).ok_or_exit();
cpp.write_all(gen.implementation.as_slice()).ok_or_exit();
}
{
let mut hpp = File::create(format!("{}.hpp", name)).unwrap();
hpp.write_all(gen.header.as_slice()).ok_or_exit();
}
} }