1 // Copyright © 2019 The Rust Fuzz Project Developers.
2 //
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
8 
9 //! The `Arbitrary` trait crate.
10 //!
11 //! This trait provides an [`Arbitrary`](./trait.Arbitrary.html) trait to
12 //! produce well-typed, structured values, from raw, byte buffers. It is
13 //! generally intended to be used with fuzzers like AFL or libFuzzer. See the
14 //! [`Arbitrary`](./trait.Arbitrary.html) trait's documentation for details on
15 //! automatically deriving, implementing, and/or using the trait.
16 
17 #![deny(bad_style)]
18 #![deny(missing_docs)]
19 #![deny(future_incompatible)]
20 #![deny(nonstandard_style)]
21 #![deny(rust_2018_compatibility)]
22 #![deny(rust_2018_idioms)]
23 #![deny(unused)]
24 
25 #[cfg(feature = "derive_arbitrary")]
26 pub use derive_arbitrary::*;
27 
28 mod error;
29 pub use error::*;
30 
31 pub mod unstructured;
32 #[doc(inline)]
33 pub use unstructured::Unstructured;
34 
35 pub mod size_hint;
36 
37 use core::array;
38 use core::cell::{Cell, RefCell, UnsafeCell};
39 use core::iter;
40 use core::mem;
41 use core::num::{NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize};
42 use core::num::{NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize};
43 use core::ops::{Range, RangeBounds, RangeFrom, RangeInclusive, RangeTo, RangeToInclusive};
44 use core::str;
45 use core::time::Duration;
46 use std::borrow::{Cow, ToOwned};
47 use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque};
48 use std::ffi::{CString, OsString};
49 use std::hash::BuildHasher;
50 use std::net::{Ipv4Addr, Ipv6Addr};
51 use std::ops::Bound;
52 use std::path::PathBuf;
53 use std::rc::Rc;
54 use std::sync::atomic::{AtomicBool, AtomicIsize, AtomicUsize};
55 use std::sync::{Arc, Mutex};
56 
57 /// Generate arbitrary structured values from raw, unstructured data.
58 ///
59 /// The `Arbitrary` trait allows you to generate valid structured values, like
60 /// `HashMap`s, or ASTs, or `MyTomlConfig`, or any other data structure from
61 /// raw, unstructured bytes provided by a fuzzer.
62 ///
63 /// # Deriving `Arbitrary`
64 ///
65 /// Automatically deriving the `Arbitrary` trait is the recommended way to
66 /// implement `Arbitrary` for your types.
67 ///
68 /// Using the custom derive requires that you enable the `"derive"` cargo
69 /// feature in your `Cargo.toml`:
70 ///
71 /// ```toml
72 /// [dependencies]
73 /// arbitrary = { version = "1", features = ["derive"] }
74 /// ```
75 ///
76 /// Then, you add the `#[derive(Arbitrary)]` annotation to your `struct` or
77 /// `enum` type definition:
78 ///
79 /// ```
80 /// # #[cfg(feature = "derive")] mod foo {
81 /// use arbitrary::Arbitrary;
82 /// use std::collections::HashSet;
83 ///
84 /// #[derive(Arbitrary)]
85 /// pub struct AddressBook {
86 ///     friends: HashSet<Friend>,
87 /// }
88 ///
89 /// #[derive(Arbitrary, Hash, Eq, PartialEq)]
90 /// pub enum Friend {
91 ///     Buddy { name: String },
92 ///     Pal { age: usize },
93 /// }
94 /// # }
95 /// ```
96 ///
97 /// Every member of the `struct` or `enum` must also implement `Arbitrary`.
98 ///
99 /// # Implementing `Arbitrary` By Hand
100 ///
101 /// Implementing `Arbitrary` mostly involves nested calls to other `Arbitrary`
102 /// arbitrary implementations for each of your `struct` or `enum`'s members. But
103 /// sometimes you need some amount of raw data, or you need to generate a
104 /// variably-sized collection type, or something of that sort. The
105 /// [`Unstructured`][crate::Unstructured] type helps you with these tasks.
106 ///
107 /// ```
108 /// # #[cfg(feature = "derive")] mod foo {
109 /// # pub struct MyCollection<T> { _t: std::marker::PhantomData<T> }
110 /// # impl<T> MyCollection<T> {
111 /// #     pub fn new() -> Self { MyCollection { _t: std::marker::PhantomData } }
112 /// #     pub fn insert(&mut self, element: T) {}
113 /// # }
114 /// use arbitrary::{Arbitrary, Result, Unstructured};
115 ///
116 /// impl<'a, T> Arbitrary<'a> for MyCollection<T>
117 /// where
118 ///     T: Arbitrary<'a>,
119 /// {
120 ///     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
121 ///         // Get an iterator of arbitrary `T`s.
122 ///         let iter = u.arbitrary_iter::<T>()?;
123 ///
124 ///         // And then create a collection!
125 ///         let mut my_collection = MyCollection::new();
126 ///         for elem_result in iter {
127 ///             let elem = elem_result?;
128 ///             my_collection.insert(elem);
129 ///         }
130 ///
131 ///         Ok(my_collection)
132 ///     }
133 /// }
134 /// # }
135 /// ```
136 pub trait Arbitrary<'a>: Sized {
137     /// Generate an arbitrary value of `Self` from the given unstructured data.
138     ///
139     /// Calling `Arbitrary::arbitrary` requires that you have some raw data,
140     /// perhaps given to you by a fuzzer like AFL or libFuzzer. You wrap this
141     /// raw data in an `Unstructured`, and then you can call `<MyType as
142     /// Arbitrary>::arbitrary` to construct an arbitrary instance of `MyType`
143     /// from that unstructured data.
144     ///
145     /// Implementations may return an error if there is not enough data to
146     /// construct a full instance of `Self`, or they may fill out the rest of
147     /// `Self` with dummy values. Using dummy values when the underlying data is
148     /// exhausted can help avoid accidentally "defeating" some of the fuzzer's
149     /// mutations to the underlying byte stream that might otherwise lead to
150     /// interesting runtime behavior or new code coverage if only we had just a
151     /// few more bytes. However, it also requires that implementations for
152     /// recursive types (e.g. `struct Foo(Option<Box<Foo>>)`) avoid infinite
153     /// recursion when the underlying data is exhausted.
154     ///
155     /// ```
156     /// # #[cfg(feature = "derive")] fn foo() {
157     /// use arbitrary::{Arbitrary, Unstructured};
158     ///
159     /// #[derive(Arbitrary)]
160     /// pub struct MyType {
161     ///     // ...
162     /// }
163     ///
164     /// // Get the raw data from the fuzzer or wherever else.
165     /// # let get_raw_data_from_fuzzer = || &[];
166     /// let raw_data: &[u8] = get_raw_data_from_fuzzer();
167     ///
168     /// // Wrap that raw data in an `Unstructured`.
169     /// let mut unstructured = Unstructured::new(raw_data);
170     ///
171     /// // Generate an arbitrary instance of `MyType` and do stuff with it.
172     /// if let Ok(value) = MyType::arbitrary(&mut unstructured) {
173     /// #   let do_stuff = |_| {};
174     ///     do_stuff(value);
175     /// }
176     /// # }
177     /// ```
178     ///
179     /// See also the documentation for [`Unstructured`][crate::Unstructured].
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>180     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self>;
181 
182     /// Generate an arbitrary value of `Self` from the entirety of the given
183     /// unstructured data.
184     ///
185     /// This is similar to Arbitrary::arbitrary, however it assumes that it is
186     /// the last consumer of the given data, and is thus able to consume it all
187     /// if it needs.  See also the documentation for
188     /// [`Unstructured`][crate::Unstructured].
arbitrary_take_rest(mut u: Unstructured<'a>) -> Result<Self>189     fn arbitrary_take_rest(mut u: Unstructured<'a>) -> Result<Self> {
190         Self::arbitrary(&mut u)
191     }
192 
193     /// Get a size hint for how many bytes out of an `Unstructured` this type
194     /// needs to construct itself.
195     ///
196     /// This is useful for determining how many elements we should insert when
197     /// creating an arbitrary collection.
198     ///
199     /// The return value is similar to
200     /// [`Iterator::size_hint`][iterator-size-hint]: it returns a tuple where
201     /// the first element is a lower bound on the number of bytes required, and
202     /// the second element is an optional upper bound.
203     ///
204     /// The default implementation return `(0, None)` which is correct for any
205     /// type, but not ultimately that useful. Using `#[derive(Arbitrary)]` will
206     /// create a better implementation. If you are writing an `Arbitrary`
207     /// implementation by hand, and your type can be part of a dynamically sized
208     /// collection (such as `Vec`), you are strongly encouraged to override this
209     /// default with a better implementation. The
210     /// [`size_hint`][crate::size_hint] module will help with this task.
211     ///
212     /// ## Invariant
213     ///
214     /// It must be possible to construct every possible output using only inputs
215     /// of lengths bounded by these parameters. This applies to both
216     /// [`Arbitrary::arbitrary`] and [`Arbitrary::arbitrary_take_rest`].
217     ///
218     /// This is trivially true for `(0, None)`. To restrict this further, it
219     /// must be proven that all inputs that are now excluded produced redundant
220     /// outputs which are still possible to produce using the reduced input
221     /// space.
222     ///
223     /// ## The `depth` Parameter
224     ///
225     /// If you 100% know that the type you are implementing `Arbitrary` for is
226     /// not a recursive type, or your implementation is not transitively calling
227     /// any other `size_hint` methods, you can ignore the `depth` parameter.
228     /// Note that if you are implementing `Arbitrary` for a generic type, you
229     /// cannot guarantee the lack of type recursion!
230     ///
231     /// Otherwise, you need to use
232     /// [`arbitrary::size_hint::recursion_guard(depth)`][crate::size_hint::recursion_guard]
233     /// to prevent potential infinite recursion when calculating size hints for
234     /// potentially recursive types:
235     ///
236     /// ```
237     /// use arbitrary::{Arbitrary, Unstructured, size_hint};
238     ///
239     /// // This can potentially be a recursive type if `L` or `R` contain
240     /// // something like `Box<Option<MyEither<L, R>>>`!
241     /// enum MyEither<L, R> {
242     ///     Left(L),
243     ///     Right(R),
244     /// }
245     ///
246     /// impl<'a, L, R> Arbitrary<'a> for MyEither<L, R>
247     /// where
248     ///     L: Arbitrary<'a>,
249     ///     R: Arbitrary<'a>,
250     /// {
251     ///     fn arbitrary(u: &mut Unstructured) -> arbitrary::Result<Self> {
252     ///         // ...
253     /// #       unimplemented!()
254     ///     }
255     ///
256     ///     fn size_hint(depth: usize) -> (usize, Option<usize>) {
257     ///         // Protect against potential infinite recursion with
258     ///         // `recursion_guard`.
259     ///         size_hint::recursion_guard(depth, |depth| {
260     ///             // If we aren't too deep, then `recursion_guard` calls
261     ///             // this closure, which implements the natural size hint.
262     ///             // Don't forget to use the new `depth` in all nested
263     ///             // `size_hint` calls! We recommend shadowing the
264     ///             // parameter, like what is done here, so that you can't
265     ///             // accidentally use the wrong depth.
266     ///             size_hint::or(
267     ///                 <L as Arbitrary>::size_hint(depth),
268     ///                 <R as Arbitrary>::size_hint(depth),
269     ///             )
270     ///         })
271     ///     }
272     /// }
273     /// ```
274     ///
275     /// [iterator-size-hint]: https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.size_hint
276     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)277     fn size_hint(depth: usize) -> (usize, Option<usize>) {
278         let _ = depth;
279         (0, None)
280     }
281 }
282 
283 impl<'a> Arbitrary<'a> for () {
arbitrary(_: &mut Unstructured<'a>) -> Result<Self>284     fn arbitrary(_: &mut Unstructured<'a>) -> Result<Self> {
285         Ok(())
286     }
287 
288     #[inline]
size_hint(_depth: usize) -> (usize, Option<usize>)289     fn size_hint(_depth: usize) -> (usize, Option<usize>) {
290         (0, Some(0))
291     }
292 }
293 
294 impl<'a> Arbitrary<'a> for bool {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>295     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
296         Ok(<u8 as Arbitrary<'a>>::arbitrary(u)? & 1 == 1)
297     }
298 
299     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)300     fn size_hint(depth: usize) -> (usize, Option<usize>) {
301         <u8 as Arbitrary<'a>>::size_hint(depth)
302     }
303 }
304 
305 macro_rules! impl_arbitrary_for_integers {
306     ( $( $ty:ty: $unsigned:ty; )* ) => {
307         $(
308             impl<'a> Arbitrary<'a> for $ty {
309                 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
310                     let mut buf = [0; mem::size_of::<$ty>()];
311                     u.fill_buffer(&mut buf)?;
312                     let mut x: $unsigned = 0;
313                     for i in 0..mem::size_of::<$ty>() {
314                         x |= buf[i] as $unsigned << (i * 8);
315                     }
316                     Ok(x as $ty)
317                 }
318 
319                 #[inline]
320                 fn size_hint(_depth: usize) -> (usize, Option<usize>) {
321                     let n = mem::size_of::<$ty>();
322                     (n, Some(n))
323                 }
324 
325             }
326         )*
327     }
328 }
329 
330 impl_arbitrary_for_integers! {
331     u8: u8;
332     u16: u16;
333     u32: u32;
334     u64: u64;
335     u128: u128;
336     usize: usize;
337     i8: u8;
338     i16: u16;
339     i32: u32;
340     i64: u64;
341     i128: u128;
342     isize: usize;
343 }
344 
345 macro_rules! impl_arbitrary_for_floats {
346     ( $( $ty:ident : $unsigned:ty; )* ) => {
347         $(
348             impl<'a> Arbitrary<'a> for $ty {
349                 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
350                     Ok(Self::from_bits(<$unsigned as Arbitrary<'a>>::arbitrary(u)?))
351                 }
352 
353                 #[inline]
354                 fn size_hint(depth: usize) -> (usize, Option<usize>) {
355                     <$unsigned as Arbitrary<'a>>::size_hint(depth)
356                 }
357             }
358         )*
359     }
360 }
361 
362 impl_arbitrary_for_floats! {
363     f32: u32;
364     f64: u64;
365 }
366 
367 impl<'a> Arbitrary<'a> for char {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>368     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
369         use std::char;
370         // The highest unicode code point is 0x11_FFFF
371         const CHAR_END: u32 = 0x11_0000;
372         // The size of the surrogate blocks
373         const SURROGATES_START: u32 = 0xD800;
374         let mut c = <u32 as Arbitrary<'a>>::arbitrary(u)? % CHAR_END;
375         if let Some(c) = char::from_u32(c) {
376             Ok(c)
377         } else {
378             // We found a surrogate, wrap and try again
379             c -= SURROGATES_START;
380             Ok(char::from_u32(c)
381                 .expect("Generated character should be valid! This is a bug in arbitrary-rs"))
382         }
383     }
384 
385     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)386     fn size_hint(depth: usize) -> (usize, Option<usize>) {
387         <u32 as Arbitrary<'a>>::size_hint(depth)
388     }
389 }
390 
391 impl<'a> Arbitrary<'a> for AtomicBool {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>392     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
393         Arbitrary::arbitrary(u).map(Self::new)
394     }
395 
396     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)397     fn size_hint(depth: usize) -> (usize, Option<usize>) {
398         <bool as Arbitrary<'a>>::size_hint(depth)
399     }
400 }
401 
402 impl<'a> Arbitrary<'a> for AtomicIsize {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>403     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
404         Arbitrary::arbitrary(u).map(Self::new)
405     }
406 
407     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)408     fn size_hint(depth: usize) -> (usize, Option<usize>) {
409         <isize as Arbitrary<'a>>::size_hint(depth)
410     }
411 }
412 
413 impl<'a> Arbitrary<'a> for AtomicUsize {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>414     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
415         Arbitrary::arbitrary(u).map(Self::new)
416     }
417 
418     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)419     fn size_hint(depth: usize) -> (usize, Option<usize>) {
420         <usize as Arbitrary<'a>>::size_hint(depth)
421     }
422 }
423 
424 macro_rules! impl_range {
425     (
426         $range:ty,
427         $value_closure:expr,
428         $value_ty:ty,
429         $fun:ident($fun_closure:expr),
430         $size_hint_closure:expr
431     ) => {
432         impl<'a, A> Arbitrary<'a> for $range
433         where
434             A: Arbitrary<'a> + Clone + PartialOrd,
435         {
436             fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
437                 let value: $value_ty = Arbitrary::arbitrary(u)?;
438                 Ok($fun(value, $fun_closure))
439             }
440 
441             #[inline]
442             fn size_hint(depth: usize) -> (usize, Option<usize>) {
443                 $size_hint_closure(depth)
444             }
445         }
446     };
447 }
448 
449 impl_range!(
450     Range<A>,
451     |r: &Range<A>| (r.start.clone(), r.end.clone()),
452     (A, A),
453     bounded_range(|(a, b)| a..b),
454     |depth| crate::size_hint::and(
455         <A as Arbitrary>::size_hint(depth),
456         <A as Arbitrary>::size_hint(depth)
457     )
458 );
459 impl_range!(
460     RangeFrom<A>,
461     |r: &RangeFrom<A>| r.start.clone(),
462     A,
463     unbounded_range(|a| a..),
464     |depth| <A as Arbitrary>::size_hint(depth)
465 );
466 impl_range!(
467     RangeInclusive<A>,
468     |r: &RangeInclusive<A>| (r.start().clone(), r.end().clone()),
469     (A, A),
470     bounded_range(|(a, b)| a..=b),
471     |depth| crate::size_hint::and(
472         <A as Arbitrary>::size_hint(depth),
473         <A as Arbitrary>::size_hint(depth)
474     )
475 );
476 impl_range!(
477     RangeTo<A>,
478     |r: &RangeTo<A>| r.end.clone(),
479     A,
480     unbounded_range(|b| ..b),
481     |depth| <A as Arbitrary>::size_hint(depth)
482 );
483 impl_range!(
484     RangeToInclusive<A>,
485     |r: &RangeToInclusive<A>| r.end.clone(),
486     A,
487     unbounded_range(|b| ..=b),
488     |depth| <A as Arbitrary>::size_hint(depth)
489 );
490 
bounded_range<CB, I, R>(bounds: (I, I), cb: CB) -> R where CB: Fn((I, I)) -> R, I: PartialOrd, R: RangeBounds<I>,491 pub(crate) fn bounded_range<CB, I, R>(bounds: (I, I), cb: CB) -> R
492 where
493     CB: Fn((I, I)) -> R,
494     I: PartialOrd,
495     R: RangeBounds<I>,
496 {
497     let (mut start, mut end) = bounds;
498     if start > end {
499         mem::swap(&mut start, &mut end);
500     }
501     cb((start, end))
502 }
503 
unbounded_range<CB, I, R>(bound: I, cb: CB) -> R where CB: Fn(I) -> R, R: RangeBounds<I>,504 pub(crate) fn unbounded_range<CB, I, R>(bound: I, cb: CB) -> R
505 where
506     CB: Fn(I) -> R,
507     R: RangeBounds<I>,
508 {
509     cb(bound)
510 }
511 
512 impl<'a> Arbitrary<'a> for Duration {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>513     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
514         Ok(Self::new(
515             <u64 as Arbitrary>::arbitrary(u)?,
516             u.int_in_range(0..=999_999_999)?,
517         ))
518     }
519 
520     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)521     fn size_hint(depth: usize) -> (usize, Option<usize>) {
522         crate::size_hint::and(
523             <u64 as Arbitrary>::size_hint(depth),
524             <u32 as Arbitrary>::size_hint(depth),
525         )
526     }
527 }
528 
529 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for Option<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>530     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
531         Ok(if <bool as Arbitrary<'a>>::arbitrary(u)? {
532             Some(Arbitrary::arbitrary(u)?)
533         } else {
534             None
535         })
536     }
537 
538     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)539     fn size_hint(depth: usize) -> (usize, Option<usize>) {
540         crate::size_hint::and(
541             <bool as Arbitrary>::size_hint(depth),
542             crate::size_hint::or((0, Some(0)), <A as Arbitrary>::size_hint(depth)),
543         )
544     }
545 }
546 
547 impl<'a, A: Arbitrary<'a>, B: Arbitrary<'a>> Arbitrary<'a> for std::result::Result<A, B> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>548     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
549         Ok(if <bool as Arbitrary<'a>>::arbitrary(u)? {
550             Ok(<A as Arbitrary>::arbitrary(u)?)
551         } else {
552             Err(<B as Arbitrary>::arbitrary(u)?)
553         })
554     }
555 
556     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)557     fn size_hint(depth: usize) -> (usize, Option<usize>) {
558         crate::size_hint::and(
559             <bool as Arbitrary>::size_hint(depth),
560             crate::size_hint::or(
561                 <A as Arbitrary>::size_hint(depth),
562                 <B as Arbitrary>::size_hint(depth),
563             ),
564         )
565     }
566 }
567 
568 macro_rules! arbitrary_tuple {
569     () => {};
570     ($last: ident $($xs: ident)*) => {
571         arbitrary_tuple!($($xs)*);
572 
573         impl<'a, $($xs: Arbitrary<'a>,)* $last: Arbitrary<'a>> Arbitrary<'a> for ($($xs,)* $last,) {
574             fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
575                 Ok(($($xs::arbitrary(u)?,)* Arbitrary::arbitrary(u)?,))
576             }
577 
578             #[allow(unused_mut, non_snake_case)]
579             fn arbitrary_take_rest(mut u: Unstructured<'a>) -> Result<Self> {
580                 $(let $xs = $xs::arbitrary(&mut u)?;)*
581                 let $last = $last::arbitrary_take_rest(u)?;
582                 Ok(($($xs,)* $last,))
583             }
584 
585             #[inline]
586             fn size_hint(depth: usize) -> (usize, Option<usize>) {
587                 crate::size_hint::and_all(&[
588                     <$last as Arbitrary>::size_hint(depth),
589                     $( <$xs as Arbitrary>::size_hint(depth) ),*
590                 ])
591             }
592         }
593     };
594 }
595 arbitrary_tuple!(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z);
596 
597 // Helper to safely create arrays since the standard library doesn't
598 // provide one yet. Shouldn't be necessary in the future.
599 struct ArrayGuard<T, const N: usize> {
600     dst: *mut T,
601     initialized: usize,
602 }
603 
604 impl<T, const N: usize> Drop for ArrayGuard<T, N> {
drop(&mut self)605     fn drop(&mut self) {
606         debug_assert!(self.initialized <= N);
607         let initialized_part = core::ptr::slice_from_raw_parts_mut(self.dst, self.initialized);
608         unsafe {
609             core::ptr::drop_in_place(initialized_part);
610         }
611     }
612 }
613 
try_create_array<F, T, const N: usize>(mut cb: F) -> Result<[T; N]> where F: FnMut(usize) -> Result<T>,614 fn try_create_array<F, T, const N: usize>(mut cb: F) -> Result<[T; N]>
615 where
616     F: FnMut(usize) -> Result<T>,
617 {
618     let mut array: mem::MaybeUninit<[T; N]> = mem::MaybeUninit::uninit();
619     let array_ptr = array.as_mut_ptr();
620     let dst = array_ptr as _;
621     let mut guard: ArrayGuard<T, N> = ArrayGuard {
622         dst,
623         initialized: 0,
624     };
625     unsafe {
626         for (idx, value_ptr) in (*array.as_mut_ptr()).iter_mut().enumerate() {
627             core::ptr::write(value_ptr, cb(idx)?);
628             guard.initialized += 1;
629         }
630         mem::forget(guard);
631         Ok(array.assume_init())
632     }
633 }
634 
635 impl<'a, T, const N: usize> Arbitrary<'a> for [T; N]
636 where
637     T: Arbitrary<'a>,
638 {
639     #[inline]
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>640     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
641         try_create_array(|_| <T as Arbitrary<'a>>::arbitrary(u))
642     }
643 
644     #[inline]
arbitrary_take_rest(mut u: Unstructured<'a>) -> Result<Self>645     fn arbitrary_take_rest(mut u: Unstructured<'a>) -> Result<Self> {
646         let mut array = Self::arbitrary(&mut u)?;
647         if let Some(last) = array.last_mut() {
648             *last = Arbitrary::arbitrary_take_rest(u)?;
649         }
650         Ok(array)
651     }
652 
653     #[inline]
size_hint(d: usize) -> (usize, Option<usize>)654     fn size_hint(d: usize) -> (usize, Option<usize>) {
655         crate::size_hint::and_all(&array::from_fn::<_, N, _>(|_| {
656             <T as Arbitrary>::size_hint(d)
657         }))
658     }
659 }
660 
661 impl<'a> Arbitrary<'a> for &'a [u8] {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>662     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
663         let len = u.arbitrary_len::<u8>()?;
664         u.bytes(len)
665     }
666 
arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self>667     fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
668         Ok(u.take_rest())
669     }
670 
671     #[inline]
size_hint(_depth: usize) -> (usize, Option<usize>)672     fn size_hint(_depth: usize) -> (usize, Option<usize>) {
673         (0, None)
674     }
675 }
676 
677 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for Vec<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>678     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
679         u.arbitrary_iter()?.collect()
680     }
681 
arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self>682     fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
683         u.arbitrary_take_rest_iter()?.collect()
684     }
685 
686     #[inline]
size_hint(_depth: usize) -> (usize, Option<usize>)687     fn size_hint(_depth: usize) -> (usize, Option<usize>) {
688         (0, None)
689     }
690 }
691 
692 impl<'a, K: Arbitrary<'a> + Ord, V: Arbitrary<'a>> Arbitrary<'a> for BTreeMap<K, V> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>693     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
694         u.arbitrary_iter()?.collect()
695     }
696 
arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self>697     fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
698         u.arbitrary_take_rest_iter()?.collect()
699     }
700 
701     #[inline]
size_hint(_depth: usize) -> (usize, Option<usize>)702     fn size_hint(_depth: usize) -> (usize, Option<usize>) {
703         (0, None)
704     }
705 }
706 
707 impl<'a, A: Arbitrary<'a> + Ord> Arbitrary<'a> for BTreeSet<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>708     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
709         u.arbitrary_iter()?.collect()
710     }
711 
arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self>712     fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
713         u.arbitrary_take_rest_iter()?.collect()
714     }
715 
716     #[inline]
size_hint(_depth: usize) -> (usize, Option<usize>)717     fn size_hint(_depth: usize) -> (usize, Option<usize>) {
718         (0, None)
719     }
720 }
721 
722 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for Bound<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>723     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
724         match u.int_in_range::<u8>(0..=2)? {
725             0 => Ok(Bound::Included(A::arbitrary(u)?)),
726             1 => Ok(Bound::Excluded(A::arbitrary(u)?)),
727             2 => Ok(Bound::Unbounded),
728             _ => unreachable!(),
729         }
730     }
731 
732     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)733     fn size_hint(depth: usize) -> (usize, Option<usize>) {
734         size_hint::or(
735             size_hint::and((1, Some(1)), A::size_hint(depth)),
736             (1, Some(1)),
737         )
738     }
739 }
740 
741 impl<'a, A: Arbitrary<'a> + Ord> Arbitrary<'a> for BinaryHeap<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>742     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
743         u.arbitrary_iter()?.collect()
744     }
745 
arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self>746     fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
747         u.arbitrary_take_rest_iter()?.collect()
748     }
749 
750     #[inline]
size_hint(_depth: usize) -> (usize, Option<usize>)751     fn size_hint(_depth: usize) -> (usize, Option<usize>) {
752         (0, None)
753     }
754 }
755 
756 impl<'a, K: Arbitrary<'a> + Eq + ::std::hash::Hash, V: Arbitrary<'a>, S: BuildHasher + Default>
757     Arbitrary<'a> for HashMap<K, V, S>
758 {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>759     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
760         u.arbitrary_iter()?.collect()
761     }
762 
arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self>763     fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
764         u.arbitrary_take_rest_iter()?.collect()
765     }
766 
767     #[inline]
size_hint(_depth: usize) -> (usize, Option<usize>)768     fn size_hint(_depth: usize) -> (usize, Option<usize>) {
769         (0, None)
770     }
771 }
772 
773 impl<'a, A: Arbitrary<'a> + Eq + ::std::hash::Hash, S: BuildHasher + Default> Arbitrary<'a>
774     for HashSet<A, S>
775 {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>776     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
777         u.arbitrary_iter()?.collect()
778     }
779 
arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self>780     fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
781         u.arbitrary_take_rest_iter()?.collect()
782     }
783 
784     #[inline]
size_hint(_depth: usize) -> (usize, Option<usize>)785     fn size_hint(_depth: usize) -> (usize, Option<usize>) {
786         (0, None)
787     }
788 }
789 
790 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for LinkedList<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>791     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
792         u.arbitrary_iter()?.collect()
793     }
794 
arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self>795     fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
796         u.arbitrary_take_rest_iter()?.collect()
797     }
798 
799     #[inline]
size_hint(_depth: usize) -> (usize, Option<usize>)800     fn size_hint(_depth: usize) -> (usize, Option<usize>) {
801         (0, None)
802     }
803 }
804 
805 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for VecDeque<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>806     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
807         u.arbitrary_iter()?.collect()
808     }
809 
arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self>810     fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
811         u.arbitrary_take_rest_iter()?.collect()
812     }
813 
814     #[inline]
size_hint(_depth: usize) -> (usize, Option<usize>)815     fn size_hint(_depth: usize) -> (usize, Option<usize>) {
816         (0, None)
817     }
818 }
819 
820 impl<'a, A> Arbitrary<'a> for Cow<'a, A>
821 where
822     A: ToOwned + ?Sized,
823     <A as ToOwned>::Owned: Arbitrary<'a>,
824 {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>825     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
826         Arbitrary::arbitrary(u).map(Cow::Owned)
827     }
828 
829     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)830     fn size_hint(depth: usize) -> (usize, Option<usize>) {
831         crate::size_hint::recursion_guard(depth, |depth| {
832             <<A as ToOwned>::Owned as Arbitrary>::size_hint(depth)
833         })
834     }
835 }
836 
837 impl<'a> Arbitrary<'a> for &'a str {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>838     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
839         let size = u.arbitrary_len::<u8>()?;
840         match str::from_utf8(u.peek_bytes(size).unwrap()) {
841             Ok(s) => {
842                 u.bytes(size).unwrap();
843                 Ok(s)
844             }
845             Err(e) => {
846                 let i = e.valid_up_to();
847                 let valid = u.bytes(i).unwrap();
848                 let s = unsafe {
849                     debug_assert!(str::from_utf8(valid).is_ok());
850                     str::from_utf8_unchecked(valid)
851                 };
852                 Ok(s)
853             }
854         }
855     }
856 
arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self>857     fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
858         let bytes = u.take_rest();
859         str::from_utf8(bytes).map_err(|_| Error::IncorrectFormat)
860     }
861 
862     #[inline]
size_hint(_depth: usize) -> (usize, Option<usize>)863     fn size_hint(_depth: usize) -> (usize, Option<usize>) {
864         (0, None)
865     }
866 }
867 
868 impl<'a> Arbitrary<'a> for String {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>869     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
870         <&str as Arbitrary>::arbitrary(u).map(Into::into)
871     }
872 
arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self>873     fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
874         <&str as Arbitrary>::arbitrary_take_rest(u).map(Into::into)
875     }
876 
877     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)878     fn size_hint(depth: usize) -> (usize, Option<usize>) {
879         <&str as Arbitrary>::size_hint(depth)
880     }
881 }
882 
883 impl<'a> Arbitrary<'a> for CString {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>884     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
885         <Vec<u8> as Arbitrary>::arbitrary(u).map(|mut x| {
886             x.retain(|&c| c != 0);
887             Self::new(x).unwrap()
888         })
889     }
890 
891     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)892     fn size_hint(depth: usize) -> (usize, Option<usize>) {
893         <Vec<u8> as Arbitrary>::size_hint(depth)
894     }
895 }
896 
897 impl<'a> Arbitrary<'a> for OsString {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>898     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
899         <String as Arbitrary>::arbitrary(u).map(From::from)
900     }
901 
902     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)903     fn size_hint(depth: usize) -> (usize, Option<usize>) {
904         <String as Arbitrary>::size_hint(depth)
905     }
906 }
907 
908 impl<'a> Arbitrary<'a> for PathBuf {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>909     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
910         <OsString as Arbitrary>::arbitrary(u).map(From::from)
911     }
912 
913     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)914     fn size_hint(depth: usize) -> (usize, Option<usize>) {
915         <OsString as Arbitrary>::size_hint(depth)
916     }
917 }
918 
919 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for Box<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>920     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
921         Arbitrary::arbitrary(u).map(Self::new)
922     }
923 
924     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)925     fn size_hint(depth: usize) -> (usize, Option<usize>) {
926         crate::size_hint::recursion_guard(depth, <A as Arbitrary>::size_hint)
927     }
928 }
929 
930 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for Box<[A]> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>931     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
932         <Vec<A> as Arbitrary>::arbitrary(u).map(|x| x.into_boxed_slice())
933     }
934 
935     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)936     fn size_hint(depth: usize) -> (usize, Option<usize>) {
937         <Vec<A> as Arbitrary>::size_hint(depth)
938     }
939 }
940 
941 impl<'a> Arbitrary<'a> for Box<str> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>942     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
943         <String as Arbitrary>::arbitrary(u).map(|x| x.into_boxed_str())
944     }
945 
946     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)947     fn size_hint(depth: usize) -> (usize, Option<usize>) {
948         <String as Arbitrary>::size_hint(depth)
949     }
950 }
951 
952 // impl Arbitrary for Box<CStr> {
953 //     fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> {
954 //         <CString as Arbitrary>::arbitrary(u).map(|x| x.into_boxed_c_str())
955 //     }
956 // }
957 
958 // impl Arbitrary for Box<OsStr> {
959 //     fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> {
960 //         <OsString as Arbitrary>::arbitrary(u).map(|x| x.into_boxed_osstr())
961 //
962 //     }
963 // }
964 
965 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for Arc<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>966     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
967         Arbitrary::arbitrary(u).map(Self::new)
968     }
969 
970     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)971     fn size_hint(depth: usize) -> (usize, Option<usize>) {
972         crate::size_hint::recursion_guard(depth, <A as Arbitrary>::size_hint)
973     }
974 }
975 
976 impl<'a> Arbitrary<'a> for Arc<str> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>977     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
978         <&str as Arbitrary>::arbitrary(u).map(Into::into)
979     }
980 
981     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)982     fn size_hint(depth: usize) -> (usize, Option<usize>) {
983         <&str as Arbitrary>::size_hint(depth)
984     }
985 }
986 
987 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for Rc<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>988     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
989         Arbitrary::arbitrary(u).map(Self::new)
990     }
991 
992     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)993     fn size_hint(depth: usize) -> (usize, Option<usize>) {
994         crate::size_hint::recursion_guard(depth, <A as Arbitrary>::size_hint)
995     }
996 }
997 
998 impl<'a> Arbitrary<'a> for Rc<str> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>999     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
1000         <&str as Arbitrary>::arbitrary(u).map(Into::into)
1001     }
1002 
1003     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)1004     fn size_hint(depth: usize) -> (usize, Option<usize>) {
1005         <&str as Arbitrary>::size_hint(depth)
1006     }
1007 }
1008 
1009 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for Cell<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>1010     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
1011         Arbitrary::arbitrary(u).map(Self::new)
1012     }
1013 
1014     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)1015     fn size_hint(depth: usize) -> (usize, Option<usize>) {
1016         <A as Arbitrary<'a>>::size_hint(depth)
1017     }
1018 }
1019 
1020 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for RefCell<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>1021     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
1022         Arbitrary::arbitrary(u).map(Self::new)
1023     }
1024 
1025     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)1026     fn size_hint(depth: usize) -> (usize, Option<usize>) {
1027         <A as Arbitrary<'a>>::size_hint(depth)
1028     }
1029 }
1030 
1031 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for UnsafeCell<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>1032     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
1033         Arbitrary::arbitrary(u).map(Self::new)
1034     }
1035 
1036     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)1037     fn size_hint(depth: usize) -> (usize, Option<usize>) {
1038         <A as Arbitrary<'a>>::size_hint(depth)
1039     }
1040 }
1041 
1042 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for Mutex<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>1043     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
1044         Arbitrary::arbitrary(u).map(Self::new)
1045     }
1046 
1047     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)1048     fn size_hint(depth: usize) -> (usize, Option<usize>) {
1049         <A as Arbitrary<'a>>::size_hint(depth)
1050     }
1051 }
1052 
1053 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for iter::Empty<A> {
arbitrary(_: &mut Unstructured<'a>) -> Result<Self>1054     fn arbitrary(_: &mut Unstructured<'a>) -> Result<Self> {
1055         Ok(iter::empty())
1056     }
1057 
1058     #[inline]
size_hint(_depth: usize) -> (usize, Option<usize>)1059     fn size_hint(_depth: usize) -> (usize, Option<usize>) {
1060         (0, Some(0))
1061     }
1062 }
1063 
1064 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for ::std::marker::PhantomData<A> {
arbitrary(_: &mut Unstructured<'a>) -> Result<Self>1065     fn arbitrary(_: &mut Unstructured<'a>) -> Result<Self> {
1066         Ok(::std::marker::PhantomData)
1067     }
1068 
1069     #[inline]
size_hint(_depth: usize) -> (usize, Option<usize>)1070     fn size_hint(_depth: usize) -> (usize, Option<usize>) {
1071         (0, Some(0))
1072     }
1073 }
1074 
1075 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for ::std::num::Wrapping<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>1076     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
1077         Arbitrary::arbitrary(u).map(::std::num::Wrapping)
1078     }
1079 
1080     #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)1081     fn size_hint(depth: usize) -> (usize, Option<usize>) {
1082         <A as Arbitrary<'a>>::size_hint(depth)
1083     }
1084 }
1085 
1086 macro_rules! implement_nonzero_int {
1087     ($nonzero:ty, $int:ty) => {
1088         impl<'a> Arbitrary<'a> for $nonzero {
1089             fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
1090                 match Self::new(<$int as Arbitrary<'a>>::arbitrary(u)?) {
1091                     Some(n) => Ok(n),
1092                     None => Err(Error::IncorrectFormat),
1093                 }
1094             }
1095 
1096             #[inline]
1097             fn size_hint(depth: usize) -> (usize, Option<usize>) {
1098                 <$int as Arbitrary<'a>>::size_hint(depth)
1099             }
1100         }
1101     };
1102 }
1103 
1104 implement_nonzero_int! { NonZeroI8, i8 }
1105 implement_nonzero_int! { NonZeroI16, i16 }
1106 implement_nonzero_int! { NonZeroI32, i32 }
1107 implement_nonzero_int! { NonZeroI64, i64 }
1108 implement_nonzero_int! { NonZeroI128, i128 }
1109 implement_nonzero_int! { NonZeroIsize, isize }
1110 implement_nonzero_int! { NonZeroU8, u8 }
1111 implement_nonzero_int! { NonZeroU16, u16 }
1112 implement_nonzero_int! { NonZeroU32, u32 }
1113 implement_nonzero_int! { NonZeroU64, u64 }
1114 implement_nonzero_int! { NonZeroU128, u128 }
1115 implement_nonzero_int! { NonZeroUsize, usize }
1116 
1117 impl<'a> Arbitrary<'a> for Ipv4Addr {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>1118     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
1119         Ok(Ipv4Addr::from(u32::arbitrary(u)?))
1120     }
1121 
1122     #[inline]
size_hint(_depth: usize) -> (usize, Option<usize>)1123     fn size_hint(_depth: usize) -> (usize, Option<usize>) {
1124         (4, Some(4))
1125     }
1126 }
1127 
1128 impl<'a> Arbitrary<'a> for Ipv6Addr {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>1129     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
1130         Ok(Ipv6Addr::from(u128::arbitrary(u)?))
1131     }
1132 
1133     #[inline]
size_hint(_depth: usize) -> (usize, Option<usize>)1134     fn size_hint(_depth: usize) -> (usize, Option<usize>) {
1135         (16, Some(16))
1136     }
1137 }
1138 
1139 #[cfg(test)]
1140 mod test {
1141     use super::*;
1142 
1143     /// Generates an arbitrary `T`, and checks that the result is consistent with the
1144     /// `size_hint()` reported by `T`.
checked_arbitrary<'a, T: Arbitrary<'a>>(u: &mut Unstructured<'a>) -> Result<T>1145     fn checked_arbitrary<'a, T: Arbitrary<'a>>(u: &mut Unstructured<'a>) -> Result<T> {
1146         let (min, max) = T::size_hint(0);
1147 
1148         let len_before = u.len();
1149         let result = T::arbitrary(u);
1150 
1151         let consumed = len_before - u.len();
1152 
1153         if let Some(max) = max {
1154             assert!(
1155                 consumed <= max,
1156                 "incorrect maximum size: indicated {}, actually consumed {}",
1157                 max,
1158                 consumed
1159             );
1160         }
1161 
1162         if result.is_ok() {
1163             assert!(
1164                 consumed >= min,
1165                 "incorrect minimum size: indicated {}, actually consumed {}",
1166                 min,
1167                 consumed
1168             );
1169         }
1170 
1171         result
1172     }
1173 
1174     /// Like `checked_arbitrary()`, but calls `arbitrary_take_rest()` instead of `arbitrary()`.
checked_arbitrary_take_rest<'a, T: Arbitrary<'a>>(u: Unstructured<'a>) -> Result<T>1175     fn checked_arbitrary_take_rest<'a, T: Arbitrary<'a>>(u: Unstructured<'a>) -> Result<T> {
1176         let (min, _) = T::size_hint(0);
1177 
1178         let len_before = u.len();
1179         let result = T::arbitrary_take_rest(u);
1180 
1181         if result.is_ok() {
1182             assert!(
1183                 len_before >= min,
1184                 "incorrect minimum size: indicated {}, worked with {}",
1185                 min,
1186                 len_before
1187             );
1188         }
1189 
1190         result
1191     }
1192 
1193     #[test]
finite_buffer_fill_buffer()1194     fn finite_buffer_fill_buffer() {
1195         let x = [1, 2, 3, 4];
1196         let mut rb = Unstructured::new(&x);
1197         let mut z = [0; 2];
1198         rb.fill_buffer(&mut z).unwrap();
1199         assert_eq!(z, [1, 2]);
1200         rb.fill_buffer(&mut z).unwrap();
1201         assert_eq!(z, [3, 4]);
1202         rb.fill_buffer(&mut z).unwrap();
1203         assert_eq!(z, [0, 0]);
1204     }
1205 
1206     #[test]
arbitrary_for_integers()1207     fn arbitrary_for_integers() {
1208         let x = [1, 2, 3, 4];
1209         let mut buf = Unstructured::new(&x);
1210         let expected = 1 | (2 << 8) | (3 << 16) | (4 << 24);
1211         let actual = checked_arbitrary::<i32>(&mut buf).unwrap();
1212         assert_eq!(expected, actual);
1213     }
1214 
1215     #[test]
arbitrary_for_bytes()1216     fn arbitrary_for_bytes() {
1217         let x = [1, 2, 3, 4, 4];
1218         let mut buf = Unstructured::new(&x);
1219         let expected = &[1, 2, 3, 4];
1220         let actual = checked_arbitrary::<&[u8]>(&mut buf).unwrap();
1221         assert_eq!(expected, actual);
1222     }
1223 
1224     #[test]
arbitrary_take_rest_for_bytes()1225     fn arbitrary_take_rest_for_bytes() {
1226         let x = [1, 2, 3, 4];
1227         let buf = Unstructured::new(&x);
1228         let expected = &[1, 2, 3, 4];
1229         let actual = checked_arbitrary_take_rest::<&[u8]>(buf).unwrap();
1230         assert_eq!(expected, actual);
1231     }
1232 
1233     #[test]
arbitrary_collection()1234     fn arbitrary_collection() {
1235         let x = [
1236             1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 12,
1237         ];
1238         assert_eq!(
1239             checked_arbitrary::<&[u8]>(&mut Unstructured::new(&x)).unwrap(),
1240             &[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3]
1241         );
1242         assert_eq!(
1243             checked_arbitrary::<Vec<u8>>(&mut Unstructured::new(&x)).unwrap(),
1244             &[2, 4, 6, 8, 1]
1245         );
1246         assert_eq!(
1247             checked_arbitrary::<Vec<u32>>(&mut Unstructured::new(&x)).unwrap(),
1248             &[84148994]
1249         );
1250         assert_eq!(
1251             checked_arbitrary::<String>(&mut Unstructured::new(&x)).unwrap(),
1252             "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x01\x02\x03"
1253         );
1254     }
1255 
1256     #[test]
arbitrary_take_rest()1257     fn arbitrary_take_rest() {
1258         let x = [1, 2, 3, 4];
1259         assert_eq!(
1260             checked_arbitrary_take_rest::<&[u8]>(Unstructured::new(&x)).unwrap(),
1261             &[1, 2, 3, 4]
1262         );
1263         assert_eq!(
1264             checked_arbitrary_take_rest::<Vec<u8>>(Unstructured::new(&x)).unwrap(),
1265             &[1, 2, 3, 4]
1266         );
1267         assert_eq!(
1268             checked_arbitrary_take_rest::<Vec<u32>>(Unstructured::new(&x)).unwrap(),
1269             &[0x4030201]
1270         );
1271         assert_eq!(
1272             checked_arbitrary_take_rest::<String>(Unstructured::new(&x)).unwrap(),
1273             "\x01\x02\x03\x04"
1274         );
1275 
1276         assert_eq!(
1277             checked_arbitrary_take_rest::<&[u8]>(Unstructured::new(&[])).unwrap(),
1278             &[]
1279         );
1280         assert_eq!(
1281             checked_arbitrary_take_rest::<Vec<u8>>(Unstructured::new(&[])).unwrap(),
1282             &[]
1283         );
1284     }
1285 
1286     #[test]
size_hint_for_tuples()1287     fn size_hint_for_tuples() {
1288         assert_eq!(
1289             (7, Some(7)),
1290             <(bool, u16, i32) as Arbitrary<'_>>::size_hint(0)
1291         );
1292         assert_eq!((1, None), <(u8, Vec<u8>) as Arbitrary>::size_hint(0));
1293     }
1294 }
1295 
1296 /// Multiple conflicting arbitrary attributes are used on the same field:
1297 /// ```compile_fail
1298 /// #[derive(::arbitrary::Arbitrary)]
1299 /// struct Point {
1300 ///     #[arbitrary(value = 2)]
1301 ///     #[arbitrary(value = 2)]
1302 ///     x: i32,
1303 /// }
1304 /// ```
1305 ///
1306 /// An unknown attribute:
1307 /// ```compile_fail
1308 /// #[derive(::arbitrary::Arbitrary)]
1309 /// struct Point {
1310 ///     #[arbitrary(unknown_attr)]
1311 ///     x: i32,
1312 /// }
1313 /// ```
1314 ///
1315 /// An unknown attribute with a value:
1316 /// ```compile_fail
1317 /// #[derive(::arbitrary::Arbitrary)]
1318 /// struct Point {
1319 ///     #[arbitrary(unknown_attr = 13)]
1320 ///     x: i32,
1321 /// }
1322 /// ```
1323 ///
1324 /// `value` without RHS:
1325 /// ```compile_fail
1326 /// #[derive(::arbitrary::Arbitrary)]
1327 /// struct Point {
1328 ///     #[arbitrary(value)]
1329 ///     x: i32,
1330 /// }
1331 /// ```
1332 ///
1333 /// `with` without RHS:
1334 /// ```compile_fail
1335 /// #[derive(::arbitrary::Arbitrary)]
1336 /// struct Point {
1337 ///     #[arbitrary(with)]
1338 ///     x: i32,
1339 /// }
1340 /// ```
1341 #[cfg(all(doctest, feature = "derive"))]
1342 pub struct CompileFailTests;
1343