Coverage Report

Created: 2026-10-17 06:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/arbitrary-1.1.0/src/unstructured.rs
Line
Count
Source
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
//! Wrappers around raw, unstructured bytes.
10
11
use crate::{Arbitrary, Error, Result};
12
use std::marker::PhantomData;
13
use std::ops::ControlFlow;
14
use std::{mem, ops};
15
16
/// A source of unstructured data.
17
///
18
/// An `Unstructured` helps `Arbitrary` implementations interpret raw data
19
/// (typically provided by a fuzzer) as a "DNA string" that describes how to
20
/// construct the `Arbitrary` type. The goal is that a small change to the "DNA
21
/// string" (the raw data wrapped by an `Unstructured`) results in a small
22
/// change to the generated `Arbitrary` instance. This helps a fuzzer
23
/// efficiently explore the `Arbitrary`'s input space.
24
///
25
/// `Unstructured` is deterministic: given the same raw data, the same series of
26
/// API calls will return the same results (modulo system resource constraints,
27
/// like running out of memory). However, `Unstructured` does not guarantee
28
/// anything beyond that: it makes not guarantee that it will yield bytes from
29
/// the underlying data in any particular order.
30
///
31
/// You shouldn't generally need to use an `Unstructured` unless you are writing
32
/// a custom `Arbitrary` implementation by hand, instead of deriving it. Mostly,
33
/// you should just be passing it through to nested `Arbitrary::arbitrary`
34
/// calls.
35
///
36
/// # Example
37
///
38
/// Imagine you were writing a color conversion crate. You might want to write
39
/// fuzz tests that take a random RGB color and assert various properties, run
40
/// functions and make sure nothing panics, etc.
41
///
42
/// Below is what translating the fuzzer's raw input into an `Unstructured` and
43
/// using that to generate an arbitrary RGB color might look like:
44
///
45
/// ```
46
/// # #[cfg(feature = "derive")] fn foo() {
47
/// use arbitrary::{Arbitrary, Unstructured};
48
///
49
/// /// An RGB color.
50
/// #[derive(Arbitrary)]
51
/// pub struct Rgb {
52
///     r: u8,
53
///     g: u8,
54
///     b: u8,
55
/// }
56
///
57
/// // Get the raw bytes from the fuzzer.
58
/// #   let get_input_from_fuzzer = || &[];
59
/// let raw_data: &[u8] = get_input_from_fuzzer();
60
///
61
/// // Wrap it in an `Unstructured`.
62
/// let mut unstructured = Unstructured::new(raw_data);
63
///
64
/// // Generate an `Rgb` color and run our checks.
65
/// if let Ok(rgb) = Rgb::arbitrary(&mut unstructured) {
66
/// #   let run_my_color_conversion_checks = |_| {};
67
///     run_my_color_conversion_checks(rgb);
68
/// }
69
/// # }
70
/// ```
71
pub struct Unstructured<'a> {
72
    data: &'a [u8],
