fuzz_util/
zerocopy.rs

1// Copyright 2022 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Provides [`ArbitraryFromBytes`] to support generation of arbitrary instances
6//! of [`zerocopy`]-friendly types.
7
8use arbitrary::{Result, Unstructured};
9use zerocopy::FromBytes;
10
11/// Extension trait that allows construction of arbitrary values via
12/// [`zerocopy::FromBytes`].
13///
14/// [`ArbitraryFromBytes`] has a blanket implementation for all types that
15/// implement `zerocopy::FromBytes`.
16pub trait ArbitraryFromBytes<'a>: FromBytes + Sized {
17    /// Constructs an arbitrary instance of `Self` from the provided
18    /// unstructured data.
19    fn arbitrary_from_bytes(u: &mut Unstructured<'a>) -> Result<Self>;
20}
21
22impl<'a, A> ArbitraryFromBytes<'a> for A
23where
24    A: FromBytes + 'a,
25{
26    fn arbitrary_from_bytes(u: &mut Unstructured<'a>) -> Result<Self> {
27        let mut bytes = vec![0u8; std::mem::size_of::<A>()];
28        u.fill_buffer(&mut bytes)?;
29        Ok(Self::read_from_bytes(&*bytes).unwrap())
30    }
31}