Skip to content

Commit

Permalink
Add an "impl_arbitrary" feature to enable implementing Arbitrary.
Browse files Browse the repository at this point in the history
  • Loading branch information
sunfishcode committed Aug 18, 2021
1 parent a13bb56 commit bb7b21e
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
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"

[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) => {}
}

#[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")]

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);
}

0 comments on commit bb7b21e

Please sign in to comment.