73
}
74
75
impl<'a> Unstructured<'a> {
76
    /// Create a new `Unstructured` from the given raw data.
77
    ///
78
    /// # Example
79
    ///
80
    /// ```
81
    /// use arbitrary::Unstructured;
82
    ///
83
    /// let u = Unstructured::new(&[1, 2, 3, 4]);
84
    /// ```
85
0
    pub fn new(data: &'a [u8]) -> Self {
86
0
        Unstructured { data }
87
0
    }
88
89
    /// Get the number of remaining bytes of underlying data that are still
90
    /// available.
91
    ///
92
    /// # Example
93
    ///
94
    /// ```
95
    /// use arbitrary::{Arbitrary, Unstructured};
96
    ///
97
    /// let mut u = Unstructured::new(&[1, 2, 3]);
98
    ///
99
    /// // Initially have three bytes of data.
100
    /// assert_eq!(u.len(), 3);
101
    ///
102
    /// // Generating a `bool` consumes one byte from the underlying data, so
103
    /// // we are left with two bytes afterwards.
104
    /// let _ = bool::arbitrary(&mut u);
105
    /// assert_eq!(u.len(), 2);
106
    /// ```
107
    #[inline]
108
0
    pub fn len(&self) -> usize {
109
0
        self.data.len()
110
0
    }
111
112
    /// Is the underlying unstructured data exhausted?
113
    ///
114
    /// `unstructured.is_empty()` is the same as `unstructured.len() == 0`.
115
    ///
116
    /// # Example
117
    ///
118
    /// ```
119
    /// use arbitrary::{Arbitrary, Unstructured};
120
    ///
121
    /// let mut u = Unstructured::new(&[1, 2, 3, 4]);
122
    ///
123
    /// // Initially, we are not empty.
124
    /// assert!(!u.is_empty());
125
    ///
126
    /// // Generating a `u32` consumes all four bytes of the underlying data, so
127
    /// // we become empty afterwards.
128
    /// let _ = u32::arbitrary(&mut u);
129
    /// assert!(u.is_empty());
130
    /// ```
131
    #[inline]
132
0
    pub fn is_empty(&self) -> bool {
133
0
        self.len() == 0
134
0
    }
135
136
    /// Generate an arbitrary instance of `A`.
137
    ///
138
    /// This is simply a helper method that is equivalent to `<A as
139
    /// Arbitrary>::arbitrary(self)`. This helper is a little bit more concise,
140
    /// and can be used in situations where Rust's type inference will figure
141
    /// out what `A` should be.
142
    ///
143
    /// # Example
144
    ///
145
    /// ```
146
    /// # #[cfg(feature="derive")] fn foo() -> arbitrary::Result<()> {
147
    /// use arbitrary::{Arbitrary, Unstructured};
148
    ///
149
    /// #[derive(Arbitrary)]
150
    /// struct MyType {
151
    ///     // ...
152
    /// }
153
    ///
154
    /// fn do_stuff(value: MyType) {
155
    /// #   let _ = value;
156
    ///     // ...
157
    /// }
158
    ///
159
    /// let mut u = Unstructured::new(&[1, 2, 3, 4]);
160
    ///
161
    /// // Rust's type inference can figure out that `value` should be of type
162
    /// // `MyType` here:
163
    /// let value = u.arbitrary()?;
164
    /// do_stuff(value);
165
    /// # Ok(()) }
166
    /// ```
167
0
    pub fn arbitrary<A>(&mut self) -> Result<A>
168
0
    where
169
0
        A: Arbitrary<'a>,
170
0
    {
171
0
        <A as Arbitrary<'a>>::arbitrary(self)
172
0
    }
173
174
    /// Get the number of elements to insert when building up a collection of
175
    /// arbitrary `ElementType`s.
176
    ///
177
    /// This uses the [`<ElementType as
178
    /// Arbitrary>::size_hint`][crate::Arbitrary::size_hint] method to smartly
179
    /// choose a length such that we most likely have enough underlying bytes to
180
    /// construct that many arbitrary `ElementType`s.
181
    ///
182
    /// This should only be called within an `Arbitrary` implementation.
183
    ///
184
    /// # Example
185
    ///
186
    /// ```
187
    /// use arbitrary::{Arbitrary, Result, Unstructured};
188
    /// # pub struct MyCollection<T> { _t: std::marker::PhantomData<T> }
189
    /// # impl<T> MyCollection<T> {
190
    /// #     pub fn with_capacity(capacity: usize) -> Self { MyCollection { _t: std::marker::PhantomData } }
191
    /// #     pub fn insert(&mut self, element: T) {}
192
    /// # }
193
    ///
194
    /// impl<'a, T> Arbitrary<'a> for MyCollection<T>
195
    /// where
196
    ///     T: Arbitrary<'a>,
197
    /// {
198
    ///     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
199
    ///         // Get the number of `T`s we should insert into our collection.
200
    ///         let len = u.arbitrary_len::<T>()?;
201
    ///
202
    ///         // And then create a collection of that length!
203
    ///         let mut my_collection = MyCollection::with_capacity(len);
204
    ///         for _ in 0..len {
205
    ///             let element = T::arbitrary(u)?;
206
    ///             my_collection.insert(element);
207
    ///         }
208
    ///
209
    ///         Ok(my_collection)
210
    ///     }
211
    /// }
212
    /// ```
213
0
    pub fn arbitrary_len<ElementType>(&mut self) -> Result<usize>
214
0
    where
215
0
        ElementType: Arbitrary<'a>,
216
0
    {
217
0
        let byte_size = self.arbitrary_byte_size()?;
218
0
        let (lower, upper) = <ElementType as Arbitrary>::size_hint(0);
219
0
        let elem_size = upper.unwrap_or_else(|| lower * 2);
220
0
        let elem_size = std::cmp::max(1, elem_size);
221
0
        Ok(byte_size / elem_size)
222
0
    }
223
224
0
    fn arbitrary_byte_size(&mut self) -> Result<usize> {
225
0
        if self.data.is_empty() {
226
0
            Ok(0)
227
0
        } else if self.data.len() == 1 {
228
0
            self.data = &[];
229
0
            Ok(0)
230
        } else {
231
            // Take lengths from the end of the data, since the `libFuzzer` folks
232
            // found that this lets fuzzers more efficiently explore the input
233
            // space.
234
            //
235
            // https://github.com/rust-fuzz/libfuzzer-sys/blob/0c450753/libfuzzer/utils/FuzzedDataProvider.h#L92-L97
236
237
            // We only consume as many bytes as necessary to cover the entire
238
            // range of the byte string.
239
0
            let len = if self.data.len() <= std::u8::MAX as usize + 1 {
240
0
                let bytes = 1;
241
0
                let max_size = self.data.len() - bytes;
242
0
                let (rest, for_size) = self.data.split_at(max_size);
243
0
                self.data = rest;
244
0
                Self::int_in_range_impl(0..=max_size as u8, for_size.iter().copied())?.0 as usize
245
0
            } else if self.data.len() <= std::u16::MAX as usize + 1 {
246
0
                let bytes = 2;
247
0
                let max_size = self.data.len() - bytes;
248
0
                let (rest, for_size) = self.data.split_at(max_size);
249
0
                self.data = rest;
250
0
                Self::int_in_range_impl(0..=max_size as u16, for_size.iter().copied())?.0 as usize
251
0
            } else if self.data.len() <= std::u32::MAX as usize + 1 {
252
0
                let bytes = 4;
253
0
                let max_size = self.data.len() - bytes;
254
0
                let (rest, for_size) = self.data.split_at(max_size);
255
0
                self.data = rest;
256
0
                Self::int_in_range_impl(0..=max_size as u32, for_size.iter().copied())?.0 as usize
257
            } else {
258
0
                let bytes = 8;
259
0
                let max_size = self.data.len() - bytes;
260
0
                let (rest, for_size) = self.data.split_at(max_size);
261
0
                self.data = rest;
262
0
                Self::int_in_range_impl(0..=max_size as u64, for_size.iter().copied())?.0 as usize
263
            };
264
265
0
            Ok(len)
266
        }
267
0
    }
268
269
    /// Generate an integer within the given range.
270
    ///
271
    /// Do not use this to generate the size of a collection. Use
272
    /// `arbitrary_len` instead.
273
    ///
274
    /// # Panics
275
    ///
276
    /// Panics if `range.start >= range.end`. That is, the given range must be
277
    /// non-empty.
278
    ///
279
    /// # Example
280
    ///
281
    /// ```
282
    /// use arbitrary::{Arbitrary, Unstructured};
283
    ///
284
    /// let mut u = Unstructured::new(&[1, 2, 3, 4]);
285
    ///
286
    /// let x: i32 = u.int_in_range(-5_000..=-1_000)
287
    ///     .expect("constructed `u` with enough bytes to generate an `i32`");
288
    ///
289
    /// assert!(-5_000 <= x);
290
    /// assert!(x <= -1_000);
291
    /// ```
292
0
    pub fn int_in_range<T>(&mut self, range: ops::RangeInclusive<T>) -> Result<T>
293
0
    where
294
0
        T: Int,
295
0
    {
296
0
        let (result, bytes_consumed) = Self::int_in_range_impl(range, self.data.iter().cloned())?;
297
0
        self.data = &self.data[bytes_consumed..];
298
0
        Ok(result)
299
0
    }
300
301
0
    fn int_in_range_impl<T>(
302
0
        range: ops::RangeInclusive<T>,
303
0
        mut bytes: impl Iterator<Item = u8>,
304
0
    ) -> Result<(T, usize)>
305
0
    where
306
0
        T: Int,
307
0
    {
308
0
        let start = range.start();
309
0
        let end = range.end();
310
0
        assert!(
311
0
            start <= end,
312
0
            "`arbitrary::Unstructured::int_in_range` requires a non-empty range"
313
0
        );
314
315
        // When there is only one possible choice, don't waste any entropy from
316
        // the underlying data.
317
0
        if start == end {
318
0
            return Ok((*start, 0));
319
0
        }
320
0
321
0
        let range: T::Widest = end.as_widest() - start.as_widest();
322
0
        let mut result = T::Widest::ZERO;
323
0
        let mut offset: usize = 0;
324
325
0
        while offset < mem::size_of::<T>()
326
0
            && (range >> T::Widest::from_usize(offset * 8)) > T::Widest::ZERO
327
        {
328
0
            let byte = bytes.next().ok_or(Error::NotEnoughData)?;
329
0
            result = (result << 8) | T::Widest::from_u8(byte);
330
0
            offset += 1;
331
        }
332
333
        // Avoid division by zero.
334
0
        if let Some(range) = range.checked_add(T::Widest::ONE) {
335
0
            result = result % range;
336
0
        }
337
338
0
        Ok((
339
0
            T::from_widest(start.as_widest().wrapping_add(result)),
340
0
            offset,
341
0
        ))
342
0
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::int_in_range_impl::<u8, core::iter::adapters::copied::Copied<core::slice::iter::Iter<u8>>>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::int_in_range_impl::<u32, core::iter::adapters::cloned::Cloned<core::slice::iter::Iter<u8>>>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::int_in_range_impl::<u32, core::iter::adapters::copied::Copied<core::slice::iter::Iter<u8>>>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::int_in_range_impl::<u16, core::iter::adapters::copied::Copied<core::slice::iter::Iter<u8>>>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::int_in_range_impl::<u64, core::iter::adapters::copied::Copied<core::slice::iter::Iter<u8>>>
343
344
    /// Choose one of the given choices.
345
    ///
346
    /// This should only be used inside of `Arbitrary` implementations.
347
    ///
348
    /// Returns an error if there is not enough underlying data to make a
349
    /// choice or if no choices are provided.
350
    ///
351
    /// # Examples
352
    ///
353
    /// Selecting from an array of choices:
354
    ///
355
    /// ```
356
    /// use arbitrary::Unstructured;
357
    ///
358
    /// let mut u = Unstructured::new(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]);
359
    /// let choices = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
360
    ///
361
    /// let choice = u.choose(&choices).unwrap();
362
    ///
363
    /// println!("chose {}", choice);
364
    /// ```
365
    ///
366
    /// An error is returned if no choices are provided:
367
    ///
368
    /// ```
369
    /// use arbitrary::Unstructured;
370
    ///
371
    /// let mut u = Unstructured::new(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]);
372
    /// let choices: [char; 0] = [];
373
    ///
374
    /// let result = u.choose(&choices);
375
    ///
376
    /// assert!(result.is_err());
377
    /// ```
378
0
    pub fn choose<'b, T>(&mut self, choices: &'b [T]) -> Result<&'b T> {
379
0
        if choices.is_empty() {
380
0
            return Err(Error::EmptyChoose);
381
0
        }
382
0
        let idx = self.int_in_range(0..=choices.len() - 1)?;
383
0
        Ok(&choices[idx])
384
0
    }
