diff --git a/bindgen-tests/tests/expectations/tests/issue-2566-cstr.rs b/bindgen-tests/tests/expectations/tests/issue-2566-cstr.rs new file mode 100644 index 0000000000..4227cf2956 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/issue-2566-cstr.rs @@ -0,0 +1,2 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +pub const FOO: &[u8; 4] = b"a\0b\0"; diff --git a/bindgen-tests/tests/expectations/tests/issue-2566.rs b/bindgen-tests/tests/expectations/tests/issue-2566.rs new file mode 100644 index 0000000000..4227cf2956 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/issue-2566.rs @@ -0,0 +1,2 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +pub const FOO: &[u8; 4] = b"a\0b\0"; diff --git a/bindgen-tests/tests/headers/issue-2566-cstr.h b/bindgen-tests/tests/headers/issue-2566-cstr.h new file mode 100644 index 0000000000..674b894024 --- /dev/null +++ b/bindgen-tests/tests/headers/issue-2566-cstr.h @@ -0,0 +1,4 @@ +// bindgen-flags: --generate-cstr + +/// We should _not_ generate a cstr for this because cstr shouldn't have interior nulls. +#define FOO "a\0b" diff --git a/bindgen-tests/tests/headers/issue-2566.h b/bindgen-tests/tests/headers/issue-2566.h new file mode 100644 index 0000000000..6e15ec1979 --- /dev/null +++ b/bindgen-tests/tests/headers/issue-2566.h @@ -0,0 +1 @@ +#define FOO "a\0b" diff --git a/bindgen/codegen/mod.rs b/bindgen/codegen/mod.rs index 11425e02a4..3d99fa02c8 100644 --- a/bindgen/codegen/mod.rs +++ b/bindgen/codegen/mod.rs @@ -714,18 +714,18 @@ impl CodeGenerator for Var { let len = proc_macro2::Literal::usize_unsuffixed( cstr_bytes.len(), ); - let cstr = CStr::from_bytes_with_nul(&cstr_bytes).unwrap(); // TODO: Here we ignore the type we just made up, probably // we should refactor how the variable type and ty ID work. let array_ty = quote! { [u8; #len] }; let cstr_ty = quote! { ::#prefix::ffi::CStr }; - let bytes = proc_macro2::Literal::byte_string( - cstr.to_bytes_with_nul(), - ); + let bytes = proc_macro2::Literal::byte_string(&cstr_bytes); - if rust_features.const_cstr && options.generate_cstr { + if options.generate_cstr && + rust_features.const_cstr && + CStr::from_bytes_with_nul(&cstr_bytes).is_ok() + { result.push(quote! { #(#attrs)* #[allow(unsafe_code)]