Skip to content

Commit

Permalink
Implement Arbitrary for &[u8].
Browse files Browse the repository at this point in the history
  • Loading branch information
frewsxcv committed Jan 25, 2021
1 parent bf391d3 commit 3470d56
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
4 changes: 3 additions & 1 deletion CHANGELOG.md
Expand Up @@ -32,7 +32,7 @@ Released YYYY-MM-DD.

### Added

*
* The `Arbitrary` trait is now implemented for `&[u8]`. [#67](https://github.com/rust-fuzz/arbitrary/pull/67)

### Changed

Expand All @@ -42,6 +42,8 @@ Released YYYY-MM-DD.

*

--------------------------------------------------------------------------------

## 1.0.0-rc1

Released 2020-11-25.
Expand Down
34 changes: 34 additions & 0 deletions src/lib.rs
Expand Up @@ -626,6 +626,22 @@ arbitrary_array! { 32, (T, a) (T, b) (T, c) (T, d) (T, e) (T, f) (T, g) (T, h)
(T, z) (T, aa) (T, ab) (T, ac) (T, ad) (T, ae) (T, af)
(T, ag) }

impl<'a> Arbitrary<'a> for &'a [u8] {
fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
let len = u.arbitrary_len::<u8>()?;
u.bytes(len)
}

fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
Ok(u.take_rest())
}

#[inline]
fn size_hint(depth: usize) -> (usize, Option<usize>) {
<usize as Arbitrary>::size_hint(depth)
}
}

impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for Vec<A> {
fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
u.arbitrary_iter()?.collect()
Expand Down Expand Up @@ -1020,6 +1036,24 @@ mod test {
assert_eq!(expected, actual);
}

#[test]
fn arbitrary_for_bytes() {
let x = [1, 2, 3, 4, 4];
let mut buf = Unstructured::new(&x);
let expected = &[1, 2, 3, 4];
let actual = <&[u8] as Arbitrary>::arbitrary(&mut buf).unwrap();
assert_eq!(expected, actual);
}

#[test]
fn arbitrary_take_rest_for_bytes() {
let x = [1, 2, 3, 4];
let buf = Unstructured::new(&x);
let expected = &[1, 2, 3, 4];
let actual = <&[u8] as Arbitrary>::arbitrary_take_rest(buf).unwrap();
assert_eq!(expected, actual);
}

#[test]
fn arbitrary_collection() {
let x = [
Expand Down

0 comments on commit 3470d56

Please sign in to comment.