diff --git a/sys/Cargo.toml b/sys/Cargo.toml index fd961be..b4aa15c 100644 --- a/sys/Cargo.toml +++ b/sys/Cargo.toml @@ -19,11 +19,17 @@ doctest = false [dependencies] libc = "0.2.88" +[dependencies.serde] +version = "1.0.0" +optional = true +features = ["derive"] + [build-dependencies] num_cpus = "1.13.0" cc = "1.0.67" pkg-config = "0.3.19" bindgen = "0.58.1" +regex = "1" [target.'cfg(target_env = "msvc")'.build-dependencies] vcpkg = "0.2.11" diff --git a/sys/build.rs b/sys/build.rs index 6c7fbeb..7e9fe81 100644 --- a/sys/build.rs +++ b/sys/build.rs @@ -1,4 +1,3 @@ - use std::env; use std::fs::{self, File}; use std::io::{self, BufRead, BufReader, Write}; @@ -9,6 +8,7 @@ use std::str; use bindgen::callbacks::{ EnumVariantCustomBehavior, EnumVariantValue, IntKind, MacroParsingBehavior, ParseCallbacks, }; +use regex::Regex; #[derive(Debug)] struct Library { @@ -1273,14 +1273,28 @@ fn thread_main() { } // Finish the builder and generate the bindings. - let bindings = builder + let mut bindings = builder .generate() // Unwrap the Result and panic on failure. - .expect("Unable to generate bindings"); + .expect("Unable to generate bindings") + .to_string(); + + if env::var("CARGO_FEATURE_SERDE").is_ok() { + bindings = Regex::new( + r"#\s*\[\s*derive\s*\((?P[^)]+)\)\s*\]\s*pub\s*(?Penum)" + ) + .unwrap() + .replace_all(&bindings, r#" + #[derive($d)] + #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] + #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))] + pub $s + "#) + .into(); + } // Write the bindings to the $OUT_DIR/bindings.rs file. - bindings - .write_to_file(output().join("bindings.rs")) + fs::write(output().join("bindings.rs"), &bindings) .expect("Couldn't write bindings!"); }