Coverage Report

Created: 2025-08-26 06:08

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