385
386
    /// Generate a boolean according to the given ratio.
387
    ///
388
    /// # Panics
389
    ///
390
    /// Panics when the numerator and denominator do not meet these constraints:
391
    ///
392
    /// * `0 < numerator <= denominator`
393
    ///
394
    /// # Example
395
    ///
396
    /// Generate a boolean that is `true` five sevenths of the time:
397
    ///
398
    /// ```
399
    /// # fn foo() -> arbitrary::Result<()> {
400
    /// use arbitrary::Unstructured;
401
    ///
402
    /// # let my_data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
403
    /// let mut u = Unstructured::new(&my_data);
404
    ///
405
    /// if u.ratio(5, 7)? {
406
    ///     // Take this branch 5/7 of the time.
407
    /// }
408
    /// # Ok(())
409
    /// # }
410
    /// ```
411
0
    pub fn ratio<T>(&mut self, numerator: T, denominator: T) -> Result<bool>
412
0
    where
413
0
        T: Int,
414
0
    {
415
0
        assert!(T::ZERO < numerator);
416
0
        assert!(numerator <= denominator);
417
0
        let x = self.int_in_range(T::ONE..=denominator)?;
418
0
        Ok(x <= numerator)
419
0
    }
420
421
    /// Fill a `buffer` with bytes from the underlying raw data.
