Coverage Report

Created: 2025-07-01 06:46

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