From ed944f725a71445dca99091c969b6ef6ed5ff0c1 Mon Sep 17 00:00:00 2001 From: Zhiming Wang Date: Tue, 2 Jun 2020 17:58:16 +0800 Subject: [PATCH] Constify AV_CODEC_ID_FIRST_* in enums There are dummy IDs AV_CODEC_ID_FIRST_AUDIO, AV_CODEC_ID_FIRST_SUBTITLE, and AV_CODEC_ID_FIRST_UNKNOWN that are duplicates of their following entries in the AVCodecID enum in libavcodec/avcodec.h. In C this is not a problem, but when bindgen converts the C enum to Rust enum it has to drop one in each pair of duplicates, and since the dummy IDs are listed first, they push the meaningful ones AV_CODEC_ID_FIRST_AUDIO, AV_CODEC_ID_DVD_SUBTITLE, and AV_CODEC_ID_TTF to associated constants. We introduce enum_variant_behavior callback to fix this. --- sys/build.rs | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/sys/build.rs b/sys/build.rs index 5cddc04..00d6aaa 100644 --- a/sys/build.rs +++ b/sys/build.rs @@ -12,7 +12,7 @@ use std::process::Command; use std::str; use regex::Regex; -use bindgen::callbacks::{IntKind, ParseCallbacks, MacroParsingBehavior}; +use bindgen::callbacks::{EnumVariantCustomBehavior, EnumVariantValue, IntKind, ParseCallbacks, MacroParsingBehavior}; #[derive(Debug)] struct Library { @@ -43,9 +43,9 @@ static LIBRARIES: &[Library] = &[ ]; #[derive(Debug)] -struct IntCallbacks; +struct Callbacks; -impl ParseCallbacks for IntCallbacks { +impl ParseCallbacks for Callbacks { fn int_macro(&self, _name: &str, value: i64) -> Option { let ch_layout = Regex::new(r"^AV_CH").unwrap(); let codec_cap = Regex::new(r"^AV_CODEC_CAP").unwrap(); @@ -72,6 +72,20 @@ impl ParseCallbacks for IntCallbacks { } } + fn enum_variant_behavior( + &self, + _enum_name: Option<&str>, + original_variant_name: &str, + _variant_value: EnumVariantValue, + ) -> Option { + let dummy_codec_id = Regex::new(r"^AV_CODEC_ID_FIRST").unwrap(); + if dummy_codec_id.is_match(original_variant_name) { + Some(EnumVariantCustomBehavior::Constify) + } else { + None + } + } + // https://github.com/rust-lang/rust-bindgen/issues/687#issuecomment-388277405 fn will_parse_macro(&self, name: &str) -> MacroParsingBehavior { use MacroParsingBehavior::*; @@ -1035,7 +1049,7 @@ fn main() { .prepend_enum_name(false) .derive_eq(true) .size_t_is_usize(true) - .parse_callbacks(Box::new(IntCallbacks)); + .parse_callbacks(Box::new(Callbacks)); // The input headers we would like to generate // bindings for.