422
    ///
423
    /// This should only be called within an `Arbitrary` implementation. This is
424
    /// a very low-level operation. You should generally prefer calling nested
425
    /// `Arbitrary` implementations like `<Vec<u8>>::arbitrary` and
426
    /// `String::arbitrary` over using this method directly.
427
    ///
428
    /// If this `Unstructured` does not have enough underlying data to fill the
429
    /// whole `buffer`, it pads the buffer out with zeros.
430
    ///
431
    /// # Example
432
    ///
433
    /// ```
434
    /// use arbitrary::Unstructured;
435
    ///
436
    /// let mut u = Unstructured::new(&[1, 2, 3, 4]);
437
    ///
438
    /// let mut buf = [0; 2];
439
    ///
440
    /// assert!(u.fill_buffer(&mut buf).is_ok());
441
    /// assert_eq!(buf, [1, 2]);
442
    ///
443
    /// assert!(u.fill_buffer(&mut buf).is_ok());
444
    /// assert_eq!(buf, [3, 4]);
445
    ///
446
    /// assert!(u.fill_buffer(&mut buf).is_ok());
447
    /// assert_eq!(buf, [0, 0]);
448
    /// ```
449
0
    pub fn fill_buffer(&mut self, buffer: &mut [u8]) -> Result<()> {
450
0
        let n = std::cmp::min(buffer.len(), self.data.len());
451
0
        buffer[..n].copy_from_slice(&self.data[..n]);
452
0
        for byte in buffer[n..].iter_mut() {
453
0
            *byte = 0;
454
0
        }
455
0
        self.data = &self.data[n..];
456
0
        Ok(())
457
0
    }
458
459
    /// Provide `size` bytes from the underlying raw data.
460
    ///
461
    /// This should only be called within an `Arbitrary` implementation. This is
462
    /// a very low-level operation. You should generally prefer calling nested
463
    /// `Arbitrary` implementations like `<Vec<u8>>::arbitrary` and
464
    /// `String::arbitrary` over using this method directly.
465
    ///
466
    /// # Example
467
    ///
468
    /// ```
469
    /// use arbitrary::Unstructured;
470
    ///
471
    /// let mut u = Unstructured::new(&[1, 2, 3, 4]);
472
    ///
473
    /// assert!(u.bytes(2).unwrap() == &[1, 2]);
474
    /// assert!(u.bytes(2).unwrap() == &[3, 4]);
475
    /// ```
476
0
    pub fn bytes(&mut self, size: usize) -> Result<&'a [u8]> {
477
0
        if self.data.len() < size {
478
0
            return Err(Error::NotEnoughData);
479
0
        }
480
0
481
0
        let (for_buf, rest) = self.data.split_at(size);
