From 7f264e3ffb1b626932bd42da521755acf6e89982 Mon Sep 17 00:00:00 2001 From: Federico Maria Morrone Date: Wed, 19 Jun 2024 20:19:16 +0200 Subject: [PATCH] Add optional "arbitrary" crate integration --- Cargo.toml | 1 + src/arbitrary.rs | 18 ++++++++++++++++++ src/lib.rs | 3 +++ 3 files changed, 22 insertions(+) create mode 100644 src/arbitrary.rs diff --git a/Cargo.toml b/Cargo.toml index 793582af1..401e331bc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,7 @@ default = ["std"] std = [] [dependencies] +arbitrary = { version = "1.1.6", optional = true } serde = { version = "1.0.60", optional = true, default-features = false, features = ["alloc"] } [dev-dependencies] diff --git a/src/arbitrary.rs b/src/arbitrary.rs new file mode 100644 index 000000000..7d992f046 --- /dev/null +++ b/src/arbitrary.rs @@ -0,0 +1,18 @@ +use super::{Bytes, BytesMut}; +use arbitrary::{Arbitrary, Result}; + +impl<'a> Arbitrary<'a> for Bytes { + fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> Result { + let len = u.arbitrary_len::()?; + + u.bytes(len).map(Bytes::copy_from_slice) + } +} + +impl<'a> Arbitrary<'a> for BytesMut { + fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> Result { + let len = u.arbitrary_len::()?; + + u.bytes(len).map(|slice| BytesMut::from_vec(slice.to_vec())) + } +} diff --git a/src/lib.rs b/src/lib.rs index 7ddd2205b..b854a104b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -91,6 +91,9 @@ pub use crate::bytes_mut::BytesMut; #[cfg(feature = "serde")] mod serde; +#[cfg(feature = "arbitrary")] +mod arbitrary; + #[inline(never)] #[cold] fn abort() -> ! {