Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an "impl_arbitrary" feature to enable implementing Arbitrary. #260

Closed
wants to merge 12 commits into from
2 changes: 2 additions & 0 deletions Cargo.toml
Expand Up @@ -29,11 +29,13 @@ walkdir = "2.3"
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
arbitrary = "1"
sunfishcode marked this conversation as resolved.
Show resolved Hide resolved

[features]
default = []
example_generated = []
rustc-dep-of-std = ["core", "compiler_builtins"]
impl_arbitrary = []

[package.metadata.docs.rs]
features = ["example_generated"]
24 changes: 24 additions & 0 deletions src/lib.rs
Expand Up @@ -820,6 +820,8 @@ macro_rules! __impl_bitflags {
result
}
}

__impl_arbitrary_for_bitflags!($BitFlags);
};

// Every attribute that the user writes on a const is applied to the
Expand Down Expand Up @@ -931,6 +933,28 @@ macro_rules! __impl_bitflags {
};
}

// When "arbitrary" is not enabled, emit code to implement the `Arbitrary` trait.
#[cfg(feature = "impl_arbitrary")]
#[macro_export(local_inner_macros)]
#[doc(hidden)]
macro_rules! __impl_arbitrary_for_bitflags {
($BitFlags:ident) => {
impl<'a> arbitrary::Arbitrary<'a> for $BitFlags {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
Self::from_bits(u.arbitrary()?).ok_or_else(|| arbitrary::Error::IncorrectFormat)
}
}
};
}

// When "arbitrary" is not enabled, don't emit any code for it.
#[cfg(not(feature = "impl_arbitrary"))]
#[macro_export(local_inner_macros)]
#[doc(hidden)]
macro_rules! __impl_arbitrary_for_bitflags {
($BitFlags:ident) => {};
}
sunfishcode marked this conversation as resolved.
Show resolved Hide resolved

#[cfg(feature = "example_generated")]
pub mod example_generated;

Expand Down
17 changes: 17 additions & 0 deletions tests/arbitrary.rs
@@ -0,0 +1,17 @@
#![cfg(feature = "impl_arbitrary")]
sunfishcode marked this conversation as resolved.
Show resolved Hide resolved

use arbitrary::Arbitrary;

bitflags::bitflags! {
struct Color: u32 {
const RED = 0x1;
const GREEN = 0x2;
const BLUE = 0x4;
}
}

#[test]
fn test_arbitary() {
let mut unstructured = arbitrary::Unstructured::new(&[0_u8; 256]);
let _color = Color::arbitrary(&mut unstructured);
}