482
0
        self.data = rest;
483
0
        Ok(for_buf)
484
0
    }
485
486
    /// Peek at `size` number of bytes of the underlying raw input.
487
    ///
488
    /// Does not consume the bytes, only peeks at them.
489
    ///
490
    /// Returns `None` if there are not `size` bytes left in the underlying raw
491
    /// input.
492
    ///
493
    /// # Example
494
    ///
495
    /// ```
496
    /// use arbitrary::Unstructured;
497
    ///
498
    /// let u = Unstructured::new(&[1, 2, 3]);
499
    ///
500
    /// assert_eq!(u.peek_bytes(0).unwrap(), []);
501
    /// assert_eq!(u.peek_bytes(1).unwrap(), [1]);
502
    /// assert_eq!(u.peek_bytes(2).unwrap(), [1, 2]);
503
    /// assert_eq!(u.peek_bytes(3).unwrap(), [1, 2, 3]);
504
    ///
505
    /// assert!(u.peek_bytes(4).is_none());
506
    /// ```
507
0
    pub fn peek_bytes(&self, size: usize) -> Option<&'a [u8]> {
508
0
        self.data.get(..size)
509
0
    }
510
511
    /// Consume all of the rest of the remaining underlying bytes.
512
    ///
513
    /// Returns a slice of all the remaining, unconsumed bytes.
514
    ///
515
    /// # Example
516
    ///
517
    /// ```
518
    /// use arbitrary::Unstructured;
519
    ///
520
    /// let mut u = Unstructured::new(&[1, 2, 3]);
521
    ///
522
    /// let mut remaining = u.take_rest();
523
    ///
524
    /// assert_eq!(remaining, [1, 2, 3]);
525
    /// ```
526
0
    pub fn take_rest(mut self) -> &'a [u8] {
527
0
        mem::replace(&mut self.data, &[])
528
0
    }
529
530
    /// Provide an iterator over elements for constructing a collection
531
    ///
532
    /// This is useful for implementing [`Arbitrary::arbitrary`] on collections
533
    /// since the implementation is simply `u.arbitrary_iter()?.collect()`
534
0
    pub fn arbitrary_iter<'b, ElementType: Arbitrary<'a>>(
535
0
        &'b mut self,
536
0
    ) -> Result<ArbitraryIter<'a, 'b, ElementType>> {
537
0
        Ok(ArbitraryIter {
538
0
            u: &mut *self,
539
0
            _marker: PhantomData,
540
0
        })
541
0
    }
542
543
    /// Provide an iterator over elements for constructing a collection from
544
    /// all the remaining bytes.
545
    ///
546
    /// This is useful for implementing [`Arbitrary::arbitrary_take_rest`] on collections
547
    /// since the implementation is simply `u.arbitrary_take_rest_iter()?.collect()`
548
0
    pub fn arbitrary_take_rest_iter<ElementType: Arbitrary<'a>>(
549
0
        self,
550
0
    ) -> Result<ArbitraryTakeRestIter<'a, ElementType>> {
551
0
        let (lower, upper) = ElementType::size_hint(0);
552
0
553
0
        let elem_size = upper.unwrap_or(lower * 2);
554
0
        let elem_size = std::cmp::max(1, elem_size);
555
0
        let size = self.len() / elem_size;
556
0
        Ok(ArbitraryTakeRestIter {
557
0
            size,
558
0
            u: Some(self),
559
0
            _marker: PhantomData,
560
0
        })
561
0
    }
562
563
    /// Call the given function an arbitrary number of times.
564
    ///
565
    /// The function is given this `Unstructured` so that it can continue to
566
    /// generate arbitrary data and structures.
567
    ///
568
    /// You may optionaly specify minimum and maximum bounds on the number of
569
    /// times the function is called.
570
    ///
571
    /// You may break out of the loop early by returning
572
    /// `Ok(std::ops::ControlFlow::Break)`. To continue the loop, return
573
    /// `Ok(std::ops::ControlFlow::Continue)`.
574
    ///
575
    /// # Panics
576
    ///
577
    /// Panics if `min > max`.
578
    ///
579
    /// # Example
580
    ///
581
    /// Call a closure that generates an arbitrary type inside a context an
582
    /// arbitrary number of times:
583
    ///
584
    /// ```
585
    /// use arbitrary::{Result, Unstructured};
586
    /// use std::ops::ControlFlow;
587
    ///
588
    /// enum Type {
589
    ///     /// A boolean type.
590
    ///     Bool,
591
    ///
592
    ///     /// An integer type.
593
    ///     Int,
594
    ///
595
    ///     /// A list of the `i`th type in this type's context.
596
    ///     List(usize),
597
    /// }
598
    ///
599
    /// fn arbitrary_types_context(u: &mut Unstructured) -> Result<Vec<Type>> {
600
    ///     let mut context = vec![];
601
    ///
602
    ///     u.arbitrary_loop(Some(10), Some(20), |u| {
603
    ///         let num_choices = if context.is_empty() {
604
    ///             2
605
    ///         } else {
