Skip to content

Commit

Permalink
feat(serde): derive Serial./Deserial. on serde feat
Browse files Browse the repository at this point in the history
Change bindings to include serde serialize/Deserialize for ClipperPoint64
behind conditional feature compilation.
  • Loading branch information
tirithen committed Jun 1, 2024
1 parent 5fa8ab0 commit e15f63c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 25 deletions.
35 changes: 10 additions & 25 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ fn main() {

#[cfg(feature = "generate-bindings")]
{
let mut builder = bindgen::Builder::default()
let builder = bindgen::Builder::default()
.header("clipper2c/include/clipper2c.h")
.header("clipper2c/include/types.h")
.allowlist_type("ClipperClipperD")
Expand Down Expand Up @@ -190,41 +190,26 @@ fn main() {
.allowlist_function("clipper_delete_clipperoffset")
.size_t_is_usize(true);

#[cfg(feature = "serde")]
{
builder = builder.parse_callbacks(Box::new(serde_callbacks::BindgenCallbacks));
}

let bindings = builder.generate().expect("unable to generate bindings");

let out_path = if cfg!(feature = "update-bindings") {
std::path::PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()).join("generated")
} else {
std::path::PathBuf::from(env::var("OUT_DIR").unwrap())
};
let out_bindings = out_path.join("bindings.rs");

bindings
.write_to_file(out_path.join("bindings.rs"))
.write_to_file(&out_bindings)
.expect("couldn't write bindings!");
}
}

#[cfg(all(feature = "generate-bindings", feature = "serde"))]
mod serde_callbacks {
#[derive(Debug)]
pub(crate) struct BindgenCallbacks;
let content = std::fs::read_to_string(&out_bindings).expect("couldn't read bindings file");
let processed_content = content.replace(
"pub struct ClipperPoint64 {",
"#[cfg_attr(\n\tfeature = \"serde\",\n\tderive(serde::Serialize, serde::Deserialize)\n)]\npub struct ClipperPoint64 {",
);

impl bindgen::callbacks::ParseCallbacks for BindgenCallbacks {
fn add_derives(&self, info: &bindgen::callbacks::DeriveInfo<'_>) -> Vec<String> {
let names = vec!["ClipperPoint64"];
if names.contains(&info.name) {
vec!["Serialize", "Deserialize"]
.drain(..)
.map(|s| s.to_string())
.collect()
} else {
vec![]
}
}
std::fs::write(&out_bindings, processed_content)
.expect("couldn't write processed bindings file");
}
}
4 changes: 4 additions & 0 deletions generated/bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@ fn bindgen_test_layout_ClipperPointD() {
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize)
)]
pub struct ClipperPoint64 {
pub x: i64,
pub y: i64,
Expand Down

0 comments on commit e15f63c

Please sign in to comment.