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::cell::{Cell, RefCell, UnsafeCell};
38 use core::iter;
39 use core::mem;
40 use core::ops::{Range, RangeBounds, RangeFrom, RangeInclusive, RangeTo, RangeToInclusive};
41 use core::str;
42 use core::time::Duration;
43 use std::borrow::{Cow, ToOwned};
44 use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque};
45 use std::ffi::{CString, OsString};
46 use std::path::PathBuf;
47 use std::rc::Rc;
48 use std::sync::atomic::{AtomicBool, AtomicIsize, AtomicUsize};
49 use std::sync::{Arc, Mutex};
50
51 /// Generate arbitrary structured values from raw, unstructured data.
52 ///
53 /// The `Arbitrary` trait allows you to generate valid structured values, like
54 /// `HashMap`s, or ASTs, or `MyTomlConfig`, or any other data structure from
55 /// raw, unstructured bytes provided by a fuzzer.
56 ///
57 /// # Deriving `Arbitrary`
58 ///
59 /// Automatically deriving the `Arbitrary` trait is the recommended way to
60 /// implement `Arbitrary` for your types.
61 ///
62 /// Using the custom derive requires that you enable the `"derive"` cargo
63 /// feature in your `Cargo.toml`:
64 ///
65 /// ```toml
66 /// [dependencies]
67 /// arbitrary = { version = "1", features = ["derive"] }
68 /// ```
69 ///
70 /// Then, you add the `#[derive(Arbitrary)]` annotation to your `struct` or
71 /// `enum` type definition:
72 ///
73 /// ```
74 /// # #[cfg(feature = "derive")] mod foo {
75 /// use arbitrary::Arbitrary;
76 /// use std::collections::HashSet;
77 ///
78 /// #[derive(Arbitrary)]
79 /// pub struct AddressBook {
80 /// friends: HashSet<Friend>,
81 /// }
82 ///
83 /// #[derive(Arbitrary, Hash, Eq, PartialEq)]
84 /// pub enum Friend {
85 /// Buddy { name: String },
86 /// Pal { age: usize },
87 /// }
88 /// # }
89 /// ```
90 ///
91 /// Every member of the `struct` or `enum` must also implement `Arbitrary`.
92 ///
93 /// # Implementing `Arbitrary` By Hand
94 ///
95 /// Implementing `Arbitrary` mostly involves nested calls to other `Arbitrary`
96 /// arbitrary implementations for each of your `struct` or `enum`'s members. But
97 /// sometimes you need some amount of raw data, or you need to generate a
98 /// variably-sized collection type, or you something of that sort. The
99 /// [`Unstructured`][crate::Unstructured] type helps you with these tasks.
100 ///
101 /// ```
102 /// # #[cfg(feature = "derive")] mod foo {
103 /// # pub struct MyCollection<T> { _t: std::marker::PhantomData<T> }
104 /// # impl<T> MyCollection<T> {
105 /// # pub fn new() -> Self { MyCollection { _t: std::marker::PhantomData } }
106 /// # pub fn insert(&mut self, element: T) {}
107 /// # }
108 /// use arbitrary::{Arbitrary, Result, Unstructured};
109 ///
110 /// impl<'a, T> Arbitrary<'a> for MyCollection<T>
111 /// where
112 /// T: Arbitrary<'a>,
113 /// {
114 /// fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
115 /// // Get an iterator of arbitrary `T`s.
116 /// let iter = u.arbitrary_iter::<T>()?;
117 ///
118 /// // And then create a collection!
119 /// let mut my_collection = MyCollection::new();
120 /// for elem_result in iter {
121 /// let elem = elem_result?;
122 /// my_collection.insert(elem);
123 /// }
124 ///
125 /// Ok(my_collection)
126 /// }
127 /// }
128 /// # }
129 /// ```
130 pub trait Arbitrary<'a>: Sized {
131 /// Generate an arbitrary value of `Self` from the given unstructured data.
132 ///
133 /// Calling `Arbitrary::arbitrary` requires that you have some raw data,
134 /// perhaps given to you by a fuzzer like AFL or libFuzzer. You wrap this
135 /// raw data in an `Unstructured`, and then you can call `<MyType as
136 /// Arbitrary>::arbitrary` to construct an arbitrary instance of `MyType`
137 /// from that unstuctured data.
138 ///
139 /// Implementation may return an error if there is not enough data to
140 /// construct a full instance of `Self`. This is generally OK: it is better
141 /// to exit early and get the fuzzer to provide more input data, than it is
142 /// to generate default values in place of the missing data, which would
143 /// bias the distribution of generated values, and ultimately make fuzzing
144 /// less efficient.
145 ///
146 /// ```
147 /// # #[cfg(feature = "derive")] fn foo() {
148 /// use arbitrary::{Arbitrary, Unstructured};
149 ///
150 /// #[derive(Arbitrary)]
151 /// pub struct MyType {
152 /// // ...
153 /// }
154 ///
155 /// // Get the raw data from the fuzzer or wherever else.
156 /// # let get_raw_data_from_fuzzer = || &[];
157 /// let raw_data: &[u8] = get_raw_data_from_fuzzer();
158 ///
159 /// // Wrap that raw data in an `Unstructured`.
160 /// let mut unstructured = Unstructured::new(raw_data);
161 ///
162 /// // Generate an arbitrary instance of `MyType` and do stuff with it.
163 /// if let Ok(value) = MyType::arbitrary(&mut unstructured) {
164 /// # let do_stuff = |_| {};
165 /// do_stuff(value);
166 /// }
167 /// # }
168 /// ```
169 ///
170 /// See also the documentation for [`Unstructured`][crate::Unstructured].
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>171 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self>;
172
173 /// Generate an arbitrary value of `Self` from the entirety of the given unstructured data.
174 ///
175 /// This is similar to Arbitrary::arbitrary, however it assumes that it is the
176 /// last consumer of the given data, and is thus able to consume it all if it needs.
177 /// See also the documentation for [`Unstructured`][crate::Unstructured].
arbitrary_take_rest(mut u: Unstructured<'a>) -> Result<Self>178 fn arbitrary_take_rest(mut u: Unstructured<'a>) -> Result<Self> {
179 Self::arbitrary(&mut u)
180 }
181
182 /// Get a size hint for how many bytes out of an `Unstructured` this type
183 /// needs to construct itself.
184 ///
185 /// This is useful for determining how many elements we should insert when
186 /// creating an arbitrary collection.
187 ///
188 /// The return value is similar to
189 /// [`Iterator::size_hint`][iterator-size-hint]: it returns a tuple where
190 /// the first element is a lower bound on the number of bytes required, and
191 /// the second element is an optional upper bound.
192 ///
193 /// The default implementation return `(0, None)` which is correct for any
194 /// type, but not ultimately that useful. Using `#[derive(Arbitrary)]` will
195 /// create a better implementation. If you are writing an `Arbitrary`
196 /// implementation by hand, and your type can be part of a dynamically sized
197 /// collection (such as `Vec`), you are strongly encouraged to override this
198 /// default with a better implementation. The
199 /// [`size_hint`][crate::size_hint] module will help with this task.
200 ///
201 /// ## The `depth` Parameter
202 ///
203 /// If you 100% know that the type you are implementing `Arbitrary` for is
204 /// not a recursive type, or your implementation is not transitively calling
205 /// any other `size_hint` methods, you can ignore the `depth` parameter.
206 /// Note that if you are implementing `Arbitrary` for a generic type, you
207 /// cannot guarantee the lack of type recrusion!
208 ///
209 /// Otherwise, you need to use
210 /// [`arbitrary::size_hint::recursion_guard(depth)`][crate::size_hint::recursion_guard]
211 /// to prevent potential infinite recursion when calculating size hints for
212 /// potentially recursive types:
213 ///
214 /// ```
215 /// use arbitrary::{Arbitrary, Unstructured, size_hint};
216 ///
217 /// // This can potentially be a recursive type if `L` or `R` contain
218 /// // something like `Box<Option<MyEither<L, R>>>`!
219 /// enum MyEither<L, R> {
220 /// Left(L),
221 /// Right(R),
222 /// }
223 ///
224 /// impl<'a, L, R> Arbitrary<'a> for MyEither<L, R>
225 /// where
226 /// L: Arbitrary<'a>,
227 /// R: Arbitrary<'a>,
228 /// {
229 /// fn arbitrary(u: &mut Unstructured) -> arbitrary::Result<Self> {
230 /// // ...
231 /// # unimplemented!()
232 /// }
233 ///
234 /// fn size_hint(depth: usize) -> (usize, Option<usize>) {
235 /// // Protect against potential infinite recursion with
236 /// // `recursion_guard`.
237 /// size_hint::recursion_guard(depth, |depth| {
238 /// // If we aren't too deep, then `recursion_guard` calls
239 /// // this closure, which implements the natural size hint.
240 /// // Don't forget to use the new `depth` in all nested
241 /// // `size_hint` calls! We recommend shadowing the
242 /// // parameter, like what is done here, so that you can't
243 /// // accidentally use the wrong depth.
244 /// size_hint::or(
245 /// <L as Arbitrary>::size_hint(depth),
246 /// <R as Arbitrary>::size_hint(depth),
247 /// )
248 /// })
249 /// }
250 /// }
251 /// ```
252 ///
253 /// [iterator-size-hint]: https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.size_hint
254 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)255 fn size_hint(depth: usize) -> (usize, Option<usize>) {
256 let _ = depth;
257 (0, None)
258 }
259 }
260
261 impl<'a> Arbitrary<'a> for () {
arbitrary(_: &mut Unstructured<'a>) -> Result<Self>262 fn arbitrary(_: &mut Unstructured<'a>) -> Result<Self> {
263 Ok(())
264 }
265
266 #[inline]
size_hint(_depth: usize) -> (usize, Option<usize>)267 fn size_hint(_depth: usize) -> (usize, Option<usize>) {
268 (0, Some(0))
269 }
270 }
271
272 impl<'a> Arbitrary<'a> for bool {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>273 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
274 Ok(<u8 as Arbitrary<'a>>::arbitrary(u)? & 1 == 1)
275 }
276
277 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)278 fn size_hint(depth: usize) -> (usize, Option<usize>) {
279 <u8 as Arbitrary<'a>>::size_hint(depth)
280 }
281 }
282
283 macro_rules! impl_arbitrary_for_integers {
284 ( $( $ty:ty: $unsigned:ty; )* ) => {
285 $(
286 impl<'a> Arbitrary<'a> for $ty {
287 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
288 let mut buf = [0; mem::size_of::<$ty>()];
289 u.fill_buffer(&mut buf)?;
290 let mut x: $unsigned = 0;
291 for i in 0..mem::size_of::<$ty>() {
292 x |= buf[i] as $unsigned << (i * 8);
293 }
294 Ok(x as $ty)
295 }
296
297 #[inline]
298 fn size_hint(_depth: usize) -> (usize, Option<usize>) {
299 let n = mem::size_of::<$ty>();
300 (n, Some(n))
301 }
302
303 }
304 )*
305 }
306 }
307
308 impl_arbitrary_for_integers! {
309 u8: u8;
310 u16: u16;
311 u32: u32;
312 u64: u64;
313 u128: u128;
314 usize: usize;
315 i8: u8;
316 i16: u16;
317 i32: u32;
318 i64: u64;
319 i128: u128;
320 isize: usize;
321 }
322
323 macro_rules! impl_arbitrary_for_floats {
324 ( $( $ty:ident : $unsigned:ty; )* ) => {
325 $(
326 impl<'a> Arbitrary<'a> for $ty {
327 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
328 Ok(Self::from_bits(<$unsigned as Arbitrary<'a>>::arbitrary(u)?))
329 }
330
331 #[inline]
332 fn size_hint(depth: usize) -> (usize, Option<usize>) {
333 <$unsigned as Arbitrary<'a>>::size_hint(depth)
334 }
335 }
336 )*
337 }
338 }
339
340 impl_arbitrary_for_floats! {
341 f32: u32;
342 f64: u64;
343 }
344
345 impl<'a> Arbitrary<'a> for char {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>346 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
347 use std::char;
348 const CHAR_END: u32 = 0x0011_000;
349 // The size of the surrogate blocks
350 const SURROGATES_START: u32 = 0xD800;
351 let mut c = <u32 as Arbitrary<'a>>::arbitrary(u)? % CHAR_END;
352 if let Some(c) = char::from_u32(c) {
353 return Ok(c);
354 } else {
355 // We found a surrogate, wrap and try again
356 c -= SURROGATES_START;
357 Ok(char::from_u32(c)
358 .expect("Generated character should be valid! This is a bug in arbitrary-rs"))
359 }
360 }
361
362 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)363 fn size_hint(depth: usize) -> (usize, Option<usize>) {
364 <u32 as Arbitrary<'a>>::size_hint(depth)
365 }
366 }
367
368 impl<'a> Arbitrary<'a> for AtomicBool {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>369 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
370 Arbitrary::arbitrary(u).map(Self::new)
371 }
372
373 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)374 fn size_hint(depth: usize) -> (usize, Option<usize>) {
375 <bool as Arbitrary<'a>>::size_hint(depth)
376 }
377 }
378
379 impl<'a> Arbitrary<'a> for AtomicIsize {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>380 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
381 Arbitrary::arbitrary(u).map(Self::new)
382 }
383
384 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)385 fn size_hint(depth: usize) -> (usize, Option<usize>) {
386 <isize as Arbitrary<'a>>::size_hint(depth)
387 }
388 }
389
390 impl<'a> Arbitrary<'a> for AtomicUsize {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>391 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
392 Arbitrary::arbitrary(u).map(Self::new)
393 }
394
395 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)396 fn size_hint(depth: usize) -> (usize, Option<usize>) {
397 <usize as Arbitrary<'a>>::size_hint(depth)
398 }
399 }
400
401 macro_rules! impl_range {
402 (
403 $range:ty,
404 $value_closure:expr,
405 $value_ty:ty,
406 $fun:ident($fun_closure:expr),
407 $size_hint_closure:expr
408 ) => {
409 impl<'a, A> Arbitrary<'a> for $range
410 where
411 A: Arbitrary<'a> + Clone + PartialOrd,
412 {
413 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
414 let value: $value_ty = Arbitrary::arbitrary(u)?;
415 Ok($fun(value, $fun_closure))
416 }
417
418 #[inline]
419 fn size_hint(depth: usize) -> (usize, Option<usize>) {
420 $size_hint_closure(depth)
421 }
422 }
423 };
424 }
425
426 impl_range!(
427 Range<A>,
428 |r: &Range<A>| (r.start.clone(), r.end.clone()),
429 (A, A),
430 bounded_range(|(a, b)| a..b),
431 |depth| crate::size_hint::and(
432 <A as Arbitrary>::size_hint(depth),
433 <A as Arbitrary>::size_hint(depth)
434 )
435 );
436 impl_range!(
437 RangeFrom<A>,
438 |r: &RangeFrom<A>| r.start.clone(),
439 A,
440 unbounded_range(|a| a..),
441 |depth| <A as Arbitrary>::size_hint(depth)
442 );
443 impl_range!(
444 RangeInclusive<A>,
445 |r: &RangeInclusive<A>| (r.start().clone(), r.end().clone()),
446 (A, A),
447 bounded_range(|(a, b)| a..=b),
448 |depth| crate::size_hint::and(
449 <A as Arbitrary>::size_hint(depth),
450 <A as Arbitrary>::size_hint(depth)
451 )
452 );
453 impl_range!(
454 RangeTo<A>,
455 |r: &RangeTo<A>| r.end.clone(),
456 A,
457 unbounded_range(|b| ..b),
458 |depth| <A as Arbitrary>::size_hint(depth)
459 );
460 impl_range!(
461 RangeToInclusive<A>,
462 |r: &RangeToInclusive<A>| r.end.clone(),
463 A,
464 unbounded_range(|b| ..=b),
465 |depth| <A as Arbitrary>::size_hint(depth)
466 );
467
bounded_range<CB, I, R>(bounds: (I, I), cb: CB) -> R where CB: Fn((I, I)) -> R, I: PartialOrd, R: RangeBounds<I>,468 pub(crate) fn bounded_range<CB, I, R>(bounds: (I, I), cb: CB) -> R
469 where
470 CB: Fn((I, I)) -> R,
471 I: PartialOrd,
472 R: RangeBounds<I>,
473 {
474 let (mut start, mut end) = bounds;
475 if start > end {
476 mem::swap(&mut start, &mut end);
477 }
478 cb((start, end))
479 }
480
unbounded_range<CB, I, R>(bound: I, cb: CB) -> R where CB: Fn(I) -> R, R: RangeBounds<I>,481 pub(crate) fn unbounded_range<CB, I, R>(bound: I, cb: CB) -> R
482 where
483 CB: Fn(I) -> R,
484 R: RangeBounds<I>,
485 {
486 cb(bound)
487 }
488
489 impl<'a> Arbitrary<'a> for Duration {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>490 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
491 Ok(Self::new(
492 <u64 as Arbitrary>::arbitrary(u)?,
493 u.int_in_range(0..=999_999_999)?,
494 ))
495 }
496
497 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)498 fn size_hint(depth: usize) -> (usize, Option<usize>) {
499 crate::size_hint::and(
500 <u64 as Arbitrary>::size_hint(depth),
501 <u32 as Arbitrary>::size_hint(depth),
502 )
503 }
504 }
505
506 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for Option<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>507 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
508 Ok(if <bool as Arbitrary<'a>>::arbitrary(u)? {
509 Some(Arbitrary::arbitrary(u)?)
510 } else {
511 None
512 })
513 }
514
515 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)516 fn size_hint(depth: usize) -> (usize, Option<usize>) {
517 crate::size_hint::and(
518 <bool as Arbitrary>::size_hint(depth),
519 crate::size_hint::or((0, Some(0)), <A as Arbitrary>::size_hint(depth)),
520 )
521 }
522 }
523
524 impl<'a, A: Arbitrary<'a>, B: Arbitrary<'a>> Arbitrary<'a> for std::result::Result<A, B> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>525 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
526 Ok(if <bool as Arbitrary<'a>>::arbitrary(u)? {
527 Ok(<A as Arbitrary>::arbitrary(u)?)
528 } else {
529 Err(<B as Arbitrary>::arbitrary(u)?)
530 })
531 }
532
533 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)534 fn size_hint(depth: usize) -> (usize, Option<usize>) {
535 crate::size_hint::and(
536 <bool as Arbitrary>::size_hint(depth),
537 crate::size_hint::or(
538 <A as Arbitrary>::size_hint(depth),
539 <B as Arbitrary>::size_hint(depth),
540 ),
541 )
542 }
543 }
544
545 macro_rules! arbitrary_tuple {
546 () => {};
547 ($last: ident $($xs: ident)*) => {
548 arbitrary_tuple!($($xs)*);
549
550 impl<'a, $($xs: Arbitrary<'a>,)* $last: Arbitrary<'a>> Arbitrary<'a> for ($($xs,)* $last,) {
551 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
552 Ok(($($xs::arbitrary(u)?,)* Arbitrary::arbitrary(u)?,))
553 }
554
555 #[allow(unused_mut, non_snake_case)]
556 fn arbitrary_take_rest(mut u: Unstructured<'a>) -> Result<Self> {
557 $(let $xs = $xs::arbitrary(&mut u)?;)*
558 let $last = $last::arbitrary_take_rest(u)?;
559 Ok(($($xs,)* $last,))
560 }
561
562 #[inline]
563 fn size_hint(depth: usize) -> (usize, Option<usize>) {
564 crate::size_hint::and_all(&[
565 <$last as Arbitrary>::size_hint(depth),
566 $( <$xs as Arbitrary>::size_hint(depth) ),*
567 ])
568 }
569 }
570 };
571 }
572 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);
573
574 macro_rules! arbitrary_array {
575 {$n:expr, ($t:ident, $a:ident) $(($ts:ident, $as:ident))*} => {
576 arbitrary_array!{($n - 1), $(($ts, $as))*}
577
578 impl<'a, T: Arbitrary<'a>> Arbitrary<'a> for [T; $n] {
579 fn arbitrary(u: &mut Unstructured<'a>) -> Result<[T; $n]> {
580 Ok([
581 Arbitrary::arbitrary(u)?,
582 $(<$ts as Arbitrary>::arbitrary(u)?),*
583 ])
584 }
585
586 #[allow(unused_mut)]
587 fn arbitrary_take_rest(mut u: Unstructured<'a>) -> Result<[T; $n]> {
588 $(let $as = $ts::arbitrary(&mut u)?;)*
589 let last = Arbitrary::arbitrary_take_rest(u)?;
590
591 Ok([
592 $($as,)* last
593 ])
594 }
595
596 #[inline]
597 fn size_hint(depth: usize) -> (usize, Option<usize>) {
598 crate::size_hint::and_all(&[
599 <$t as Arbitrary>::size_hint(depth),
600 $( <$ts as Arbitrary>::size_hint(depth) ),*
601 ])
602 }
603 }
604 };
605 ($n: expr,) => {};
606 }
607
608 impl<'a, T: Arbitrary<'a>> Arbitrary<'a> for [T; 0] {
arbitrary(_: &mut Unstructured<'a>) -> Result<[T; 0]>609 fn arbitrary(_: &mut Unstructured<'a>) -> Result<[T; 0]> {
610 Ok([])
611 }
612
arbitrary_take_rest(_: Unstructured<'a>) -> Result<[T; 0]>613 fn arbitrary_take_rest(_: Unstructured<'a>) -> Result<[T; 0]> {
614 Ok([])
615 }
616
617 #[inline]
size_hint(_: usize) -> (usize, Option<usize>)618 fn size_hint(_: usize) -> (usize, Option<usize>) {
619 crate::size_hint::and_all(&[])
620 }
621 }
622
623 arbitrary_array! { 32, (T, a) (T, b) (T, c) (T, d) (T, e) (T, f) (T, g) (T, h)
624 (T, i) (T, j) (T, k) (T, l) (T, m) (T, n) (T, o) (T, p)
625 (T, q) (T, r) (T, s) (T, u) (T, v) (T, w) (T, x) (T, y)
626 (T, z) (T, aa) (T, ab) (T, ac) (T, ad) (T, ae) (T, af)
627 (T, ag) }
628
629 impl<'a> Arbitrary<'a> for &'a [u8] {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>630 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
631 let len = u.arbitrary_len::<u8>()?;
632 u.bytes(len)
633 }
634
arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self>635 fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
636 Ok(u.take_rest())
637 }
638
639 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)640 fn size_hint(depth: usize) -> (usize, Option<usize>) {
641 <usize as Arbitrary>::size_hint(depth)
642 }
643 }
644
645 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for Vec<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>646 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
647 u.arbitrary_iter()?.collect()
648 }
649
arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self>650 fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
651 u.arbitrary_take_rest_iter()?.collect()
652 }
653
654 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)655 fn size_hint(depth: usize) -> (usize, Option<usize>) {
656 crate::size_hint::and(<usize as Arbitrary>::size_hint(depth), (0, None))
657 }
658 }
659
660 impl<'a, K: Arbitrary<'a> + Ord, V: Arbitrary<'a>> Arbitrary<'a> for BTreeMap<K, V> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>661 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
662 u.arbitrary_iter()?.collect()
663 }
664
arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self>665 fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
666 u.arbitrary_take_rest_iter()?.collect()
667 }
668
669 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)670 fn size_hint(depth: usize) -> (usize, Option<usize>) {
671 crate::size_hint::and(<usize as Arbitrary>::size_hint(depth), (0, None))
672 }
673 }
674
675 impl<'a, A: Arbitrary<'a> + Ord> Arbitrary<'a> for BTreeSet<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>676 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
677 u.arbitrary_iter()?.collect()
678 }
679
arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self>680 fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
681 u.arbitrary_take_rest_iter()?.collect()
682 }
683
684 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)685 fn size_hint(depth: usize) -> (usize, Option<usize>) {
686 crate::size_hint::and(<usize as Arbitrary>::size_hint(depth), (0, None))
687 }
688 }
689
690 impl<'a, A: Arbitrary<'a> + Ord> Arbitrary<'a> for BinaryHeap<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>691 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
692 u.arbitrary_iter()?.collect()
693 }
694
arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self>695 fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
696 u.arbitrary_take_rest_iter()?.collect()
697 }
698
699 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)700 fn size_hint(depth: usize) -> (usize, Option<usize>) {
701 crate::size_hint::and(<usize as Arbitrary>::size_hint(depth), (0, None))
702 }
703 }
704
705 impl<'a, K: Arbitrary<'a> + Eq + ::std::hash::Hash, V: Arbitrary<'a>> Arbitrary<'a>
706 for HashMap<K, V>
707 {
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 crate::size_hint::and(<usize as Arbitrary>::size_hint(depth), (0, None))
719 }
720 }
721
722 impl<'a, A: Arbitrary<'a> + Eq + ::std::hash::Hash> Arbitrary<'a> for HashSet<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>723 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
724 u.arbitrary_iter()?.collect()
725 }
726
arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self>727 fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
728 u.arbitrary_take_rest_iter()?.collect()
729 }
730
731 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)732 fn size_hint(depth: usize) -> (usize, Option<usize>) {
733 crate::size_hint::and(<usize as Arbitrary>::size_hint(depth), (0, None))
734 }
735 }
736
737 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for LinkedList<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>738 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
739 u.arbitrary_iter()?.collect()
740 }
741
arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self>742 fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
743 u.arbitrary_take_rest_iter()?.collect()
744 }
745
746 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)747 fn size_hint(depth: usize) -> (usize, Option<usize>) {
748 crate::size_hint::and(<usize as Arbitrary>::size_hint(depth), (0, None))
749 }
750 }
751
752 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for VecDeque<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>753 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
754 u.arbitrary_iter()?.collect()
755 }
756
arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self>757 fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
758 u.arbitrary_take_rest_iter()?.collect()
759 }
760
761 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)762 fn size_hint(depth: usize) -> (usize, Option<usize>) {
763 crate::size_hint::and(<usize as Arbitrary>::size_hint(depth), (0, None))
764 }
765 }
766
767 impl<'a, A> Arbitrary<'a> for Cow<'a, A>
768 where
769 A: ToOwned + ?Sized,
770 <A as ToOwned>::Owned: Arbitrary<'a>,
771 {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>772 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
773 Arbitrary::arbitrary(u).map(Cow::Owned)
774 }
775
776 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)777 fn size_hint(depth: usize) -> (usize, Option<usize>) {
778 crate::size_hint::recursion_guard(depth, |depth| {
779 <<A as ToOwned>::Owned as Arbitrary>::size_hint(depth)
780 })
781 }
782 }
783
784 impl<'a> Arbitrary<'a> for &'a str {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>785 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
786 let size = u.arbitrary_len::<u8>()?;
787 match str::from_utf8(&u.peek_bytes(size).unwrap()) {
788 Ok(s) => {
789 u.bytes(size).unwrap();
790 Ok(s)
791 }
792 Err(e) => {
793 let i = e.valid_up_to();
794 let valid = u.bytes(i).unwrap();
795 let s = unsafe {
796 debug_assert!(str::from_utf8(valid).is_ok());
797 str::from_utf8_unchecked(valid)
798 };
799 Ok(s)
800 }
801 }
802 }
803
arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self>804 fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
805 let bytes = u.take_rest();
806 str::from_utf8(bytes)
807 .map_err(|_| Error::IncorrectFormat)
808 .map(Into::into)
809 }
810
811 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)812 fn size_hint(depth: usize) -> (usize, Option<usize>) {
813 crate::size_hint::and(<usize as Arbitrary>::size_hint(depth), (0, None))
814 }
815 }
816
817 impl<'a> Arbitrary<'a> for String {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>818 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
819 <&str as Arbitrary>::arbitrary(u).map(Into::into)
820 }
821
arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self>822 fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
823 <&str as Arbitrary>::arbitrary_take_rest(u).map(Into::into)
824 }
825
826 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)827 fn size_hint(depth: usize) -> (usize, Option<usize>) {
828 <&str as Arbitrary>::size_hint(depth)
829 }
830 }
831
832 impl<'a> Arbitrary<'a> for CString {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>833 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
834 <Vec<u8> as Arbitrary>::arbitrary(u).map(|mut x| {
835 x.retain(|&c| c != 0);
836 Self::new(x).unwrap()
837 })
838 }
839
840 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)841 fn size_hint(depth: usize) -> (usize, Option<usize>) {
842 <Vec<u8> as Arbitrary>::size_hint(depth)
843 }
844 }
845
846 impl<'a> Arbitrary<'a> for OsString {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>847 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
848 <String as Arbitrary>::arbitrary(u).map(From::from)
849 }
850
851 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)852 fn size_hint(depth: usize) -> (usize, Option<usize>) {
853 <String as Arbitrary>::size_hint(depth)
854 }
855 }
856
857 impl<'a> Arbitrary<'a> for PathBuf {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>858 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
859 <OsString as Arbitrary>::arbitrary(u).map(From::from)
860 }
861
862 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)863 fn size_hint(depth: usize) -> (usize, Option<usize>) {
864 <OsString as Arbitrary>::size_hint(depth)
865 }
866 }
867
868 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for Box<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>869 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
870 Arbitrary::arbitrary(u).map(Self::new)
871 }
872
873 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)874 fn size_hint(depth: usize) -> (usize, Option<usize>) {
875 crate::size_hint::recursion_guard(depth, |depth| <A as Arbitrary>::size_hint(depth))
876 }
877 }
878
879 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for Box<[A]> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>880 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
881 <Vec<A> as Arbitrary>::arbitrary(u).map(|x| x.into_boxed_slice())
882 }
883
884 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)885 fn size_hint(depth: usize) -> (usize, Option<usize>) {
886 <Vec<A> as Arbitrary>::size_hint(depth)
887 }
888 }
889
890 impl<'a> Arbitrary<'a> for Box<str> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>891 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
892 <String as Arbitrary>::arbitrary(u).map(|x| x.into_boxed_str())
893 }
894
895 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)896 fn size_hint(depth: usize) -> (usize, Option<usize>) {
897 <String as Arbitrary>::size_hint(depth)
898 }
899 }
900
901 // impl Arbitrary for Box<CStr> {
902 // fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> {
903 // <CString as Arbitrary>::arbitrary(u).map(|x| x.into_boxed_c_str())
904 // }
905 // }
906
907 // impl Arbitrary for Box<OsStr> {
908 // fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> {
909 // <OsString as Arbitrary>::arbitrary(u).map(|x| x.into_boxed_osstr())
910 //
911 // }
912 // }
913
914 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for Arc<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>915 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
916 Arbitrary::arbitrary(u).map(Self::new)
917 }
918
919 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)920 fn size_hint(depth: usize) -> (usize, Option<usize>) {
921 crate::size_hint::recursion_guard(depth, |depth| <A as Arbitrary>::size_hint(depth))
922 }
923 }
924
925 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for Rc<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>926 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
927 Arbitrary::arbitrary(u).map(Self::new)
928 }
929
930 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)931 fn size_hint(depth: usize) -> (usize, Option<usize>) {
932 crate::size_hint::recursion_guard(depth, |depth| <A as Arbitrary>::size_hint(depth))
933 }
934 }
935
936 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for Cell<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>937 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
938 Arbitrary::arbitrary(u).map(Self::new)
939 }
940
941 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)942 fn size_hint(depth: usize) -> (usize, Option<usize>) {
943 <A as Arbitrary<'a>>::size_hint(depth)
944 }
945 }
946
947 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for RefCell<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>948 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
949 Arbitrary::arbitrary(u).map(Self::new)
950 }
951
952 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)953 fn size_hint(depth: usize) -> (usize, Option<usize>) {
954 <A as Arbitrary<'a>>::size_hint(depth)
955 }
956 }
957
958 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for UnsafeCell<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>959 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
960 Arbitrary::arbitrary(u).map(Self::new)
961 }
962
963 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)964 fn size_hint(depth: usize) -> (usize, Option<usize>) {
965 <A as Arbitrary<'a>>::size_hint(depth)
966 }
967 }
968
969 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for Mutex<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>970 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
971 Arbitrary::arbitrary(u).map(Self::new)
972 }
973
974 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)975 fn size_hint(depth: usize) -> (usize, Option<usize>) {
976 <A as Arbitrary<'a>>::size_hint(depth)
977 }
978 }
979
980 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for iter::Empty<A> {
arbitrary(_: &mut Unstructured<'a>) -> Result<Self>981 fn arbitrary(_: &mut Unstructured<'a>) -> Result<Self> {
982 Ok(iter::empty())
983 }
984
985 #[inline]
size_hint(_depth: usize) -> (usize, Option<usize>)986 fn size_hint(_depth: usize) -> (usize, Option<usize>) {
987 (0, Some(0))
988 }
989 }
990
991 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for ::std::marker::PhantomData<A> {
arbitrary(_: &mut Unstructured<'a>) -> Result<Self>992 fn arbitrary(_: &mut Unstructured<'a>) -> Result<Self> {
993 Ok(::std::marker::PhantomData)
994 }
995
996 #[inline]
size_hint(_depth: usize) -> (usize, Option<usize>)997 fn size_hint(_depth: usize) -> (usize, Option<usize>) {
998 (0, Some(0))
999 }
1000 }
1001
1002 impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for ::std::num::Wrapping<A> {
arbitrary(u: &mut Unstructured<'a>) -> Result<Self>1003 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
1004 Arbitrary::arbitrary(u).map(::std::num::Wrapping)
1005 }
1006
1007 #[inline]
size_hint(depth: usize) -> (usize, Option<usize>)1008 fn size_hint(depth: usize) -> (usize, Option<usize>) {
1009 <A as Arbitrary<'a>>::size_hint(depth)
1010 }
1011 }
1012
1013 #[cfg(test)]
1014 mod test {
1015 use super::*;
1016
1017 #[test]
finite_buffer_fill_buffer()1018 fn finite_buffer_fill_buffer() {
1019 let x = [1, 2, 3, 4];
1020 let mut rb = Unstructured::new(&x);
1021 let mut z = [0; 2];
1022 rb.fill_buffer(&mut z).unwrap();
1023 assert_eq!(z, [1, 2]);
1024 rb.fill_buffer(&mut z).unwrap();
1025 assert_eq!(z, [3, 4]);
1026 rb.fill_buffer(&mut z).unwrap();
1027 assert_eq!(z, [0, 0]);
1028 }
1029
1030 #[test]
arbitrary_for_integers()1031 fn arbitrary_for_integers() {
1032 let x = [1, 2, 3, 4];
1033 let mut buf = Unstructured::new(&x);
1034 let expected = 1 | (2 << 8) | (3 << 16) | (4 << 24);
1035 let actual = i32::arbitrary(&mut buf).unwrap();
1036 assert_eq!(expected, actual);
1037 }
1038
1039 #[test]
arbitrary_for_bytes()1040 fn arbitrary_for_bytes() {
1041 let x = [1, 2, 3, 4, 4];
1042 let mut buf = Unstructured::new(&x);
1043 let expected = &[1, 2, 3, 4];
1044 let actual = <&[u8] as Arbitrary>::arbitrary(&mut buf).unwrap();
1045 assert_eq!(expected, actual);
1046 }
1047
1048 #[test]
arbitrary_take_rest_for_bytes()1049 fn arbitrary_take_rest_for_bytes() {
1050 let x = [1, 2, 3, 4];
1051 let buf = Unstructured::new(&x);
1052 let expected = &[1, 2, 3, 4];
1053 let actual = <&[u8] as Arbitrary>::arbitrary_take_rest(buf).unwrap();
1054 assert_eq!(expected, actual);
1055 }
1056
1057 #[test]
arbitrary_collection()1058 fn arbitrary_collection() {
1059 let x = [
1060 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,
1061 ];
1062 assert_eq!(
1063 Vec::<u8>::arbitrary(&mut Unstructured::new(&x)).unwrap(),
1064 &[2, 4, 6, 8, 1]
1065 );
1066 assert_eq!(
1067 Vec::<u32>::arbitrary(&mut Unstructured::new(&x)).unwrap(),
1068 &[84148994]
1069 );
1070 assert_eq!(
1071 String::arbitrary(&mut Unstructured::new(&x)).unwrap(),
1072 "\x01\x02\x03\x04\x05\x06\x07\x08"
1073 );
1074 }
1075
1076 #[test]
arbitrary_take_rest()1077 fn arbitrary_take_rest() {
1078 let x = [1, 2, 3, 4];
1079 assert_eq!(
1080 Vec::<u8>::arbitrary_take_rest(Unstructured::new(&x)).unwrap(),
1081 &[1, 2, 3, 4]
1082 );
1083 assert_eq!(
1084 Vec::<u32>::arbitrary_take_rest(Unstructured::new(&x)).unwrap(),
1085 &[0x4030201]
1086 );
1087 assert_eq!(
1088 String::arbitrary_take_rest(Unstructured::new(&x)).unwrap(),
1089 "\x01\x02\x03\x04"
1090 );
1091 }
1092
1093 #[test]
size_hint_for_tuples()1094 fn size_hint_for_tuples() {
1095 assert_eq!(
1096 (7, Some(7)),
1097 <(bool, u16, i32) as Arbitrary<'_>>::size_hint(0)
1098 );
1099 assert_eq!(
1100 (1 + mem::size_of::<usize>(), None),
1101 <(u8, Vec<u8>) as Arbitrary>::size_hint(0)
1102 );
1103 }
1104 }
1105