606
    ///             3
607
    ///         };
608
    ///         let ty = match u.int_in_range::<u8>(1..=num_choices)? {
609
    ///             1 => Type::Bool,
610
    ///             2 => Type::Int,
611
    ///             3 => Type::List(u.int_in_range(0..=context.len() - 1)?),
612
    ///             _ => unreachable!(),
613
    ///         };
614
    ///         context.push(ty);
615
    ///         Ok(ControlFlow::Continue(()))
616
    ///     })?;
617
    ///
618
    ///     // The number of loop iterations are constrained by the min/max
619
    ///     // bounds that we provided.
620
    ///     assert!(context.len() >= 10);
621
    ///     assert!(context.len() <= 20);
622
    ///
623
    ///     Ok(context)
624
    /// }
625
    /// ```
626
0
    pub fn arbitrary_loop(
627
0
        &mut self,
628
0
        min: Option<u32>,
629
0
        max: Option<u32>,
630
0
        mut f: impl FnMut(&mut Self) -> Result<ControlFlow<(), ()>>,
631
0
    ) -> Result<()> {
632
0
        let min = min.unwrap_or(0);
633
0
        let max = max.unwrap_or(u32::MAX);
634
0
        assert!(min <= max);
635
636
0
        for _ in 0..min {
637
0
            match f(self)? {
638
0
                ControlFlow::Continue(_) => continue,
639
0
                ControlFlow::Break(_) => return Ok(()),
640
            }
641
        }
642
643
0
        for _ in 0..(max - min) {
644
0
            let keep_going = self.arbitrary().unwrap_or(false);
645
0
            if !keep_going {
646
0
                break;
647
0
            }
648
0
            match f(self)? {
649
0
                ControlFlow::Continue(_) => continue,
650
0
                ControlFlow::Break(_) => break,
651
            }
652
        }
653
654
0
        Ok(())
655
0
    }
656
}
657
658
/// Utility iterator produced by [`Unstructured::arbitrary_iter`]
659
pub struct ArbitraryIter<'a, 'b, ElementType> {
660
    u: &'b mut Unstructured<'a>,
661
    _marker: PhantomData<ElementType>,
662
}
663
664
impl<'a, 'b, ElementType: Arbitrary<'a>> Iterator for ArbitraryIter<'a, 'b, ElementType> {
665
    type Item = Result<ElementType>;
666
0
    fn next(&mut self) -> Option<Result<ElementType>> {
667
0
        let keep_going = self.u.arbitrary().unwrap_or(false);
668
0
        if keep_going {
669
0
            Some(Arbitrary::arbitrary(self.u))
670
        } else {
671
0
            None
672
        }
673
0
    }
674
}
675
676
/// Utility iterator produced by [`Unstructured::arbitrary_take_rest_iter`]
677
pub struct ArbitraryTakeRestIter<'a, ElementType> {
678
    u: Option<Unstructured<'a>>,
679
    size: usize,
680
    _marker: PhantomData<ElementType>,
681
}
682
683
impl<'a, ElementType: Arbitrary<'a>> Iterator for ArbitraryTakeRestIter<'a, ElementType> {
684
    type Item = Result<ElementType>;
685
0
    fn next(&mut self) -> Option<Result<ElementType>> {
686
0
        if let Some(mut u) = self.u.take() {
687
0
            if self.size == 1 {
688
0
                Some(Arbitrary::arbitrary_take_rest(u))
689
0
            } else if self.size == 0 {
690
0
                None
691
            } else {
692
0
                self.size -= 1;
693
0
                let ret = Arbitrary::arbitrary(&mut u);
694
0
                self.u = Some(u);
695
0
                Some(ret)
696
            }
697
        } else {
698
0
            None
699
        }
700
0
    }
701
}
702
703
/// A trait that is implemented for all of the primitive integers:
704
///
705
/// * `u8`
706
/// * `u16`
707
/// * `u32`
708
/// * `u64`
709
/// * `u128`
710
/// * `usize`
711
/// * `i8`
712
/// * `i16`
713
/// * `i32`
714
/// * `i64`
715
/// * `i128`
716
/// * `isize`
717
///
718
/// Don't implement this trait yourself.
719
pub trait Int:
720
    Copy
721
    + PartialOrd
722
    + Ord
723
    + ops::Sub<Self, Output = Self>
724
    + ops::Rem<Self, Output = Self>
725
    + ops::Shr<Self, Output = Self>
726
    + ops::Shl<usize, Output = Self>
727
    + ops::BitOr<Self, Output = Self>
728
{
729
    #[doc(hidden)]
730
    type Widest: Int;
731
732
    #[doc(hidden)]
733
    const ZERO: Self;
734
735
    #[doc(hidden)]
736
    const ONE: Self;
737
738
    #[doc(hidden)]
739
    fn as_widest(self) -> Self::Widest;
740
741
    #[doc(hidden)]
742
    fn from_widest(w: Self::Widest) -> Self;
743
744
    #[doc(hidden)]
745
    fn from_u8(b: u8) -> Self;
746
747
    #[doc(hidden)]
748
    fn from_usize(u: usize) -> Self;
749
750
    #[doc(hidden)]
751
    fn checked_add(self, rhs: Self) -> Option<Self>;
752
753
    #[doc(hidden)]
754
    fn wrapping_add(self, rhs: Self) -> Self;
755
}
756
757
macro_rules! impl_int {
758
    ( $( $ty:ty : $widest:ty ; )* ) => {
759
        $(
760
            impl Int for $ty {
761
                type Widest = $widest;
762
763
                const ZERO: Self = 0;
764
765
                const ONE: Self = 1;
766
767
0
                fn as_widest(self) -> Self::Widest {
768
0
                    self as $widest
769
0
                }
Unexecuted instantiation: <u8 as arbitrary::unstructured::Int>::as_widest
Unexecuted instantiation: <u16 as arbitrary::unstructured::Int>::as_widest
Unexecuted instantiation: <u32 as arbitrary::unstructured::Int>::as_widest
Unexecuted instantiation: <u64 as arbitrary::unstructured::Int>::as_widest
Unexecuted instantiation: <u128 as arbitrary::unstructured::Int>::as_widest
Unexecuted instantiation: <usize as arbitrary::unstructured::Int>::as_widest
Unexecuted instantiation: <i8 as arbitrary::unstructured::Int>::as_widest
Unexecuted instantiation: <i16 as arbitrary::unstructured::Int>::as_widest
Unexecuted instantiation: <i32 as arbitrary::unstructured::Int>::as_widest
Unexecuted instantiation: <i64 as arbitrary::unstructured::Int>::as_widest
Unexecuted instantiation: <i128 as arbitrary::unstructured::Int>::as_widest
Unexecuted instantiation: <isize as arbitrary::unstructured::Int>::as_widest
770
771
0
                fn from_widest(w: Self::Widest) -> Self {
772
0
                    let x = <$ty>::max_value().as_widest();
773
0
                    (w % x) as Self
774
0
                }
Unexecuted instantiation: <u8 as arbitrary::unstructured::Int>::from_widest
Unexecuted instantiation: <u16 as arbitrary::unstructured::Int>::from_widest
Unexecuted instantiation: <u32 as arbitrary::unstructured::Int>::from_widest
Unexecuted instantiation: <u64 as arbitrary::unstructured::Int>::from_widest
Unexecuted instantiation: <u128 as arbitrary::unstructured::Int>::from_widest
Unexecuted instantiation: <usize as arbitrary::unstructured::Int>::from_widest
Unexecuted instantiation: <i8 as arbitrary::unstructured::Int>::from_widest
Unexecuted instantiation: <i16 as arbitrary::unstructured::Int>::from_widest
Unexecuted instantiation: <i32 as arbitrary::unstructured::Int>::from_widest
Unexecuted instantiation: <i64 as arbitrary::unstructured::Int>::from_widest
Unexecuted instantiation: <i128 as arbitrary::unstructured::Int>::from_widest
Unexecuted instantiation: <isize as arbitrary::unstructured::Int>::from_widest
775
776
0
                fn from_u8(b: u8) -> Self {
777
0
                    b as Self
778
0
                }
Unexecuted instantiation: <u8 as arbitrary::unstructured::Int>::from_u8
Unexecuted instantiation: <u16 as arbitrary::unstructured::Int>::from_u8
Unexecuted instantiation: <u32 as arbitrary::unstructured::Int>::from_u8
Unexecuted instantiation: <u64 as arbitrary::unstructured::Int>::from_u8
Unexecuted instantiation: <u128 as arbitrary::unstructured::Int>::from_u8
Unexecuted instantiation: <usize as arbitrary::unstructured::Int>::from_u8
Unexecuted instantiation: <i8 as arbitrary::unstructured::Int>::from_u8
Unexecuted instantiation: <i16 as arbitrary::unstructured::Int>::from_u8
Unexecuted instantiation: <i32 as arbitrary::unstructured::Int>::from_u8
Unexecuted instantiation: <i64 as arbitrary::unstructured::Int>::from_u8
Unexecuted instantiation: <i128 as arbitrary::unstructured::Int>::from_u8
Unexecuted instantiation: <isize as arbitrary::unstructured::Int>::from_u8
779
780
0
                fn from_usize(u: usize) -> Self {
781
0
                    u as Self
782
0
                }
Unexecuted instantiation: <u8 as arbitrary::unstructured::Int>::from_usize
Unexecuted instantiation: <u16 as arbitrary::unstructured::Int>::from_usize
Unexecuted instantiation: <u32 as arbitrary::unstructured::Int>::from_usize
Unexecuted instantiation: <u64 as arbitrary::unstructured::Int>::from_usize
Unexecuted instantiation: <u128 as arbitrary::unstructured::Int>::from_usize
Unexecuted instantiation: <usize as arbitrary::unstructured::Int>::from_usize
Unexecuted instantiation: <i8 as arbitrary::unstructured::Int>::from_usize
Unexecuted instantiation: <i16 as arbitrary::unstructured::Int>::from_usize
Unexecuted instantiation: <i32 as arbitrary::unstructured::Int>::from_usize
Unexecuted instantiation: <i64 as arbitrary::unstructured::Int>::from_usize
Unexecuted instantiation: <i128 as arbitrary::unstructured::Int>::from_usize
Unexecuted instantiation: <isize as arbitrary::unstructured::Int>::from_usize
783
784
0
                fn checked_add(self, rhs: Self) -> Option<Self> {
785
0
                    <$ty>::checked_add(self, rhs)
786
0
                }
Unexecuted instantiation: <u8 as arbitrary::unstructured::Int>::checked_add
Unexecuted instantiation: <u16 as arbitrary::unstructured::Int>::checked_add
Unexecuted instantiation: <u32 as arbitrary::unstructured::Int>::checked_add
Unexecuted instantiation: <u64 as arbitrary::unstructured::Int>::checked_add
Unexecuted instantiation: <u128 as arbitrary::unstructured::Int>::checked_add
Unexecuted instantiation: <usize as arbitrary::unstructured::Int>::checked_add
Unexecuted instantiation: <i8 as arbitrary::unstructured::Int>::checked_add
Unexecuted instantiation: <i16 as arbitrary::unstructured::Int>::checked_add
Unexecuted instantiation: <i32 as arbitrary::unstructured::Int>::checked_add
Unexecuted instantiation: <i64 as arbitrary::unstructured::Int>::checked_add
Unexecuted instantiation: <i128 as arbitrary::unstructured::Int>::checked_add
Unexecuted instantiation: <isize as arbitrary::unstructured::Int>::checked_add
787
788
0
                fn wrapping_add(self, rhs: Self) -> Self {
789
0
                    <$ty>::wrapping_add(self, rhs)
790
0
                }
Unexecuted instantiation: <u8 as arbitrary::unstructured::Int>::wrapping_add
Unexecuted instantiation: <u16 as arbitrary::unstructured::Int>::wrapping_add
Unexecuted instantiation: <u32 as arbitrary::unstructured::Int>::wrapping_add
Unexecuted instantiation: <u64 as arbitrary::unstructured::Int>::wrapping_add
Unexecuted instantiation: <u128 as arbitrary::unstructured::Int>::wrapping_add
Unexecuted instantiation: <usize as arbitrary::unstructured::Int>::wrapping_add
Unexecuted instantiation: <i8 as arbitrary::unstructured::Int>::wrapping_add
Unexecuted instantiation: <i16 as arbitrary::unstructured::Int>::wrapping_add
Unexecuted instantiation: <i32 as arbitrary::unstructured::Int>::wrapping_add
Unexecuted instantiation: <i64 as arbitrary::unstructured::Int>::wrapping_add
Unexecuted instantiation: <i128 as arbitrary::unstructured::Int>::wrapping_add
Unexecuted instantiation: <isize as arbitrary::unstructured::Int>::wrapping_add
791
            }
792
        )*
793
    }
794
}
795
796
impl_int! {
797
    u8: u128;
798
    u16: u128;
799
    u32: u128;
800
    u64: u128;
801
    u128: u128;
802
    usize: u128;
803
    i8: i128;
804
    i16: i128;
805
    i32: i128;
806
    i64: i128;
807
    i128: i128;
808
    isize: i128;
809
}
810
811
#[cfg(test)]
812
mod tests {
813
    use super::*;
814
815
    #[test]
816
    fn test_byte_size() {
817
        let mut u = Unstructured::new(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 6]);
818
        // Should take one byte off the end
819
        assert_eq!(u.arbitrary_byte_size().unwrap(), 6);
820
        assert_eq!(u.len(), 9);
821
        let mut v = vec![];
822
        v.resize(260, 0);
823
        v.push(1);
824
        v.push(4);
825
        let mut u = Unstructured::new(&v);
826
        // Should read two bytes off the end
827
        assert_eq!(u.arbitrary_byte_size().unwrap(), 0x104);
828
        assert_eq!(u.len(), 260);
829
    }
830
831
    #[test]
832
    fn int_in_range_of_one() {
833
        let mut u = Unstructured::new(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 6]);
834
        let x = u.int_in_range(0..=0).unwrap();
835
        assert_eq!(x, 0);
836
        let choice = *u.choose(&[42]).unwrap();
837
        assert_eq!(choice, 42)
838
    }
839
840
    #[test]
841
    fn int_in_range_uses_minimal_amount_of_bytes() {
842
        let mut u = Unstructured::new(&[1]);
843
        u.int_in_range::<u8>(0..=u8::MAX).unwrap();
844
845
        let mut u = Unstructured::new(&[1]);
846
        u.int_in_range::<u32>(0..=u8::MAX as u32).unwrap();
847
848
        let mut u = Unstructured::new(&[1]);
849
        u.int_in_range::<u32>(0..=u8::MAX as u32 + 1).unwrap_err();
850
    }
851
}