Coverage Report

Created: 2026-11-03 08:22

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/arbitrary-1.4.2/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
#[derive(Debug)]
72
pub struct Unstructured<'a> {
73
    data: &'a [u8],
74
}
75
76
impl<'a> Unstructured<'a> {
77
    /// Create a new `Unstructured` from the given raw data.
78
    ///
79
    /// # Example
80
    ///
81
    /// ```
82
    /// use arbitrary::Unstructured;
83
    ///
84
    /// let u = Unstructured::new(&[1, 2, 3, 4]);
85
    /// ```
86
29.5k
    pub fn new(data: &'a [u8]) -> Self {
87
29.5k
        Unstructured { data }
88
29.5k
    }
89
90
    /// Get the number of remaining bytes of underlying data that are still
91
    /// available.
92
    ///
93
    /// # Example
94
    ///
95
    /// ```
96
    /// use arbitrary::{Arbitrary, Unstructured};
97
    ///
98
    /// let mut u = Unstructured::new(&[1, 2, 3]);
99
    ///
100
    /// // Initially have three bytes of data.
101
    /// assert_eq!(u.len(), 3);
102
    ///
103
    /// // Generating a `bool` consumes one byte from the underlying data, so
104
    /// // we are left with two bytes afterwards.
105
    /// let _ = bool::arbitrary(&mut u);
106
    /// assert_eq!(u.len(), 2);
107
    /// ```
108
    #[inline]
109
27.6M
    pub fn len(&self) -> usize {
110
27.6M
        self.data.len()
111
27.6M
    }
112
113
    /// Is the underlying unstructured data exhausted?
114
    ///
115
    /// `unstructured.is_empty()` is the same as `unstructured.len() == 0`.
116
    ///
117
    /// # Example
118
    ///
119
    /// ```
120
    /// use arbitrary::{Arbitrary, Unstructured};
121
    ///
122
    /// let mut u = Unstructured::new(&[1, 2, 3, 4]);
123
    ///
124
    /// // Initially, we are not empty.
125
    /// assert!(!u.is_empty());
126
    ///
127
    /// // Generating a `u32` consumes all four bytes of the underlying data, so
128
    /// // we become empty afterwards.
129
    /// let _ = u32::arbitrary(&mut u);
130
    /// assert!(u.is_empty());
131
    /// ```
132
    #[inline]
133
27.6M
    pub fn is_empty(&self) -> bool {
134
27.6M
        self.len() == 0
135
27.6M
    }
136
137
    /// Generate an arbitrary instance of `A`.
138
    ///
139
    /// This is simply a helper method that is equivalent to `<A as
140
    /// Arbitrary>::arbitrary(self)`. This helper is a little bit more concise,
141
    /// and can be used in situations where Rust's type inference will figure
142
    /// out what `A` should be.
143
    ///
144
    /// # Example
145
    ///
146
    /// ```
147
    /// # #[cfg(feature="derive")] fn foo() -> arbitrary::Result<()> {
148
    /// use arbitrary::{Arbitrary, Unstructured};
149
    ///
150
    /// #[derive(Arbitrary)]
151
    /// struct MyType {
152
    ///     // ...
153
    /// }
154
    ///
155
    /// fn do_stuff(value: MyType) {
156
    /// #   let _ = value;
157
    ///     // ...
158
    /// }
159
    ///
160
    /// let mut u = Unstructured::new(&[1, 2, 3, 4]);
161
    ///
162
    /// // Rust's type inference can figure out that `value` should be of type
163
    /// // `MyType` here:
164
    /// let value = u.arbitrary()?;
165
    /// do_stuff(value);
166
    /// # Ok(()) }
167
    /// ```
168
16.1M
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
16.1M
    where
170
16.1M
        A: Arbitrary<'a>,
171
    {
172
16.1M
        <A as Arbitrary<'a>>::arbitrary(self)
173
16.1M
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary::<core::option::Option<alloc::vec::Vec<surrealdb_core::sql::kind::Kind>>>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary::<core::option::Option<alloc::boxed::Box<surrealdb_core::sql::kind::Kind>>>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary::<core::option::Option<surrealdb_strand::Strand>>
<arbitrary::unstructured::Unstructured>::arbitrary::<core::option::Option<alloc::string::String>>
Line
Count
Source
168
9
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
9
    where
170
9
        A: Arbitrary<'a>,
171
    {
172
9
        <A as Arbitrary<'a>>::arbitrary(self)
173
9
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<core::option::Option<surrealdb_core::sql::expression::Expr>>
Line
Count
Source
168
17
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
17
    where
170
17
        A: Arbitrary<'a>,
171
    {
172
17
        <A as Arbitrary<'a>>::arbitrary(self)
173
17
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<core::option::Option<surrealdb_core::sql::cond::Cond>>
Line
Count
Source
168
49
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
49
    where
170
49
        A: Arbitrary<'a>,
171
    {
172
49
        <A as Arbitrary<'a>>::arbitrary(self)
173
49
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<core::option::Option<surrealdb_core::sql::kind::Kind>>
Line
Count
Source
168
9.85k
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
9.85k
    where
170
9.85k
        A: Arbitrary<'a>,
171
    {
172
9.85k
        <A as Arbitrary<'a>>::arbitrary(self)
173
9.85k
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<core::option::Option<surrealdb_core::sql::part::RecurseInstruction>>
Line
Count
Source
168
15
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
15
    where
170
15
        A: Arbitrary<'a>,
171
    {
172
15
        <A as Arbitrary<'a>>::arbitrary(self)
173
15
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<core::option::Option<surrealdb_core::sql::with::With>>
Line
Count
Source
168
7
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
7
    where
170
7
        A: Arbitrary<'a>,
171
    {
172
7
        <A as Arbitrary<'a>>::arbitrary(self)
173
7
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<core::option::Option<surrealdb_core::sql::fetch::Fetchs>>
Line
Count
Source
168
7
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
7
    where
170
7
        A: Arbitrary<'a>,
171
    {
172
7
        <A as Arbitrary<'a>>::arbitrary(self)
173
7
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<core::option::Option<surrealdb_core::sql::field::Fields>>
Line
Count
Source
168
44
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
44
    where
170
44
        A: Arbitrary<'a>,
171
    {
172
44
        <A as Arbitrary<'a>>::arbitrary(self)
173
44
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<core::option::Option<surrealdb_core::sql::limit::Limit>>
Line
Count
Source
168
49
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
49
    where
170
49
        A: Arbitrary<'a>,
171
    {
172
49
        <A as Arbitrary<'a>>::arbitrary(self)
173
49
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<core::option::Option<surrealdb_core::sql::start::Start>>
Line
Count
Source
168
49
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
49
    where
170
49
        A: Arbitrary<'a>,
171
    {
172
49
        <A as Arbitrary<'a>>::arbitrary(self)
173
49
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<core::option::Option<surrealdb_core::sql::output::Output>>
Line
Count
Source
168
39
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
39
    where
170
39
        A: Arbitrary<'a>,
171
    {
172
39
        <A as Arbitrary<'a>>::arbitrary(self)
173
39
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<core::option::Option<surrealdb_core::sql::explain::Explain>>
Line
Count
Source
168
7
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
7
    where
170
7
        A: Arbitrary<'a>,
171
    {
172
7
        <A as Arbitrary<'a>>::arbitrary(self)
173
7
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<core::option::Option<surrealdb_core::sql::reference::Reference>>
Line
Count
Source
168
2
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
2
    where
170
2
        A: Arbitrary<'a>,
171
    {
172
2
        <A as Arbitrary<'a>>::arbitrary(self)
173
2
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary::<core::option::Option<u64>>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary::<alloc::vec::Vec<alloc::string::String>>
<arbitrary::unstructured::Unstructured>::arbitrary::<alloc::vec::Vec<surrealdb_core::sql::expression::Expr>>
Line
Count
Source
168
26
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
26
    where
170
26
        A: Arbitrary<'a>,
171
    {
172
26
        <A as Arbitrary<'a>>::arbitrary(self)
173
26
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary::<alloc::vec::Vec<surrealdb_core::sql::kind::GeometryKind>>
<arbitrary::unstructured::Unstructured>::arbitrary::<alloc::vec::Vec<surrealdb_core::sql::lookup::LookupSubject>>
Line
Count
Source
168
42
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
42
    where
170
42
        A: Arbitrary<'a>,
171
    {
172
42
        <A as Arbitrary<'a>>::arbitrary(self)
173
42
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<alloc::vec::Vec<surrealdb_core::sql::literal::ObjectEntry>>
Line
Count
Source
168
1
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
1
    where
170
1
        A: Arbitrary<'a>,
171
    {
172
1
        <A as Arbitrary<'a>>::arbitrary(self)
173
1
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary::<alloc::vec::Vec<surrealdb_core::val::table::TableName>>
<arbitrary::unstructured::Unstructured>::arbitrary::<alloc::vec::Vec<(surrealdb_core::sql::param::Param, surrealdb_core::sql::kind::Kind)>>
Line
Count
Source
168
9.85k
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
9.85k
    where
170
9.85k
        A: Arbitrary<'a>,
171
    {
172
9.85k
        <A as Arbitrary<'a>>::arbitrary(self)
173
9.85k
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary::<alloc::boxed::Box<surrealdb_core::sql::kind::Kind>>
<arbitrary::unstructured::Unstructured>::arbitrary::<alloc::boxed::Box<surrealdb_core::sql::block::Block>>
Line
Count
Source
168
9.83k
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
9.83k
    where
170
9.83k
        A: Arbitrary<'a>,
171
    {
172
9.83k
        <A as Arbitrary<'a>>::arbitrary(self)
173
9.83k
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<alloc::boxed::Box<surrealdb_core::sql::lookup::Lookup>>
Line
Count
Source
168
84
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
84
    where
170
84
        A: Arbitrary<'a>,
171
    {
172
84
        <A as Arbitrary<'a>>::arbitrary(self)
173
84
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::sql::statements::alter::AlterKind<alloc::string::String>>
Line
Count
Source
168
2
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
2
    where
170
2
        A: Arbitrary<'a>,
171
    {
172
2
        <A as Arbitrary<'a>>::arbitrary(self)
173
2
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_strand::Strand>
Line
Count
Source
168
2.16M
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
2.16M
    where
170
2.16M
        A: Arbitrary<'a>,
171
    {
172
2.16M
        <A as Arbitrary<'a>>::arbitrary(self)
173
2.16M
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<alloc::string::String>
Line
Count
Source
168
12
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
12
    where
170
12
        A: Arbitrary<'a>,
171
    {
172
12
        <A as Arbitrary<'a>>::arbitrary(self)
173
12
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<rust_decimal::decimal::Decimal>
Line
Count
Source
168
33.8k
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
33.8k
    where
170
33.8k
        A: Arbitrary<'a>,
171
    {
172
33.8k
        <A as Arbitrary<'a>>::arbitrary(self)
173
33.8k
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_types::value::uuid::Uuid>
Line
Count
Source
168
988
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
988
    where
170
988
        A: Arbitrary<'a>,
171
    {
172
988
        <A as Arbitrary<'a>>::arbitrary(self)
173
988
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_types::value::duration::Duration>
<arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::sql::expression::Expr>
Line
Count
Source
168
387
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
387
    where
170
387
        A: Arbitrary<'a>,
171
    {
172
387
        <A as Arbitrary<'a>>::arbitrary(self)
173
387
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::sql::permission::Permissions>
Line
Count
Source
168
2
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
2
    where
170
2
        A: Arbitrary<'a>,
171
    {
172
2
        <A as Arbitrary<'a>>::arbitrary(self)
173
2
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::sql::access_type::AccessType>
Line
Count
Source
168
11
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
11
    where
170
11
        A: Arbitrary<'a>,
171
    {
172
11
        <A as Arbitrary<'a>>::arbitrary(self)
173
11
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::sql::access_type::JwtAccessVerify>
Line
Count
Source
168
11
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
11
    where
170
11
        A: Arbitrary<'a>,
171
    {
172
11
        <A as Arbitrary<'a>>::arbitrary(self)
173
11
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::sql::base::Base>
Line
Count
Source
168
4
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
4
    where
170
4
        A: Arbitrary<'a>,
171
    {
172
4
        <A as Arbitrary<'a>>::arbitrary(self)
173
4
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::sql::kind::KindLiteral>
<arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::sql::part::Part>
Line
Count
Source
168
11.2M
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
11.2M
    where
170
11.2M
        A: Arbitrary<'a>,
171
    {
172
11.2M
        <A as Arbitrary<'a>>::arbitrary(self)
173
11.2M
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::sql::part::Recurse>
Line
Count
Source
168
16
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
16
    where
170
16
        A: Arbitrary<'a>,
171
    {
172
16
        <A as Arbitrary<'a>>::arbitrary(self)
173
16
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::sql::field::Fields>
Line
Count
Source
168
7
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
7
    where
170
7
        A: Arbitrary<'a>,
171
    {
172
7
        <A as Arbitrary<'a>>::arbitrary(self)
173
7
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::sql::index::Index>
<arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::sql::model::Model>
Line
Count
Source
168
29
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
29
    where
170
29
        A: Arbitrary<'a>,
171
    {
172
29
        <A as Arbitrary<'a>>::arbitrary(self)
173
29
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::sql::order::OrderList>
<arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::sql::param::Param>
Line
Count
Source
168
2.01M
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
2.01M
    where
170
2.01M
        A: Arbitrary<'a>,
171
    {
172
2.01M
        <A as Arbitrary<'a>>::arbitrary(self)
173
2.01M
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::sql::lookup::LookupKind>
Line
Count
Source
168
82
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
82
    where
170
82
        A: Arbitrary<'a>,
171
    {
172
82
        <A as Arbitrary<'a>>::arbitrary(self)
173
82
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::sql::lookup::LookupSubject>
Line
Count
Source
168
20
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
20
    where
170
20
        A: Arbitrary<'a>,
171
    {
172
20
        <A as Arbitrary<'a>>::arbitrary(self)
173
20
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::sql::script::Script>
Line
Count
Source
168
26
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
26
    where
170
26
        A: Arbitrary<'a>,
171
    {
172
26
        <A as Arbitrary<'a>>::arbitrary(self)
173
26
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::sql::algorithm::Algorithm>
Line
Count
Source
168
1
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
1
    where
170
1
        A: Arbitrary<'a>,
171
    {
172
1
        <A as Arbitrary<'a>>::arbitrary(self)
173
1
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::val::table::TableName>
Line
Count
Source
168
38
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
38
    where
170
38
        A: Arbitrary<'a>,
171
    {
172
38
        <A as Arbitrary<'a>>::arbitrary(self)
173
38
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::sql::statements::define::DefineKind>
Line
Count
Source
168
14
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
14
    where
170
14
        A: Arbitrary<'a>,
171
    {
172
14
        <A as Arbitrary<'a>>::arbitrary(self)
173
14
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::sql::record_id::key::RecordIdKeyGen>
Line
Count
Source
168
1
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
1
    where
170
1
        A: Arbitrary<'a>,
171
    {
172
1
        <A as Arbitrary<'a>>::arbitrary(self)
173
1
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::sql::statements::define::user::PassType>
Line
Count
Source
168
1
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
1
    where
170
1
        A: Arbitrary<'a>,
171
    {
172
1
        <A as Arbitrary<'a>>::arbitrary(self)
173
1
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<surrealdb_core::sql::statements::define::field::DefineDefault>
Line
Count
Source
168
2
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
2
    where
170
2
        A: Arbitrary<'a>,
171
    {
172
2
        <A as Arbitrary<'a>>::arbitrary(self)
173
2
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<&str>
Line
Count
Source
168
1
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
1
    where
170
1
        A: Arbitrary<'a>,
171
    {
172
1
        <A as Arbitrary<'a>>::arbitrary(self)
173
1
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary::<f32>
<arbitrary::unstructured::Unstructured>::arbitrary::<alloc::vec::Vec<geo_types::geometry::line_string::LineString>>
Line
Count
Source
168
2
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
2
    where
170
2
        A: Arbitrary<'a>,
171
    {
172
2
        <A as Arbitrary<'a>>::arbitrary(self)
173
2
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<alloc::vec::Vec<geo_types::geometry::coord::Coord>>
Line
Count
Source
168
5
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
5
    where
170
5
        A: Arbitrary<'a>,
171
    {
172
5
        <A as Arbitrary<'a>>::arbitrary(self)
173
5
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary::<alloc::vec::Vec<geo_types::geometry::point::Point>>
<arbitrary::unstructured::Unstructured>::arbitrary::<alloc::vec::Vec<geo_types::geometry::polygon::Polygon>>
Line
Count
Source
168
2
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
2
    where
170
2
        A: Arbitrary<'a>,
171
    {
172
2
        <A as Arbitrary<'a>>::arbitrary(self)
173
2
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<chrono::naive::date::NaiveDate>
Line
Count
Source
168
5
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
5
    where
170
5
        A: Arbitrary<'a>,
171
    {
172
5
        <A as Arbitrary<'a>>::arbitrary(self)
173
5
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<chrono::naive::time::NaiveTime>
Line
Count
Source
168
5
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
5
    where
170
5
        A: Arbitrary<'a>,
171
    {
172
5
        <A as Arbitrary<'a>>::arbitrary(self)
173
5
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<geo_types::geometry::line_string::LineString>
Line
Count
Source
168
2
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
2
    where
170
2
        A: Arbitrary<'a>,
171
    {
172
2
        <A as Arbitrary<'a>>::arbitrary(self)
173
2
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<geo_types::geometry::coord::Coord>
Line
Count
Source
168
1
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
1
    where
170
1
        A: Arbitrary<'a>,
171
    {
172
1
        <A as Arbitrary<'a>>::arbitrary(self)
173
1
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<&[u8]>
Line
Count
Source
168
61
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
61
    where
170
61
        A: Arbitrary<'a>,
171
    {
172
61
        <A as Arbitrary<'a>>::arbitrary(self)
173
61
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<f64>
Line
Count
Source
168
58.5k
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
58.5k
    where
170
58.5k
        A: Arbitrary<'a>,
171
    {
172
58.5k
        <A as Arbitrary<'a>>::arbitrary(self)
173
58.5k
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary::<regex_syntax::ast::ClassUnicodeOpKind>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary::<regex_syntax::ast::Span>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary::<char>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary::<core::net::socket_addr::SocketAddrV4>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary::<core::net::socket_addr::SocketAddrV6>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary::<core::net::ip_addr::Ipv4Addr>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary::<core::net::ip_addr::Ipv6Addr>
<arbitrary::unstructured::Unstructured>::arbitrary::<bool>
Line
Count
Source
168
347k
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
347k
    where
170
347k
        A: Arbitrary<'a>,
171
    {
172
347k
        <A as Arbitrary<'a>>::arbitrary(self)
173
347k
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<u32>
Line
Count
Source
168
102
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
102
    where
170
102
        A: Arbitrary<'a>,
171
    {
172
102
        <A as Arbitrary<'a>>::arbitrary(self)
173
102
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary::<u16>
<arbitrary::unstructured::Unstructured>::arbitrary::<i64>
Line
Count
Source
168
42.6k
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
42.6k
    where
170
42.6k
        A: Arbitrary<'a>,
171
    {
172
42.6k
        <A as Arbitrary<'a>>::arbitrary(self)
173
42.6k
    }
<arbitrary::unstructured::Unstructured>::arbitrary::<u64>
Line
Count
Source
168
135k
    pub fn arbitrary<A>(&mut self) -> Result<A>
169
135k
    where
170
135k
        A: Arbitrary<'a>,
171
    {
172
135k
        <A as Arbitrary<'a>>::arbitrary(self)
173
135k
    }
174
175
    /// Get the number of elements to insert when building up a collection of
176
    /// arbitrary `ElementType`s.
177
    ///
178
    /// This uses the [`<ElementType as
179
    /// Arbitrary>::size_hint`][crate::Arbitrary::size_hint] method to smartly
180
    /// choose a length such that we most likely have enough underlying bytes to
181
    /// construct that many arbitrary `ElementType`s.
182
    ///
183
    /// This should only be called within an `Arbitrary` implementation.
184
    ///
185
    /// # Example
186
    ///
187
    /// ```
188
    /// use arbitrary::{Arbitrary, Result, Unstructured};
189
    /// # pub struct MyCollection<T> { _t: std::marker::PhantomData<T> }
190
    /// # impl<T> MyCollection<T> {
191
    /// #     pub fn with_capacity(capacity: usize) -> Self { MyCollection { _t: std::marker::PhantomData } }
192
    /// #     pub fn insert(&mut self, element: T) {}
193
    /// # }
194
    ///
195
    /// impl<'a, T> Arbitrary<'a> for MyCollection<T>
196
    /// where
197
    ///     T: Arbitrary<'a>,
198
    /// {
199
    ///     fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
200
    ///         // Get the number of `T`s we should insert into our collection.
201
    ///         let len = u.arbitrary_len::<T>()?;
202
    ///
203
    ///         // And then create a collection of that length!
204
    ///         let mut my_collection = MyCollection::with_capacity(len);
205
    ///         for _ in 0..len {
206
    ///             let element = T::arbitrary(u)?;
207
    ///             my_collection.insert(element);
208
    ///         }
209
    ///
210
    ///         Ok(my_collection)
211
    ///     }
212
    /// }
213
    /// ```
214
4.98M
    pub fn arbitrary_len<ElementType>(&mut self) -> Result<usize>
215
4.98M
    where
216
4.98M
        ElementType: Arbitrary<'a>,
217
    {
218
4.98M
        let byte_size = self.arbitrary_byte_size()?;
219
4.98M
        let (lower, upper) = <ElementType as Arbitrary>::size_hint(0);
220
4.98M
        let elem_size = upper.unwrap_or(lower * 2);
221
4.98M
        let elem_size = std::cmp::max(1, elem_size);
222
4.98M
        Ok(byte_size / elem_size)
223
4.98M
    }
<arbitrary::unstructured::Unstructured>::arbitrary_len::<alloc::vec::Vec<surrealdb_core::sql::expression::Expr>>
Line
Count
Source
214
22
    pub fn arbitrary_len<ElementType>(&mut self) -> Result<usize>
215
22
    where
216
22
        ElementType: Arbitrary<'a>,
217
    {
218
22
        let byte_size = self.arbitrary_byte_size()?;
219
22
        let (lower, upper) = <ElementType as Arbitrary>::size_hint(0);
220
22
        let elem_size = upper.unwrap_or(lower * 2);
221
22
        let elem_size = std::cmp::max(1, elem_size);
222
22
        Ok(byte_size / elem_size)
223
22
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_len::<alloc::string::String>
<arbitrary::unstructured::Unstructured>::arbitrary_len::<surrealdb_core::sql::expression::Expr>
Line
Count
Source
214
420
    pub fn arbitrary_len<ElementType>(&mut self) -> Result<usize>
215
420
    where
216
420
        ElementType: Arbitrary<'a>,
217
    {
218
420
        let byte_size = self.arbitrary_byte_size()?;
219
420
        let (lower, upper) = <ElementType as Arbitrary>::size_hint(0);
220
420
        let elem_size = upper.unwrap_or(lower * 2);
221
420
        let elem_size = std::cmp::max(1, elem_size);
222
420
        Ok(byte_size / elem_size)
223
420
    }
<arbitrary::unstructured::Unstructured>::arbitrary_len::<surrealdb_core::sql::data::Assignment>
Line
Count
Source
214
9
    pub fn arbitrary_len<ElementType>(&mut self) -> Result<usize>
215
9
    where
216
9
        ElementType: Arbitrary<'a>,
217
    {
218
9
        let byte_size = self.arbitrary_byte_size()?;
219
9
        let (lower, upper) = <ElementType as Arbitrary>::size_hint(0);
220
9
        let elem_size = upper.unwrap_or(lower * 2);
221
9
        let elem_size = std::cmp::max(1, elem_size);
222
9
        Ok(byte_size / elem_size)
223
9
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_len::<surrealdb_core::sql::kind::Kind>
<arbitrary::unstructured::Unstructured>::arbitrary_len::<surrealdb_core::sql::part::DestructurePart>
Line
Count
Source
214
53
    pub fn arbitrary_len<ElementType>(&mut self) -> Result<usize>
215
53
    where
216
53
        ElementType: Arbitrary<'a>,
217
    {
218
53
        let byte_size = self.arbitrary_byte_size()?;
219
53
        let (lower, upper) = <ElementType as Arbitrary>::size_hint(0);
220
53
        let elem_size = upper.unwrap_or(lower * 2);
221
53
        let elem_size = std::cmp::max(1, elem_size);
222
53
        Ok(byte_size / elem_size)
223
53
    }
<arbitrary::unstructured::Unstructured>::arbitrary_len::<surrealdb_core::sql::part::Part>
Line
Count
Source
214
181
    pub fn arbitrary_len<ElementType>(&mut self) -> Result<usize>
215
181
    where
216
181
        ElementType: Arbitrary<'a>,
217
    {
218
181
        let byte_size = self.arbitrary_byte_size()?;
219
181
        let (lower, upper) = <ElementType as Arbitrary>::size_hint(0);
220
181
        let elem_size = upper.unwrap_or(lower * 2);
221
181
        let elem_size = std::cmp::max(1, elem_size);
222
181
        Ok(byte_size / elem_size)
223
181
    }
<arbitrary::unstructured::Unstructured>::arbitrary_len::<surrealdb_core::sql::fetch::Fetch>
Line
Count
Source
214
16
    pub fn arbitrary_len<ElementType>(&mut self) -> Result<usize>
215
16
    where
216
16
        ElementType: Arbitrary<'a>,
217
    {
218
16
        let byte_size = self.arbitrary_byte_size()?;
219
16
        let (lower, upper) = <ElementType as Arbitrary>::size_hint(0);
220
16
        let elem_size = upper.unwrap_or(lower * 2);
221
16
        let elem_size = std::cmp::max(1, elem_size);
222
16
        Ok(byte_size / elem_size)
223
16
    }
<arbitrary::unstructured::Unstructured>::arbitrary_len::<surrealdb_core::sql::field::Field>
Line
Count
Source
214
13
    pub fn arbitrary_len<ElementType>(&mut self) -> Result<usize>
215
13
    where
216
13
        ElementType: Arbitrary<'a>,
217
    {
218
13
        let byte_size = self.arbitrary_byte_size()?;
219
13
        let (lower, upper) = <ElementType as Arbitrary>::size_hint(0);
220
13
        let elem_size = upper.unwrap_or(lower * 2);
221
13
        let elem_size = std::cmp::max(1, elem_size);
222
13
        Ok(byte_size / elem_size)
223
13
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_len::<surrealdb_core::sql::group::Group>
<arbitrary::unstructured::Unstructured>::arbitrary_len::<surrealdb_core::sql::idiom::Idiom>
Line
Count
Source
214
26
    pub fn arbitrary_len<ElementType>(&mut self) -> Result<usize>
215
26
    where
216
26
        ElementType: Arbitrary<'a>,
217
    {
218
26
        let byte_size = self.arbitrary_byte_size()?;
219
26
        let (lower, upper) = <ElementType as Arbitrary>::size_hint(0);
220
26
        let elem_size = upper.unwrap_or(lower * 2);
221
26
        let elem_size = std::cmp::max(1, elem_size);
222
26
        Ok(byte_size / elem_size)
223
26
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_len::<surrealdb_core::sql::order::Order>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_len::<surrealdb_core::sql::split::Split>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_len::<surrealdb_core::sql::filter::Filter>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_len::<surrealdb_core::sql::tokenizer::Tokenizer>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_len::<surrealdb_core::val::table::TableName>
<arbitrary::unstructured::Unstructured>::arbitrary_len::<surrealdb_core::catalog::schema::api::ApiMethod>
Line
Count
Source
214
1
    pub fn arbitrary_len<ElementType>(&mut self) -> Result<usize>
215
1
    where
216
1
        ElementType: Arbitrary<'a>,
217
    {
218
1
        let byte_size = self.arbitrary_byte_size()?;
219
1
        let (lower, upper) = <ElementType as Arbitrary>::size_hint(0);
220
1
        let elem_size = upper.unwrap_or(lower * 2);
221
1
        let elem_size = std::cmp::max(1, elem_size);
222
1
        Ok(byte_size / elem_size)
223
1
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_len::<surrealdb_core::sql::statements::define::config::graphql::TableConfig>
<arbitrary::unstructured::Unstructured>::arbitrary_len::<(surrealdb_core::sql::expression::Expr, surrealdb_core::sql::expression::Expr)>
Line
Count
Source
214
27
    pub fn arbitrary_len<ElementType>(&mut self) -> Result<usize>
215
27
    where
216
27
        ElementType: Arbitrary<'a>,
217
    {
218
27
        let byte_size = self.arbitrary_byte_size()?;
219
27
        let (lower, upper) = <ElementType as Arbitrary>::size_hint(0);
220
27
        let elem_size = upper.unwrap_or(lower * 2);
221
27
        let elem_size = std::cmp::max(1, elem_size);
222
27
        Ok(byte_size / elem_size)
223
27
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_len::<char>
<arbitrary::unstructured::Unstructured>::arbitrary_len::<u8>
Line
Count
Source
214
4.98M
    pub fn arbitrary_len<ElementType>(&mut self) -> Result<usize>
215
4.98M
    where
216
4.98M
        ElementType: Arbitrary<'a>,
217
    {
218
4.98M
        let byte_size = self.arbitrary_byte_size()?;
219
4.98M
        let (lower, upper) = <ElementType as Arbitrary>::size_hint(0);
220
4.98M
        let elem_size = upper.unwrap_or(lower * 2);
221
4.98M
        let elem_size = std::cmp::max(1, elem_size);
222
4.98M
        Ok(byte_size / elem_size)
223
4.98M
    }
224
225
4.98M
    fn arbitrary_byte_size(&mut self) -> Result<usize> {
226
4.98M
        if self.data.is_empty() {
227
4.62M
            Ok(0)
228
361k
        } else if self.data.len() == 1 {
229
2
            self.data = &[];
230
2
            Ok(0)
231
        } else {
232
            // Take lengths from the end of the data, since the `libFuzzer` folks
233
            // found that this lets fuzzers more efficiently explore the input
234
            // space.
235
            //
236
            // https://github.com/rust-fuzz/libfuzzer-sys/blob/0c450753/libfuzzer/utils/FuzzedDataProvider.h#L92-L97
237
238
            // We only consume as many bytes as necessary to cover the entire
239
            // range of the byte string.
240
            // Note: We cast to u64 so we don't overflow when checking u32::MAX + 4 on 32-bit archs
241
361k
            let len = if self.data.len() as u64 <= u8::MAX as u64 + 1 {
242
283
                let bytes = 1;
243
283
                let max_size = self.data.len() - bytes;
244
283
                let (rest, for_size) = self.data.split_at(max_size);
245
283
                self.data = rest;
246
283
                Self::int_in_range_impl(0..=max_size as u8, for_size.iter().copied())?.0 as usize
247
361k
            } else if self.data.len() as u64 <= u16::MAX as u64 + 2 {
248
43.7k
                let bytes = 2;
249
43.7k
                let max_size = self.data.len() - bytes;
250
43.7k
                let (rest, for_size) = self.data.split_at(max_size);
251
43.7k
                self.data = rest;
252
43.7k
                Self::int_in_range_impl(0..=max_size as u16, for_size.iter().copied())?.0 as usize
253
317k
            } else if self.data.len() as u64 <= u32::MAX as u64 + 4 {
254
317k
                let bytes = 4;
255
317k
                let max_size = self.data.len() - bytes;
256
317k
                let (rest, for_size) = self.data.split_at(max_size);
257
317k
                self.data = rest;
258
317k
                Self::int_in_range_impl(0..=max_size as u32, for_size.iter().copied())?.0 as usize
259
            } else {
260
0
                let bytes = 8;
261
0
                let max_size = self.data.len() - bytes;
262
0
                let (rest, for_size) = self.data.split_at(max_size);
263
0
                self.data = rest;
264
0
                Self::int_in_range_impl(0..=max_size as u64, for_size.iter().copied())?.0 as usize
265
            };
266
267
361k
            Ok(len)
268
        }
269
4.98M
    }
270
271
    /// Generate an integer within the given range.
272
    ///
273
    /// Do not use this to generate the size of a collection. Use
274
    /// `arbitrary_len` instead.
275
    ///
276
    /// The probability distribution of the return value is not necessarily uniform.
277
    ///
278
    /// Returns `range.start()`, not an error,
279
    /// if this `Unstructured` [is empty][Unstructured::is_empty].
280
    ///
281
    /// # Panics
282
    ///
283
    /// Panics if `range.start > range.end`. That is, the given range must be
284
    /// non-empty.
285
    ///
286
    /// # Example
287
    ///
288
    /// ```
289
    /// # fn foo() -> arbitrary::Result<()> {
290
    /// use arbitrary::{Arbitrary, Unstructured};
291
    ///
292
    /// let mut u = Unstructured::new(&[1, 2, 3, 4]);
293
    ///
294
    /// let x: i32 = u.int_in_range(-5_000..=-1_000)?;
295
    ///
296
    /// assert!(-5_000 <= x);
297
    /// assert!(x <= -1_000);
298
    /// # Ok(()) }
299
    /// ```
300
18.4M
    pub fn int_in_range<T>(&mut self, range: ops::RangeInclusive<T>) -> Result<T>
301
18.4M
    where
302
18.4M
        T: Int,
303
    {
304
18.4M
        let (result, bytes_consumed) = Self::int_in_range_impl(range, self.data.iter().cloned())?;
305
18.4M
        self.data = &self.data[bytes_consumed..];
306
18.4M
        Ok(result)
307
18.4M
    }
<arbitrary::unstructured::Unstructured>::int_in_range::<u8>
Line
Count
Source
300
7.13M
    pub fn int_in_range<T>(&mut self, range: ops::RangeInclusive<T>) -> Result<T>
301
7.13M
    where
302
7.13M
        T: Int,
303
    {
304
7.13M
        let (result, bytes_consumed) = Self::int_in_range_impl(range, self.data.iter().cloned())?;
305
7.13M
        self.data = &self.data[bytes_consumed..];
306
7.13M
        Ok(result)
307
7.13M
    }
<arbitrary::unstructured::Unstructured>::int_in_range::<i32>
Line
Count
Source
300
11.2M
    pub fn int_in_range<T>(&mut self, range: ops::RangeInclusive<T>) -> Result<T>
301
11.2M
    where
302
11.2M
        T: Int,
303
    {
304
11.2M
        let (result, bytes_consumed) = Self::int_in_range_impl(range, self.data.iter().cloned())?;
305
11.2M
        self.data = &self.data[bytes_consumed..];
306
11.2M
        Ok(result)
307
11.2M
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::int_in_range::<i64>
<arbitrary::unstructured::Unstructured>::int_in_range::<usize>
Line
Count
Source
300
582
    pub fn int_in_range<T>(&mut self, range: ops::RangeInclusive<T>) -> Result<T>
301
582
    where
302
582
        T: Int,
303
    {
304
582
        let (result, bytes_consumed) = Self::int_in_range_impl(range, self.data.iter().cloned())?;
305
582
        self.data = &self.data[bytes_consumed..];
306
582
        Ok(result)
307
582
    }
<arbitrary::unstructured::Unstructured>::int_in_range::<u32>
Line
Count
Source
300
35
    pub fn int_in_range<T>(&mut self, range: ops::RangeInclusive<T>) -> Result<T>
301
35
    where
302
35
        T: Int,
303
    {
304
35
        let (result, bytes_consumed) = Self::int_in_range_impl(range, self.data.iter().cloned())?;
305
35
        self.data = &self.data[bytes_consumed..];
306
35
        Ok(result)
307
35
    }
308
309
18.7M
    fn int_in_range_impl<T>(
310
18.7M
        range: ops::RangeInclusive<T>,
311
18.7M
        mut bytes: impl Iterator<Item = u8>,
312
18.7M
    ) -> Result<(T, usize)>
313
18.7M
    where
314
18.7M
        T: Int,
315
    {
316
18.7M
        let start = *range.start();
317
18.7M
        let end = *range.end();
318
18.7M
        assert!(
319
18.7M
            start <= end,
320
            "`arbitrary::Unstructured::int_in_range` requires a non-empty range"
321
        );
322
323
        // When there is only one possible choice, don't waste any entropy from
324
        // the underlying data.
325
18.7M
        if start == end {
326
8
            return Ok((start, 0));
327
18.7M
        }
328
329
        // From here on out we work with the unsigned representation. All of the
330
        // operations performed below work out just as well whether or not `T`
331
        // is a signed or unsigned integer.
332
18.7M
        let start = start.to_unsigned();
333
18.7M
        let end = end.to_unsigned();
334
335
18.7M
        let delta = end.wrapping_sub(start);
336
18.7M
        debug_assert_ne!(delta, T::Unsigned::ZERO);
337
338
        // Compute an arbitrary integer offset from the start of the range. We
339
        // do this by consuming `size_of(T)` bytes from the input to create an
340
        // arbitrary integer and then clamping that int into our range bounds
341
        // with a modulo operation.
342
18.7M
        let mut arbitrary_int = T::Unsigned::ZERO;
343
18.7M
        let mut bytes_consumed: usize = 0;
344
345
23.0M
        while (bytes_consumed < mem::size_of::<T>())
346
19.7M
            && (delta >> T::Unsigned::from_usize(bytes_consumed * 8)) > T::Unsigned::ZERO
347
        {
348
19.4M
            let byte = match bytes.next() {
349
15.1M
                None => break,
350
4.31M
                Some(b) => b,
351
            };
352
4.31M
            bytes_consumed += 1;
353
354
            // Combine this byte into our arbitrary integer, but avoid
355
            // overflowing the shift for `u8` and `i8`.
356
4.31M
            arbitrary_int = if mem::size_of::<T>() == 1 {
357
3.26M
                T::Unsigned::from_u8(byte)
358
            } else {
359
1.04M
                (arbitrary_int << 8) | T::Unsigned::from_u8(byte)
360
            };
361
        }
362
363
18.7M
        let offset = if delta == T::Unsigned::MAX {
364
2
            arbitrary_int
365
        } else {
366
18.7M
            arbitrary_int % (delta.checked_add(T::Unsigned::ONE).unwrap())
367
        };
368
369
        // Finally, we add `start` to our offset from `start` to get the result
370
        // actual value within the range.
371
18.7M
        let result = start.wrapping_add(offset);
372
373
        // And convert back to our maybe-signed representation.
374
18.7M
        let result = T::from_unsigned(result);
375
18.7M
        debug_assert!(*range.start() <= result);
376
18.7M
        debug_assert!(result <= *range.end());
377
378
18.7M
        Ok((result, bytes_consumed))
379
18.7M
    }
<arbitrary::unstructured::Unstructured>::int_in_range_impl::<u8, core::iter::adapters::cloned::Cloned<core::slice::iter::Iter<u8>>>
Line
Count
Source
309
7.13M
    fn int_in_range_impl<T>(
310
7.13M
        range: ops::RangeInclusive<T>,
311
7.13M
        mut bytes: impl Iterator<Item = u8>,
312
7.13M
    ) -> Result<(T, usize)>
313
7.13M
    where
314
7.13M
        T: Int,
315
    {
316
7.13M
        let start = *range.start();
317
7.13M
        let end = *range.end();
318
7.13M
        assert!(
319
7.13M
            start <= end,
320
            "`arbitrary::Unstructured::int_in_range` requires a non-empty range"
321
        );
322
323
        // When there is only one possible choice, don't waste any entropy from
324
        // the underlying data.
325
7.13M
        if start == end {
326
0
            return Ok((start, 0));
327
7.13M
        }
328
329
        // From here on out we work with the unsigned representation. All of the
330
        // operations performed below work out just as well whether or not `T`
331
        // is a signed or unsigned integer.
332
7.13M
        let start = start.to_unsigned();
333
7.13M
        let end = end.to_unsigned();
334
335
7.13M
        let delta = end.wrapping_sub(start);
336
7.13M
        debug_assert_ne!(delta, T::Unsigned::ZERO);
337
338
        // Compute an arbitrary integer offset from the start of the range. We
339
        // do this by consuming `size_of(T)` bytes from the input to create an
340
        // arbitrary integer and then clamping that int into our range bounds
341
        // with a modulo operation.
342
7.13M
        let mut arbitrary_int = T::Unsigned::ZERO;
343
7.13M
        let mut bytes_consumed: usize = 0;
344
345
10.4M
        while (bytes_consumed < mem::size_of::<T>())
346
7.13M
            && (delta >> T::Unsigned::from_usize(bytes_consumed * 8)) > T::Unsigned::ZERO
347
        {
348
7.13M
            let byte = match bytes.next() {
349
3.86M
                None => break,
350
3.26M
                Some(b) => b,
351
            };
352
3.26M
            bytes_consumed += 1;
353
354
            // Combine this byte into our arbitrary integer, but avoid
355
            // overflowing the shift for `u8` and `i8`.
356
3.26M
            arbitrary_int = if mem::size_of::<T>() == 1 {
357
3.26M
                T::Unsigned::from_u8(byte)
358
            } else {
359
0
                (arbitrary_int << 8) | T::Unsigned::from_u8(byte)
360
            };
361
        }
362
363
7.13M
        let offset = if delta == T::Unsigned::MAX {
364
0
            arbitrary_int
365
        } else {
366
7.13M
            arbitrary_int % (delta.checked_add(T::Unsigned::ONE).unwrap())
367
        };
368
369
        // Finally, we add `start` to our offset from `start` to get the result
370
        // actual value within the range.
371
7.13M
        let result = start.wrapping_add(offset);
372
373
        // And convert back to our maybe-signed representation.
374
7.13M
        let result = T::from_unsigned(result);
375
7.13M
        debug_assert!(*range.start() <= result);
376
7.13M
        debug_assert!(result <= *range.end());
377
378
7.13M
        Ok((result, bytes_consumed))
379
7.13M
    }
<arbitrary::unstructured::Unstructured>::int_in_range_impl::<i32, core::iter::adapters::cloned::Cloned<core::slice::iter::Iter<u8>>>
Line
Count
Source
309
11.2M
    fn int_in_range_impl<T>(
310
11.2M
        range: ops::RangeInclusive<T>,
311
11.2M
        mut bytes: impl Iterator<Item = u8>,
312
11.2M
    ) -> Result<(T, usize)>
313
11.2M
    where
314
11.2M
        T: Int,
315
    {
316
11.2M
        let start = *range.start();
317
11.2M
        let end = *range.end();
318
11.2M
        assert!(
319
11.2M
            start <= end,
320
            "`arbitrary::Unstructured::int_in_range` requires a non-empty range"
321
        );
322
323
        // When there is only one possible choice, don't waste any entropy from
324
        // the underlying data.
325
11.2M
        if start == end {
326
0
            return Ok((start, 0));
327
11.2M
        }
328
329
        // From here on out we work with the unsigned representation. All of the
330
        // operations performed below work out just as well whether or not `T`
331
        // is a signed or unsigned integer.
332
11.2M
        let start = start.to_unsigned();
333
11.2M
        let end = end.to_unsigned();
334
335
11.2M
        let delta = end.wrapping_sub(start);
336
11.2M
        debug_assert_ne!(delta, T::Unsigned::ZERO);
337
338
        // Compute an arbitrary integer offset from the start of the range. We
339
        // do this by consuming `size_of(T)` bytes from the input to create an
340
        // arbitrary integer and then clamping that int into our range bounds
341
        // with a modulo operation.
342
11.2M
        let mut arbitrary_int = T::Unsigned::ZERO;
343
11.2M
        let mut bytes_consumed: usize = 0;
344
345
11.2M
        while (bytes_consumed < mem::size_of::<T>())
346
11.2M
            && (delta >> T::Unsigned::from_usize(bytes_consumed * 8)) > T::Unsigned::ZERO
347
        {
348
11.2M
            let byte = match bytes.next() {
349
11.2M
                None => break,
350
3.26k
                Some(b) => b,
351
            };
352
3.26k
            bytes_consumed += 1;
353
354
            // Combine this byte into our arbitrary integer, but avoid
355
            // overflowing the shift for `u8` and `i8`.
356
3.26k
            arbitrary_int = if mem::size_of::<T>() == 1 {
357
0
                T::Unsigned::from_u8(byte)
358
            } else {
359
3.26k
                (arbitrary_int << 8) | T::Unsigned::from_u8(byte)
360
            };
361
        }
362
363
11.2M
        let offset = if delta == T::Unsigned::MAX {
364
0
            arbitrary_int
365
        } else {
366
11.2M
            arbitrary_int % (delta.checked_add(T::Unsigned::ONE).unwrap())
367
        };
368
369
        // Finally, we add `start` to our offset from `start` to get the result
370
        // actual value within the range.
371
11.2M
        let result = start.wrapping_add(offset);
372
373
        // And convert back to our maybe-signed representation.
374
11.2M
        let result = T::from_unsigned(result);
375
11.2M
        debug_assert!(*range.start() <= result);
376
11.2M
        debug_assert!(result <= *range.end());
377
378
11.2M
        Ok((result, bytes_consumed))
379
11.2M
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::int_in_range_impl::<i64, core::iter::adapters::cloned::Cloned<core::slice::iter::Iter<u8>>>
<arbitrary::unstructured::Unstructured>::int_in_range_impl::<u8, core::iter::adapters::copied::Copied<core::slice::iter::Iter<u8>>>
Line
Count
Source
309
283
    fn int_in_range_impl<T>(
310
283
        range: ops::RangeInclusive<T>,
311
283
        mut bytes: impl Iterator<Item = u8>,
312
283
    ) -> Result<(T, usize)>
313
283
    where
314
283
        T: Int,
315
    {
316
283
        let start = *range.start();
317
283
        let end = *range.end();
318
283
        assert!(
319
283
            start <= end,
320
            "`arbitrary::Unstructured::int_in_range` requires a non-empty range"
321
        );
322
323
        // When there is only one possible choice, don't waste any entropy from
324
        // the underlying data.
325
283
        if start == end {
326
0
            return Ok((start, 0));
327
283
        }
328
329
        // From here on out we work with the unsigned representation. All of the
330
        // operations performed below work out just as well whether or not `T`
331
        // is a signed or unsigned integer.
332
283
        let start = start.to_unsigned();
333
283
        let end = end.to_unsigned();
334
335
283
        let delta = end.wrapping_sub(start);
336
283
        debug_assert_ne!(delta, T::Unsigned::ZERO);
337
338
        // Compute an arbitrary integer offset from the start of the range. We
339
        // do this by consuming `size_of(T)` bytes from the input to create an
340
        // arbitrary integer and then clamping that int into our range bounds
341
        // with a modulo operation.
342
283
        let mut arbitrary_int = T::Unsigned::ZERO;
343
283
        let mut bytes_consumed: usize = 0;
344
345
566
        while (bytes_consumed < mem::size_of::<T>())
346
283
            && (delta >> T::Unsigned::from_usize(bytes_consumed * 8)) > T::Unsigned::ZERO
347
        {
348
283
            let byte = match bytes.next() {
349
0
                None => break,
350
283
                Some(b) => b,
351
            };
352
283
            bytes_consumed += 1;
353
354
            // Combine this byte into our arbitrary integer, but avoid
355
            // overflowing the shift for `u8` and `i8`.
356
283
            arbitrary_int = if mem::size_of::<T>() == 1 {
357
283
                T::Unsigned::from_u8(byte)
358
            } else {
359
0
                (arbitrary_int << 8) | T::Unsigned::from_u8(byte)
360
            };
361
        }
362
363
283
        let offset = if delta == T::Unsigned::MAX {
364
1
            arbitrary_int
365
        } else {
366
282
            arbitrary_int % (delta.checked_add(T::Unsigned::ONE).unwrap())
367
        };
368
369
        // Finally, we add `start` to our offset from `start` to get the result
370
        // actual value within the range.
371
283
        let result = start.wrapping_add(offset);
372
373
        // And convert back to our maybe-signed representation.
374
283
        let result = T::from_unsigned(result);
375
283
        debug_assert!(*range.start() <= result);
376
283
        debug_assert!(result <= *range.end());
377
378
283
        Ok((result, bytes_consumed))
379
283
    }
<arbitrary::unstructured::Unstructured>::int_in_range_impl::<usize, core::iter::adapters::cloned::Cloned<core::slice::iter::Iter<u8>>>
Line
Count
Source
309
582
    fn int_in_range_impl<T>(
310
582
        range: ops::RangeInclusive<T>,
311
582
        mut bytes: impl Iterator<Item = u8>,
312
582
    ) -> Result<(T, usize)>
313
582
    where
314
582
        T: Int,
315
    {
316
582
        let start = *range.start();
317
582
        let end = *range.end();
318
582
        assert!(
319
582
            start <= end,
320
            "`arbitrary::Unstructured::int_in_range` requires a non-empty range"
321
        );
322
323
        // When there is only one possible choice, don't waste any entropy from
324
        // the underlying data.
325
582
        if start == end {
326
8
            return Ok((start, 0));
327
574
        }
328
329
        // From here on out we work with the unsigned representation. All of the
330
        // operations performed below work out just as well whether or not `T`
331
        // is a signed or unsigned integer.
332
574
        let start = start.to_unsigned();
333
574
        let end = end.to_unsigned();
334
335
574
        let delta = end.wrapping_sub(start);
336
574
        debug_assert_ne!(delta, T::Unsigned::ZERO);
337
338
        // Compute an arbitrary integer offset from the start of the range. We
339
        // do this by consuming `size_of(T)` bytes from the input to create an
340
        // arbitrary integer and then clamping that int into our range bounds
341
        // with a modulo operation.
342
574
        let mut arbitrary_int = T::Unsigned::ZERO;
343
574
        let mut bytes_consumed: usize = 0;
344
345
1.15k
        while (bytes_consumed < mem::size_of::<T>())
346
1.15k
            && (delta >> T::Unsigned::from_usize(bytes_consumed * 8)) > T::Unsigned::ZERO
347
        {
348
584
            let byte = match bytes.next() {
349
0
                None => break,
350
584
                Some(b) => b,
351
            };
352
584
            bytes_consumed += 1;
353
354
            // Combine this byte into our arbitrary integer, but avoid
355
            // overflowing the shift for `u8` and `i8`.
356
584
            arbitrary_int = if mem::size_of::<T>() == 1 {
357
0
                T::Unsigned::from_u8(byte)
358
            } else {
359
584
                (arbitrary_int << 8) | T::Unsigned::from_u8(byte)
360
            };
361
        }
362
363
574
        let offset = if delta == T::Unsigned::MAX {
364
0
            arbitrary_int
365
        } else {
366
574
            arbitrary_int % (delta.checked_add(T::Unsigned::ONE).unwrap())
367
        };
368
369
        // Finally, we add `start` to our offset from `start` to get the result
370
        // actual value within the range.
371
574
        let result = start.wrapping_add(offset);
372
373
        // And convert back to our maybe-signed representation.
374
574
        let result = T::from_unsigned(result);
375
574
        debug_assert!(*range.start() <= result);
376
574
        debug_assert!(result <= *range.end());
377
378
574
        Ok((result, bytes_consumed))
379
582
    }
<arbitrary::unstructured::Unstructured>::int_in_range_impl::<u32, core::iter::adapters::cloned::Cloned<core::slice::iter::Iter<u8>>>
Line
Count
Source
309
35
    fn int_in_range_impl<T>(
310
35
        range: ops::RangeInclusive<T>,
311
35
        mut bytes: impl Iterator<Item = u8>,
312
35
    ) -> Result<(T, usize)>
313
35
    where
314
35
        T: Int,
315
    {
316
35
        let start = *range.start();
317
35
        let end = *range.end();
318
35
        assert!(
319
35
            start <= end,
320
            "`arbitrary::Unstructured::int_in_range` requires a non-empty range"
321
        );
322
323
        // When there is only one possible choice, don't waste any entropy from
324
        // the underlying data.
325
35
        if start == end {
326
0
            return Ok((start, 0));
327
35
        }
328
329
        // From here on out we work with the unsigned representation. All of the
330
        // operations performed below work out just as well whether or not `T`
331
        // is a signed or unsigned integer.
332
35
        let start = start.to_unsigned();
333
35
        let end = end.to_unsigned();
334
335
35
        let delta = end.wrapping_sub(start);
336
35
        debug_assert_ne!(delta, T::Unsigned::ZERO);
337
338
        // Compute an arbitrary integer offset from the start of the range. We
339
        // do this by consuming `size_of(T)` bytes from the input to create an
340
        // arbitrary integer and then clamping that int into our range bounds
341
        // with a modulo operation.
342
35
        let mut arbitrary_int = T::Unsigned::ZERO;
343
35
        let mut bytes_consumed: usize = 0;
344
345
140
        while (bytes_consumed < mem::size_of::<T>())
346
120
            && (delta >> T::Unsigned::from_usize(bytes_consumed * 8)) > T::Unsigned::ZERO
347
        {
348
105
            let byte = match bytes.next() {
349
0
                None => break,
350
105
                Some(b) => b,
351
            };
352
105
            bytes_consumed += 1;
353
354
            // Combine this byte into our arbitrary integer, but avoid
355
            // overflowing the shift for `u8` and `i8`.
356
105
            arbitrary_int = if mem::size_of::<T>() == 1 {
357
0
                T::Unsigned::from_u8(byte)
358
            } else {
359
105
                (arbitrary_int << 8) | T::Unsigned::from_u8(byte)
360
            };
361
        }
362
363
35
        let offset = if delta == T::Unsigned::MAX {
364
0
            arbitrary_int
365
        } else {
366
35
            arbitrary_int % (delta.checked_add(T::Unsigned::ONE).unwrap())
367
        };
368
369
        // Finally, we add `start` to our offset from `start` to get the result
370
        // actual value within the range.
371
35
        let result = start.wrapping_add(offset);
372
373
        // And convert back to our maybe-signed representation.
374
35
        let result = T::from_unsigned(result);
375
35
        debug_assert!(*range.start() <= result);
376
35
        debug_assert!(result <= *range.end());
377
378
35
        Ok((result, bytes_consumed))
379
35
    }
<arbitrary::unstructured::Unstructured>::int_in_range_impl::<u32, core::iter::adapters::copied::Copied<core::slice::iter::Iter<u8>>>
Line
Count
Source
309
317k
    fn int_in_range_impl<T>(
310
317k
        range: ops::RangeInclusive<T>,
311
317k
        mut bytes: impl Iterator<Item = u8>,
312
317k
    ) -> Result<(T, usize)>
313
317k
    where
314
317k
        T: Int,
315
    {
316
317k
        let start = *range.start();
317
317k
        let end = *range.end();
318
317k
        assert!(
319
317k
            start <= end,
320
            "`arbitrary::Unstructured::int_in_range` requires a non-empty range"
321
        );
322
323
        // When there is only one possible choice, don't waste any entropy from
324
        // the underlying data.
325
317k
        if start == end {
326
0
            return Ok((start, 0));
327
317k
        }
328
329
        // From here on out we work with the unsigned representation. All of the
330
        // operations performed below work out just as well whether or not `T`
331
        // is a signed or unsigned integer.
332
317k
        let start = start.to_unsigned();
333
317k
        let end = end.to_unsigned();
334
335
317k
        let delta = end.wrapping_sub(start);
336
317k
        debug_assert_ne!(delta, T::Unsigned::ZERO);
337
338
        // Compute an arbitrary integer offset from the start of the range. We
339
        // do this by consuming `size_of(T)` bytes from the input to create an
340
        // arbitrary integer and then clamping that int into our range bounds
341
        // with a modulo operation.
342
317k
        let mut arbitrary_int = T::Unsigned::ZERO;
343
317k
        let mut bytes_consumed: usize = 0;
344
345
1.26M
        while (bytes_consumed < mem::size_of::<T>())
346
1.26M
            && (delta >> T::Unsigned::from_usize(bytes_consumed * 8)) > T::Unsigned::ZERO
347
        {
348
952k
            let byte = match bytes.next() {
349
0
                None => break,
350
952k
                Some(b) => b,
351
            };
352
952k
            bytes_consumed += 1;
353
354
            // Combine this byte into our arbitrary integer, but avoid
355
            // overflowing the shift for `u8` and `i8`.
356
952k
            arbitrary_int = if mem::size_of::<T>() == 1 {
357
0
                T::Unsigned::from_u8(byte)
358
            } else {
359
952k
                (arbitrary_int << 8) | T::Unsigned::from_u8(byte)
360
            };
361
        }
362
363
317k
        let offset = if delta == T::Unsigned::MAX {
364
0
            arbitrary_int
365
        } else {
366
317k
            arbitrary_int % (delta.checked_add(T::Unsigned::ONE).unwrap())
367
        };
368
369
        // Finally, we add `start` to our offset from `start` to get the result
370
        // actual value within the range.
371
317k
        let result = start.wrapping_add(offset);
372
373
        // And convert back to our maybe-signed representation.
374
317k
        let result = T::from_unsigned(result);
375
317k
        debug_assert!(*range.start() <= result);
376
317k
        debug_assert!(result <= *range.end());
377
378
317k
        Ok((result, bytes_consumed))
379
317k
    }
<arbitrary::unstructured::Unstructured>::int_in_range_impl::<u16, core::iter::adapters::copied::Copied<core::slice::iter::Iter<u8>>>
Line
Count
Source
309
43.7k
    fn int_in_range_impl<T>(
310
43.7k
        range: ops::RangeInclusive<T>,
311
43.7k
        mut bytes: impl Iterator<Item = u8>,
312
43.7k
    ) -> Result<(T, usize)>
313
43.7k
    where
314
43.7k
        T: Int,
315
    {
316
43.7k
        let start = *range.start();
317
43.7k
        let end = *range.end();
318
43.7k
        assert!(
319
43.7k
            start <= end,
320
            "`arbitrary::Unstructured::int_in_range` requires a non-empty range"
321
        );
322
323
        // When there is only one possible choice, don't waste any entropy from
324
        // the underlying data.
325
43.7k
        if start == end {
326
0
            return Ok((start, 0));
327
43.7k
        }
328
329
        // From here on out we work with the unsigned representation. All of the
330
        // operations performed below work out just as well whether or not `T`
331
        // is a signed or unsigned integer.
332
43.7k
        let start = start.to_unsigned();
333
43.7k
        let end = end.to_unsigned();
334
335
43.7k
        let delta = end.wrapping_sub(start);
336
43.7k
        debug_assert_ne!(delta, T::Unsigned::ZERO);
337
338
        // Compute an arbitrary integer offset from the start of the range. We
339
        // do this by consuming `size_of(T)` bytes from the input to create an
340
        // arbitrary integer and then clamping that int into our range bounds
341
        // with a modulo operation.
342
43.7k
        let mut arbitrary_int = T::Unsigned::ZERO;
343
43.7k
        let mut bytes_consumed: usize = 0;
344
345
131k
        while (bytes_consumed < mem::size_of::<T>())
346
87.4k
            && (delta >> T::Unsigned::from_usize(bytes_consumed * 8)) > T::Unsigned::ZERO
347
        {
348
87.4k
            let byte = match bytes.next() {
349
0
                None => break,
350
87.4k
                Some(b) => b,
351
            };
352
87.4k
            bytes_consumed += 1;
353
354
            // Combine this byte into our arbitrary integer, but avoid
355
            // overflowing the shift for `u8` and `i8`.
356
87.4k
            arbitrary_int = if mem::size_of::<T>() == 1 {
357
0
                T::Unsigned::from_u8(byte)
358
            } else {
359
87.4k
                (arbitrary_int << 8) | T::Unsigned::from_u8(byte)
360
            };
361
        }
362
363
43.7k
        let offset = if delta == T::Unsigned::MAX {
364
1
            arbitrary_int
365
        } else {
366
43.7k
            arbitrary_int % (delta.checked_add(T::Unsigned::ONE).unwrap())
367
        };
368
369
        // Finally, we add `start` to our offset from `start` to get the result
370
        // actual value within the range.
371
43.7k
        let result = start.wrapping_add(offset);
372
373
        // And convert back to our maybe-signed representation.
374
43.7k
        let result = T::from_unsigned(result);
375
43.7k
        debug_assert!(*range.start() <= result);
376
43.7k
        debug_assert!(result <= *range.end());
377
378
43.7k
        Ok((result, bytes_consumed))
379
43.7k
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::int_in_range_impl::<u64, core::iter::adapters::copied::Copied<core::slice::iter::Iter<u8>>>
380
381
    /// Choose one of the given choices.
382
    ///
383
    /// This should only be used inside of `Arbitrary` implementations.
384
    ///
385
    /// The probability distribution of choices is not necessarily uniform.
386
    ///
387
    /// Returns the first choice, not an error,
388
    /// if this `Unstructured` [is empty][Unstructured::is_empty].
389
    ///
390
    /// Returns an error if no choices are provided.
391
    ///
392
    /// # Examples
393
    ///
394
    /// Selecting from an array of choices:
395
    ///
396
    /// ```
397
    /// use arbitrary::Unstructured;
398
    ///
399
    /// let mut u = Unstructured::new(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]);
400
    /// let choices = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
401
    ///
402
    /// let choice = u.choose(&choices).unwrap();
403
    ///
404
    /// println!("chose {}", choice);
405
    /// ```
406
    ///
407
    /// An error is returned if no choices are provided:
408
    ///
409
    /// ```
410
    /// use arbitrary::Unstructured;
411
    ///
412
    /// let mut u = Unstructured::new(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]);
413
    /// let choices: [char; 0] = [];
414
    ///
415
    /// let result = u.choose(&choices);
416
    ///
417
    /// assert!(result.is_err());
418
    /// ```
419
8
    pub fn choose<'b, T>(&mut self, choices: &'b [T]) -> Result<&'b T> {
420
8
        let idx = self.choose_index(choices.len())?;
421
8
        Ok(&choices[idx])
422
8
    }
<arbitrary::unstructured::Unstructured>::choose::<surrealdb_core::sql::field::Field>
Line
Count
Source
419
8
    pub fn choose<'b, T>(&mut self, choices: &'b [T]) -> Result<&'b T> {
420
8
        let idx = self.choose_index(choices.len())?;
421
8
        Ok(&choices[idx])
422
8
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::choose::<_>
423
424
    /// Choose one of the given iterator choices.
425
    ///
426
    /// This should only be used inside of `Arbitrary` implementations.
427
    ///
428
    /// The probability distribution of choices is not necessarily uniform.
429
    ///
430
    /// Returns the first choice, not an error,
431
    /// if this `Unstructured` [is empty][Unstructured::is_empty].
432
    ///
433
    /// Returns an error if no choices are provided.
434
    ///
435
    /// # Examples
436
    ///
437
    /// Selecting a random item from a set:
438
    ///
439
    /// ```
440
    /// use std::collections::BTreeSet;
441
    /// use arbitrary::Unstructured;
442
    ///
443
    /// let mut u = Unstructured::new(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]);
444
    /// let set = BTreeSet::from(['a', 'b', 'c']);
445
    ///
446
    /// let choice = u.choose_iter(set.iter()).unwrap();
447
    ///
448
    /// println!("chose {}", choice);
449
    /// ```
450
0
    pub fn choose_iter<T, I>(&mut self, choices: I) -> Result<T>
451
0
    where
452
0
        I: IntoIterator<Item = T>,
453
0
        I::IntoIter: ExactSizeIterator,
454
    {
455
0
        let mut choices = choices.into_iter();
456
0
        let idx = self.choose_index(choices.len())?;
457
0
        let choice = choices
458
0
            .nth(idx)
459
0
            .expect("ExactSizeIterator should have correct len");
460
0
        Ok(choice)
461
0
    }
462
463
    /// Choose a value in `0..len`.
464
    ///
465
    /// The probability distribution of return values is not necessarily uniform.
466
    ///
467
    /// Returns zero, not an error, if this `Unstructured` [is empty][Unstructured::is_empty].
468
    ///
469
    /// Returns an error if the `len` is zero.
470
    ///
471
    /// # Examples
472
    ///
473
    /// Using Fisher–Yates shuffle shuffle to generate an arbitrary permutation.
474
    ///
475
    /// [Fisher–Yates shuffle]: https://en.wikipedia.org/wiki/Fisher–Yates_shuffle
476
    ///
477
    /// ```
478
    /// use arbitrary::Unstructured;
479
    ///
480
    /// let mut u = Unstructured::new(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]);
481
    /// let mut permutation = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
482
    /// let mut to_permute = &mut permutation[..];
483
    /// while to_permute.len() > 1 {
484
    ///     let idx = u.choose_index(to_permute.len()).unwrap();
485
    ///     to_permute.swap(0, idx);
486
    ///     to_permute = &mut to_permute[1..];
487
    /// }
488
    ///
489
    /// println!("permutation: {:?}", permutation);
490
    /// ```
491
    ///
492
    /// An error is returned if the length is zero:
493
    ///
494
    /// ```
495
    /// use arbitrary::Unstructured;
496
    ///
497
    /// let mut u = Unstructured::new(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]);
498
    /// let array: [i32; 0] = [];
499
    ///
500
    /// let result = u.choose_index(array.len());
501
    ///
502
    /// assert!(result.is_err());
503
    /// ```
504
572
    pub fn choose_index(&mut self, len: usize) -> Result<usize> {
505
572
        if len == 0 {
506
0
            return Err(Error::EmptyChoose);
507
572
        }
508
572
        let idx = self.int_in_range(0..=len - 1)?;
509
572
        Ok(idx)
510
572
    }
511
512
    /// Generate a boolean which is true with probability approximately the given ratio.
513
    ///
514
    /// Returns true, not an error, if this `Unstructured` [is empty][Unstructured::is_empty].
515
    ///
516
    /// # Panics
517
    ///
518
    /// Panics when the numerator and denominator do not meet these constraints:
519
    ///
520
    /// * `0 < numerator <= denominator`
521
    ///
522
    /// # Example
523
    ///
524
    /// Generate a boolean that is `true` five sevenths of the time:
525
    ///
526
    /// ```
527
    /// # fn foo() -> arbitrary::Result<()> {
528
    /// use arbitrary::Unstructured;
529
    ///
530
    /// # let my_data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
531
    /// let mut u = Unstructured::new(&my_data);
532
    ///
533
    /// if u.ratio(5, 7)? {
534
    ///     // Take this branch approximately 5/7 of the time.
535
    /// }
536
    /// # Ok(())
537
    /// # }
538
    /// ```
539
0
    pub fn ratio<T>(&mut self, numerator: T, denominator: T) -> Result<bool>
540
0
    where
541
0
        T: Int,
542
    {
543
0
        assert!(T::ZERO < numerator);
544
0
        assert!(numerator <= denominator);
545
0
        let x = self.int_in_range(T::ONE..=denominator)?;
546
0
        Ok(x <= numerator)
547
0
    }
548
549
    /// Fill a `buffer` with bytes from the underlying raw data.
550
    ///
551
    /// This should only be called within an `Arbitrary` implementation. This is
552
    /// a very low-level operation. You should generally prefer calling nested
553
    /// `Arbitrary` implementations like `<Vec<u8>>::arbitrary` and
554
    /// `String::arbitrary` over using this method directly.
555
    ///
556
    /// If this `Unstructured` does not have enough underlying data to fill the
557
    /// whole `buffer`, it pads the buffer out with zeros.
558
    ///
559
    /// # Example
560
    ///
561
    /// ```
562
    /// use arbitrary::Unstructured;
563
    ///
564
    /// let mut u = Unstructured::new(&[1, 2, 3, 4]);
565
    ///
566
    /// let mut buf = [0; 2];
567
    ///
568
    /// assert!(u.fill_buffer(&mut buf).is_ok());
569
    /// assert_eq!(buf, [1, 2]);
570
    ///
571
    /// assert!(u.fill_buffer(&mut buf).is_ok());
572
    /// assert_eq!(buf, [3, 4]);
573
    ///
574
    /// assert!(u.fill_buffer(&mut buf).is_ok());
575
    /// assert_eq!(buf, [0, 0]);
576
    /// ```
577
26.5M
    pub fn fill_buffer(&mut self, buffer: &mut [u8]) -> Result<()> {
578
26.5M
        let n = std::cmp::min(buffer.len(), self.data.len());
579
26.5M
        buffer[..n].copy_from_slice(&self.data[..n]);
580
100M
        for byte in buffer[n..].iter_mut() {
581
100M
            *byte = 0;
582
100M
        }
583
26.5M
        self.data = &self.data[n..];
584
26.5M
        Ok(())
585
26.5M
    }
586
587
    /// Provide `size` bytes from the underlying raw data.
588
    ///
589
    /// This should only be called within an `Arbitrary` implementation. This is
590
    /// a very low-level operation. You should generally prefer calling nested
591
    /// `Arbitrary` implementations like `<Vec<u8>>::arbitrary` and
592
    /// `String::arbitrary` over using this method directly.
593
    ///
594
    /// # Example
595
    ///
596
    /// ```
597
    /// use arbitrary::Unstructured;
598
    ///
599
    /// let mut u = Unstructured::new(&[1, 2, 3, 4]);
600
    ///
601
    /// assert!(u.bytes(2).unwrap() == &[1, 2]);
602
    /// assert!(u.bytes(2).unwrap() == &[3, 4]);
603
    /// ```
604
5.02M
    pub fn bytes(&mut self, size: usize) -> Result<&'a [u8]> {
605
5.02M
        if self.data.len() < size {
606
0
            return Err(Error::NotEnoughData);
607
5.02M
        }
608
609
5.02M
        let (for_buf, rest) = self.data.split_at(size);
610
5.02M
        self.data = rest;
611
5.02M
        Ok(for_buf)
612
5.02M
    }
613
614
    /// Peek at `size` number of bytes of the underlying raw input.
615
    ///
616
    /// Does not consume the bytes, only peeks at them.
617
    ///
618
    /// Returns `None` if there are not `size` bytes left in the underlying raw
619
    /// input.
620
    ///
621
    /// # Example
622
    ///
623
    /// ```
624
    /// use arbitrary::Unstructured;
625
    ///
626
    /// let u = Unstructured::new(&[1, 2, 3]);
627
    ///
628
    /// assert_eq!(u.peek_bytes(0).unwrap(), []);
629
    /// assert_eq!(u.peek_bytes(1).unwrap(), [1]);
630
    /// assert_eq!(u.peek_bytes(2).unwrap(), [1, 2]);
631
    /// assert_eq!(u.peek_bytes(3).unwrap(), [1, 2, 3]);
632
    ///
633
    /// assert!(u.peek_bytes(4).is_none());
634
    /// ```
635
5.01M
    pub fn peek_bytes(&self, size: usize) -> Option<&'a [u8]> {
636
5.01M
        self.data.get(..size)
637
5.01M
    }
638
639
    /// Consume all of the rest of the remaining underlying bytes.
640
    ///
641
    /// Returns a slice of all the remaining, unconsumed bytes.
642
    ///
643
    /// # Example
644
    ///
645
    /// ```
646
    /// use arbitrary::Unstructured;
647
    ///
648
    /// let mut u = Unstructured::new(&[1, 2, 3]);
649
    ///
650
    /// let mut remaining = u.take_rest();
651
    ///
652
    /// assert_eq!(remaining, [1, 2, 3]);
653
    /// ```
654
0
    pub fn take_rest(mut self) -> &'a [u8] {
655
0
        mem::take(&mut self.data)
656
0
    }
657
658
    /// Provide an iterator over elements for constructing a collection
659
    ///
660
    /// This is useful for implementing [`Arbitrary::arbitrary`] on collections
661
    /// since the implementation is simply `u.arbitrary_iter()?.collect()`
662
25.2k
    pub fn arbitrary_iter<'b, ElementType: Arbitrary<'a>>(
663
25.2k
        &'b mut self,
664
25.2k
    ) -> Result<ArbitraryIter<'a, 'b, ElementType>> {
665
25.2k
        Ok(ArbitraryIter {
666
25.2k
            u: &mut *self,
667
25.2k
            _marker: PhantomData,
668
25.2k
        })
669
25.2k
    }
<arbitrary::unstructured::Unstructured>::arbitrary_iter::<alloc::string::String>
Line
Count
Source
662
1.11k
    pub fn arbitrary_iter<'b, ElementType: Arbitrary<'a>>(
663
1.11k
        &'b mut self,
664
1.11k
    ) -> Result<ArbitraryIter<'a, 'b, ElementType>> {
665
1.11k
        Ok(ArbitraryIter {
666
1.11k
            u: &mut *self,
667
1.11k
            _marker: PhantomData,
668
1.11k
        })
669
1.11k
    }
<arbitrary::unstructured::Unstructured>::arbitrary_iter::<surrealdb_core::sql::expression::Expr>
Line
Count
Source
662
10.0k
    pub fn arbitrary_iter<'b, ElementType: Arbitrary<'a>>(
663
10.0k
        &'b mut self,
664
10.0k
    ) -> Result<ArbitraryIter<'a, 'b, ElementType>> {
665
10.0k
        Ok(ArbitraryIter {
666
10.0k
            u: &mut *self,
667
10.0k
            _marker: PhantomData,
668
10.0k
        })
669
10.0k
    }
<arbitrary::unstructured::Unstructured>::arbitrary_iter::<surrealdb_core::sql::ast::TopLevelExpr>
Line
Count
Source
662
41
    pub fn arbitrary_iter<'b, ElementType: Arbitrary<'a>>(
663
41
        &'b mut self,
664
41
    ) -> Result<ArbitraryIter<'a, 'b, ElementType>> {
665
41
        Ok(ArbitraryIter {
666
41
            u: &mut *self,
667
41
            _marker: PhantomData,
668
41
        })
669
41
    }
<arbitrary::unstructured::Unstructured>::arbitrary_iter::<surrealdb_core::sql::kind::GeometryKind>
Line
Count
Source
662
1
    pub fn arbitrary_iter<'b, ElementType: Arbitrary<'a>>(
663
1
        &'b mut self,
664
1
    ) -> Result<ArbitraryIter<'a, 'b, ElementType>> {
665
1
        Ok(ArbitraryIter {
666
1
            u: &mut *self,
667
1
            _marker: PhantomData,
668
1
        })
669
1
    }
<arbitrary::unstructured::Unstructured>::arbitrary_iter::<surrealdb_core::sql::kind::Kind>
Line
Count
Source
662
3
    pub fn arbitrary_iter<'b, ElementType: Arbitrary<'a>>(
663
3
        &'b mut self,
664
3
    ) -> Result<ArbitraryIter<'a, 'b, ElementType>> {
665
3
        Ok(ArbitraryIter {
666
3
            u: &mut *self,
667
3
            _marker: PhantomData,
668
3
        })
669
3
    }
<arbitrary::unstructured::Unstructured>::arbitrary_iter::<surrealdb_core::sql::part::DestructurePart>
Line
Count
Source
662
548
    pub fn arbitrary_iter<'b, ElementType: Arbitrary<'a>>(
663
548
        &'b mut self,
664
548
    ) -> Result<ArbitraryIter<'a, 'b, ElementType>> {
665
548
        Ok(ArbitraryIter {
666
548
            u: &mut *self,
667
548
            _marker: PhantomData,
668
548
        })
669
548
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_iter::<surrealdb_core::sql::filter::Filter>
<arbitrary::unstructured::Unstructured>::arbitrary_iter::<surrealdb_core::sql::lookup::LookupSubject>
Line
Count
Source
662
42
    pub fn arbitrary_iter<'b, ElementType: Arbitrary<'a>>(
663
42
        &'b mut self,
664
42
    ) -> Result<ArbitraryIter<'a, 'b, ElementType>> {
665
42
        Ok(ArbitraryIter {
666
42
            u: &mut *self,
667
42
            _marker: PhantomData,
668
42
        })
669
42
    }
<arbitrary::unstructured::Unstructured>::arbitrary_iter::<surrealdb_core::sql::literal::ObjectEntry>
Line
Count
Source
662
86
    pub fn arbitrary_iter<'b, ElementType: Arbitrary<'a>>(
663
86
        &'b mut self,
664
86
    ) -> Result<ArbitraryIter<'a, 'b, ElementType>> {
665
86
        Ok(ArbitraryIter {
666
86
            u: &mut *self,
667
86
            _marker: PhantomData,
668
86
        })
669
86
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_iter::<surrealdb_core::sql::tokenizer::Tokenizer>
<arbitrary::unstructured::Unstructured>::arbitrary_iter::<surrealdb_core::val::table::TableName>
Line
Count
Source
662
160
    pub fn arbitrary_iter<'b, ElementType: Arbitrary<'a>>(
663
160
        &'b mut self,
664
160
    ) -> Result<ArbitraryIter<'a, 'b, ElementType>> {
665
160
        Ok(ArbitraryIter {
666
160
            u: &mut *self,
667
160
            _marker: PhantomData,
668
160
        })
669
160
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_iter::<surrealdb_core::val::geometry::Geometry>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_iter::<surrealdb_core::iam::entities::roles::Role>
<arbitrary::unstructured::Unstructured>::arbitrary_iter::<surrealdb_core::sql::statements::alter::api::AlterApiClause>
Line
Count
Source
662
2
    pub fn arbitrary_iter<'b, ElementType: Arbitrary<'a>>(
663
2
        &'b mut self,
664
2
    ) -> Result<ArbitraryIter<'a, 'b, ElementType>> {
665
2
        Ok(ArbitraryIter {
666
2
            u: &mut *self,
667
2
            _marker: PhantomData,
668
2
        })
669
2
    }
<arbitrary::unstructured::Unstructured>::arbitrary_iter::<surrealdb_core::sql::statements::define::api::ApiAction>
Line
Count
Source
662
1
    pub fn arbitrary_iter<'b, ElementType: Arbitrary<'a>>(
663
1
        &'b mut self,
664
1
    ) -> Result<ArbitraryIter<'a, 'b, ElementType>> {
665
1
        Ok(ArbitraryIter {
666
1
            u: &mut *self,
667
1
            _marker: PhantomData,
668
1
        })
669
1
    }
<arbitrary::unstructured::Unstructured>::arbitrary_iter::<surrealdb_core::sql::statements::define::config::api::Middleware>
Line
Count
Source
662
1
    pub fn arbitrary_iter<'b, ElementType: Arbitrary<'a>>(
663
1
        &'b mut self,
664
1
    ) -> Result<ArbitraryIter<'a, 'b, ElementType>> {
665
1
        Ok(ArbitraryIter {
666
1
            u: &mut *self,
667
1
            _marker: PhantomData,
668
1
        })
669
1
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_iter::<(surrealdb_strand::Strand, surrealdb_core::sql::kind::Kind)>
<arbitrary::unstructured::Unstructured>::arbitrary_iter::<(alloc::string::String, surrealdb_core::sql::kind::Kind)>
Line
Count
Source
662
1
    pub fn arbitrary_iter<'b, ElementType: Arbitrary<'a>>(
663
1
        &'b mut self,
664
1
    ) -> Result<ArbitraryIter<'a, 'b, ElementType>> {
665
1
        Ok(ArbitraryIter {
666
1
            u: &mut *self,
667
1
            _marker: PhantomData,
668
1
        })
669
1
    }
<arbitrary::unstructured::Unstructured>::arbitrary_iter::<(surrealdb_core::sql::param::Param, surrealdb_core::sql::kind::Kind)>
Line
Count
Source
662
9.85k
    pub fn arbitrary_iter<'b, ElementType: Arbitrary<'a>>(
663
9.85k
        &'b mut self,
664
9.85k
    ) -> Result<ArbitraryIter<'a, 'b, ElementType>> {
665
9.85k
        Ok(ArbitraryIter {
666
9.85k
            u: &mut *self,
667
9.85k
            _marker: PhantomData,
668
9.85k
        })
669
9.85k
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_iter::<surrealdb_types::value::Value>
<arbitrary::unstructured::Unstructured>::arbitrary_iter::<geo_types::geometry::line_string::LineString>
Line
Count
Source
662
2
    pub fn arbitrary_iter<'b, ElementType: Arbitrary<'a>>(
663
2
        &'b mut self,
664
2
    ) -> Result<ArbitraryIter<'a, 'b, ElementType>> {
665
2
        Ok(ArbitraryIter {
666
2
            u: &mut *self,
667
2
            _marker: PhantomData,
668
2
        })
669
2
    }
<arbitrary::unstructured::Unstructured>::arbitrary_iter::<geo_types::geometry::coord::Coord>
Line
Count
Source
662
5
    pub fn arbitrary_iter<'b, ElementType: Arbitrary<'a>>(
663
5
        &'b mut self,
664
5
    ) -> Result<ArbitraryIter<'a, 'b, ElementType>> {
665
5
        Ok(ArbitraryIter {
666
5
            u: &mut *self,
667
5
            _marker: PhantomData,
668
5
        })
669
5
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_iter::<geo_types::geometry::point::Point>
<arbitrary::unstructured::Unstructured>::arbitrary_iter::<geo_types::geometry::polygon::Polygon>
Line
Count
Source
662
2
    pub fn arbitrary_iter<'b, ElementType: Arbitrary<'a>>(
663
2
        &'b mut self,
664
2
    ) -> Result<ArbitraryIter<'a, 'b, ElementType>> {
665
2
        Ok(ArbitraryIter {
666
2
            u: &mut *self,
667
2
            _marker: PhantomData,
668
2
        })
669
2
    }
<arbitrary::unstructured::Unstructured>::arbitrary_iter::<surrealdb_types::value::geometry::Geometry>
Line
Count
Source
662
1
    pub fn arbitrary_iter<'b, ElementType: Arbitrary<'a>>(
663
1
        &'b mut self,
664
1
    ) -> Result<ArbitraryIter<'a, 'b, ElementType>> {
665
1
        Ok(ArbitraryIter {
666
1
            u: &mut *self,
667
1
            _marker: PhantomData,
668
1
        })
669
1
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_iter::<(alloc::string::String, surrealdb_types::value::Value)>
<arbitrary::unstructured::Unstructured>::arbitrary_iter::<regex_syntax::ast::ClassSetItem>
Line
Count
Source
662
3.34k
    pub fn arbitrary_iter<'b, ElementType: Arbitrary<'a>>(
663
3.34k
        &'b mut self,
664
3.34k
    ) -> Result<ArbitraryIter<'a, 'b, ElementType>> {
665
3.34k
        Ok(ArbitraryIter {
666
3.34k
            u: &mut *self,
667
3.34k
            _marker: PhantomData,
668
3.34k
        })
669
3.34k
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_iter::<regex_syntax::ast::Ast>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_iter::<regex_syntax::ast::Comment>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_iter::<regex_syntax::ast::FlagsItem>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_iter::<u8>
670
671
    /// Provide an iterator over elements for constructing a collection from
672
    /// all the remaining bytes.
673
    ///
674
    /// This is useful for implementing [`Arbitrary::arbitrary_take_rest`] on collections
675
    /// since the implementation is simply `u.arbitrary_take_rest_iter()?.collect()`
676
0
    pub fn arbitrary_take_rest_iter<ElementType: Arbitrary<'a>>(
677
0
        self,
678
0
    ) -> Result<ArbitraryTakeRestIter<'a, ElementType>> {
679
0
        Ok(ArbitraryTakeRestIter {
680
0
            u: self,
681
0
            _marker: PhantomData,
682
0
        })
683
0
    }
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_take_rest_iter::<alloc::string::String>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_take_rest_iter::<surrealdb_core::sql::expression::Expr>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_take_rest_iter::<surrealdb_core::sql::kind::GeometryKind>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_take_rest_iter::<surrealdb_core::sql::kind::Kind>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_take_rest_iter::<surrealdb_core::sql::part::DestructurePart>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_take_rest_iter::<surrealdb_core::sql::literal::ObjectEntry>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_take_rest_iter::<surrealdb_core::val::table::TableName>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_take_rest_iter::<surrealdb_core::val::geometry::Geometry>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_take_rest_iter::<surrealdb_core::iam::entities::roles::Role>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_take_rest_iter::<(surrealdb_strand::Strand, surrealdb_core::sql::kind::Kind)>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_take_rest_iter::<surrealdb_types::value::Value>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_take_rest_iter::<surrealdb_types::value::geometry::Geometry>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_take_rest_iter::<(alloc::string::String, surrealdb_types::value::Value)>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_take_rest_iter::<regex_syntax::ast::ClassSetItem>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_take_rest_iter::<regex_syntax::ast::Ast>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_take_rest_iter::<regex_syntax::ast::Comment>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_take_rest_iter::<regex_syntax::ast::FlagsItem>
Unexecuted instantiation: <arbitrary::unstructured::Unstructured>::arbitrary_take_rest_iter::<_>
684
685
    /// Call the given function an arbitrary number of times.
686
    ///
687
    /// The function is given this `Unstructured` so that it can continue to
688
    /// generate arbitrary data and structures.
689
    ///
690
    /// You may optionaly specify minimum and maximum bounds on the number of
691
    /// times the function is called.
692
    ///
693
    /// You may break out of the loop early by returning
694
    /// `Ok(std::ops::ControlFlow::Break)`. To continue the loop, return
695
    /// `Ok(std::ops::ControlFlow::Continue)`.
696
    ///
697
    /// # Panics
698
    ///
699
    /// Panics if `min > max`.
700
    ///
701
    /// # Example
702
    ///
703
    /// Call a closure that generates an arbitrary type inside a context an
704
    /// arbitrary number of times:
705
    ///
706
    /// ```
707
    /// use arbitrary::{Result, Unstructured};
708
    /// use std::ops::ControlFlow;
709
    ///
710
    /// enum Type {
711
    ///     /// A boolean type.
712
    ///     Bool,
713
    ///
714
    ///     /// An integer type.
715
    ///     Int,
716
    ///
717
    ///     /// A list of the `i`th type in this type's context.
718
    ///     List(usize),
719
    /// }
720
    ///
721
    /// fn arbitrary_types_context(u: &mut Unstructured) -> Result<Vec<Type>> {
722
    ///     let mut context = vec![];
723
    ///
724
    ///     u.arbitrary_loop(Some(10), Some(20), |u| {
725
    ///         let num_choices = if context.is_empty() {
726
    ///             2
727
    ///         } else {
728
    ///             3
729
    ///         };
730
    ///         let ty = match u.int_in_range::<u8>(1..=num_choices)? {
731
    ///             1 => Type::Bool,
732
    ///             2 => Type::Int,
733
    ///             3 => Type::List(u.int_in_range(0..=context.len() - 1)?),
734
    ///             _ => unreachable!(),
735
    ///         };
736
    ///         context.push(ty);
737
    ///         Ok(ControlFlow::Continue(()))
738
    ///     })?;
739
    ///
740
    ///     // The number of loop iterations are constrained by the min/max
741
    ///     // bounds that we provided.
742
    ///     assert!(context.len() >= 10);
743
    ///     assert!(context.len() <= 20);
744
    ///
745
    ///     Ok(context)
746
    /// }
747
    /// ```
748
0
    pub fn arbitrary_loop(
749
0
        &mut self,
750
0
        min: Option<u32>,
751
0
        max: Option<u32>,
752
0
        mut f: impl FnMut(&mut Self) -> Result<ControlFlow<(), ()>>,
753
0
    ) -> Result<()> {
754
0
        let min = min.unwrap_or(0);
755
0
        let max = max.unwrap_or(u32::MAX);
756
757
0
        for _ in 0..self.int_in_range(min..=max)? {
758
0
            match f(self)? {
759
0
                ControlFlow::Continue(_) => continue,
760
0
                ControlFlow::Break(_) => break,
761
            }
762
        }
763
764
0
        Ok(())
765
0
    }
766
}
767
768
/// Utility iterator produced by [`Unstructured::arbitrary_iter`]
769
pub struct ArbitraryIter<'a, 'b, ElementType> {
770
    u: &'b mut Unstructured<'a>,
771
    _marker: PhantomData<ElementType>,
772
}
773
774
impl<'a, ElementType: Arbitrary<'a>> Iterator for ArbitraryIter<'a, '_, ElementType> {
775
    type Item = Result<ElementType>;
776
346k
    fn next(&mut self) -> Option<Result<ElementType>> {
777
346k
        let keep_going = self.u.arbitrary().unwrap_or(false);
778
346k
        if keep_going {
779
321k
            Some(Arbitrary::arbitrary(self.u))
780
        } else {
781
25.1k
            None
782
        }
783
346k
    }
<arbitrary::unstructured::ArbitraryIter<alloc::string::String> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
776
12.8k
    fn next(&mut self) -> Option<Result<ElementType>> {
777
12.8k
        let keep_going = self.u.arbitrary().unwrap_or(false);
778
12.8k
        if keep_going {
779
11.7k
            Some(Arbitrary::arbitrary(self.u))
780
        } else {
781
1.11k
            None
782
        }
783
12.8k
    }
<arbitrary::unstructured::ArbitraryIter<surrealdb_core::sql::expression::Expr> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
776
40.2k
    fn next(&mut self) -> Option<Result<ElementType>> {
777
40.2k
        let keep_going = self.u.arbitrary().unwrap_or(false);
778
40.2k
        if keep_going {
779
30.2k
            Some(Arbitrary::arbitrary(self.u))
780
        } else {
781
9.99k
            None
782
        }
783
40.2k
    }
<arbitrary::unstructured::ArbitraryIter<surrealdb_core::sql::ast::TopLevelExpr> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
776
217k
    fn next(&mut self) -> Option<Result<ElementType>> {
777
217k
        let keep_going = self.u.arbitrary().unwrap_or(false);
778
217k
        if keep_going {
779
217k
            Some(Arbitrary::arbitrary(self.u))
780
        } else {
781
36
            None
782
        }
783
217k
    }
<arbitrary::unstructured::ArbitraryIter<surrealdb_core::sql::kind::GeometryKind> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
776
1
    fn next(&mut self) -> Option<Result<ElementType>> {
777
1
        let keep_going = self.u.arbitrary().unwrap_or(false);
778
1
        if keep_going {
779
0
            Some(Arbitrary::arbitrary(self.u))
780
        } else {
781
1
            None
782
        }
783
1
    }
<arbitrary::unstructured::ArbitraryIter<surrealdb_core::sql::kind::Kind> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
776
4.27k
    fn next(&mut self) -> Option<Result<ElementType>> {
777
4.27k
        let keep_going = self.u.arbitrary().unwrap_or(false);
778
4.27k
        if keep_going {
779
4.27k
            Some(Arbitrary::arbitrary(self.u))
780
        } else {
781
3
            None
782
        }
783
4.27k
    }
<arbitrary::unstructured::ArbitraryIter<surrealdb_core::sql::part::DestructurePart> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
776
1.13k
    fn next(&mut self) -> Option<Result<ElementType>> {
777
1.13k
        let keep_going = self.u.arbitrary().unwrap_or(false);
778
1.13k
        if keep_going {
779
665
            Some(Arbitrary::arbitrary(self.u))
780
        } else {
781
472
            None
782
        }
783
1.13k
    }
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryIter<surrealdb_core::sql::filter::Filter> as core::iter::traits::iterator::Iterator>::next
<arbitrary::unstructured::ArbitraryIter<surrealdb_core::sql::lookup::LookupSubject> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
776
46
    fn next(&mut self) -> Option<Result<ElementType>> {
777
46
        let keep_going = self.u.arbitrary().unwrap_or(false);
778
46
        if keep_going {
779
4
            Some(Arbitrary::arbitrary(self.u))
780
        } else {
781
42
            None
782
        }
783
46
    }
<arbitrary::unstructured::ArbitraryIter<surrealdb_core::sql::literal::ObjectEntry> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
776
87
    fn next(&mut self) -> Option<Result<ElementType>> {
777
87
        let keep_going = self.u.arbitrary().unwrap_or(false);
778
87
        if keep_going {
779
1
            Some(Arbitrary::arbitrary(self.u))
780
        } else {
781
86
            None
782
        }
783
87
    }
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryIter<surrealdb_core::sql::tokenizer::Tokenizer> as core::iter::traits::iterator::Iterator>::next
<arbitrary::unstructured::ArbitraryIter<surrealdb_core::val::table::TableName> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
776
1.01k
    fn next(&mut self) -> Option<Result<ElementType>> {
777
1.01k
        let keep_going = self.u.arbitrary().unwrap_or(false);
778
1.01k
        if keep_going {
779
857
            Some(Arbitrary::arbitrary(self.u))
780
        } else {
781
160
            None
782
        }
783
1.01k
    }
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryIter<surrealdb_core::val::geometry::Geometry> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryIter<surrealdb_core::iam::entities::roles::Role> as core::iter::traits::iterator::Iterator>::next
<arbitrary::unstructured::ArbitraryIter<surrealdb_core::sql::statements::alter::api::AlterApiClause> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
776
4
    fn next(&mut self) -> Option<Result<ElementType>> {
777
4
        let keep_going = self.u.arbitrary().unwrap_or(false);
778
4
        if keep_going {
779
2
            Some(Arbitrary::arbitrary(self.u))
780
        } else {
781
2
            None
782
        }
783
4
    }
<arbitrary::unstructured::ArbitraryIter<surrealdb_core::sql::statements::define::api::ApiAction> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
776
1
    fn next(&mut self) -> Option<Result<ElementType>> {
777
1
        let keep_going = self.u.arbitrary().unwrap_or(false);
778
1
        if keep_going {
779
0
            Some(Arbitrary::arbitrary(self.u))
780
        } else {
781
1
            None
782
        }
783
1
    }
<arbitrary::unstructured::ArbitraryIter<surrealdb_core::sql::statements::define::config::api::Middleware> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
776
2
    fn next(&mut self) -> Option<Result<ElementType>> {
777
2
        let keep_going = self.u.arbitrary().unwrap_or(false);
778
2
        if keep_going {
779
1
            Some(Arbitrary::arbitrary(self.u))
780
        } else {
781
1
            None
782
        }
783
2
    }
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryIter<(surrealdb_strand::Strand, surrealdb_core::sql::kind::Kind)> as core::iter::traits::iterator::Iterator>::next
<arbitrary::unstructured::ArbitraryIter<(alloc::string::String, surrealdb_core::sql::kind::Kind)> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
776
2
    fn next(&mut self) -> Option<Result<ElementType>> {
777
2
        let keep_going = self.u.arbitrary().unwrap_or(false);
778
2
        if keep_going {
779
1
            Some(Arbitrary::arbitrary(self.u))
780
        } else {
781
1
            None
782
        }
783
2
    }
<arbitrary::unstructured::ArbitraryIter<(surrealdb_core::sql::param::Param, surrealdb_core::sql::kind::Kind)> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
776
32.9k
    fn next(&mut self) -> Option<Result<ElementType>> {
777
32.9k
        let keep_going = self.u.arbitrary().unwrap_or(false);
778
32.9k
        if keep_going {
779
23.0k
            Some(Arbitrary::arbitrary(self.u))
780
        } else {
781
9.85k
            None
782
        }
783
32.9k
    }
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryIter<surrealdb_types::value::Value> as core::iter::traits::iterator::Iterator>::next
<arbitrary::unstructured::ArbitraryIter<geo_types::geometry::line_string::LineString> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
776
3
    fn next(&mut self) -> Option<Result<ElementType>> {
777
3
        let keep_going = self.u.arbitrary().unwrap_or(false);
778
3
        if keep_going {
779
1
            Some(Arbitrary::arbitrary(self.u))
780
        } else {
781
2
            None
782
        }
783
3
    }
<arbitrary::unstructured::ArbitraryIter<geo_types::geometry::coord::Coord> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
776
11.9k
    fn next(&mut self) -> Option<Result<ElementType>> {
777
11.9k
        let keep_going = self.u.arbitrary().unwrap_or(false);
778
11.9k
        if keep_going {
779
11.9k
            Some(Arbitrary::arbitrary(self.u))
780
        } else {
781
5
            None
782
        }
783
11.9k
    }
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryIter<geo_types::geometry::point::Point> as core::iter::traits::iterator::Iterator>::next
<arbitrary::unstructured::ArbitraryIter<geo_types::geometry::polygon::Polygon> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
776
3
    fn next(&mut self) -> Option<Result<ElementType>> {
777
3
        let keep_going = self.u.arbitrary().unwrap_or(false);
778
3
        if keep_going {
779
1
            Some(Arbitrary::arbitrary(self.u))
780
        } else {
781
2
            None
782
        }
783
3
    }
<arbitrary::unstructured::ArbitraryIter<surrealdb_types::value::geometry::Geometry> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
776
1
    fn next(&mut self) -> Option<Result<ElementType>> {
777
1
        let keep_going = self.u.arbitrary().unwrap_or(false);
778
1
        if keep_going {
779
0
            Some(Arbitrary::arbitrary(self.u))
780
        } else {
781
1
            None
782
        }
783
1
    }
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryIter<(alloc::string::String, surrealdb_types::value::Value)> as core::iter::traits::iterator::Iterator>::next
<arbitrary::unstructured::ArbitraryIter<regex_syntax::ast::ClassSetItem> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
776
24.8k
    fn next(&mut self) -> Option<Result<ElementType>> {
777
24.8k
        let keep_going = self.u.arbitrary().unwrap_or(false);
778
24.8k
        if keep_going {
779
21.5k
            Some(Arbitrary::arbitrary(self.u))
780
        } else {
781
3.34k
            None
782
        }
783
24.8k
    }
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryIter<regex_syntax::ast::Ast> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryIter<regex_syntax::ast::Comment> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryIter<regex_syntax::ast::FlagsItem> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryIter<u8> as core::iter::traits::iterator::Iterator>::next
784
}
785
786
/// Utility iterator produced by [`Unstructured::arbitrary_take_rest_iter`]
787
pub struct ArbitraryTakeRestIter<'a, ElementType> {
788
    u: Unstructured<'a>,
789
    _marker: PhantomData<ElementType>,
790
}
791
792
impl<'a, ElementType: Arbitrary<'a>> Iterator for ArbitraryTakeRestIter<'a, ElementType> {
793
    type Item = Result<ElementType>;
794
0
    fn next(&mut self) -> Option<Result<ElementType>> {
795
0
        let keep_going = self.u.arbitrary().unwrap_or(false);
796
0
        if keep_going {
797
0
            Some(Arbitrary::arbitrary(&mut self.u))
798
        } else {
799
0
            None
800
        }
801
0
    }
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryTakeRestIter<alloc::string::String> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryTakeRestIter<surrealdb_core::sql::expression::Expr> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryTakeRestIter<surrealdb_core::sql::kind::GeometryKind> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryTakeRestIter<surrealdb_core::sql::kind::Kind> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryTakeRestIter<surrealdb_core::sql::part::DestructurePart> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryTakeRestIter<surrealdb_core::sql::literal::ObjectEntry> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryTakeRestIter<surrealdb_core::val::table::TableName> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryTakeRestIter<surrealdb_core::val::geometry::Geometry> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryTakeRestIter<surrealdb_core::iam::entities::roles::Role> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryTakeRestIter<(surrealdb_strand::Strand, surrealdb_core::sql::kind::Kind)> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryTakeRestIter<surrealdb_types::value::Value> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryTakeRestIter<surrealdb_types::value::geometry::Geometry> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryTakeRestIter<(alloc::string::String, surrealdb_types::value::Value)> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryTakeRestIter<regex_syntax::ast::ClassSetItem> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryTakeRestIter<regex_syntax::ast::Ast> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryTakeRestIter<regex_syntax::ast::Comment> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryTakeRestIter<regex_syntax::ast::FlagsItem> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <arbitrary::unstructured::ArbitraryTakeRestIter<_> as core::iter::traits::iterator::Iterator>::next
802
}
803
804
/// A trait that is implemented for all of the primitive integers:
805
///
806
/// * `u8`
807
/// * `u16`
808
/// * `u32`
809
/// * `u64`
810
/// * `u128`
811
/// * `usize`
812
/// * `i8`
813
/// * `i16`
814
/// * `i32`
815
/// * `i64`
816
/// * `i128`
817
/// * `isize`
818
///
819
/// Don't implement this trait yourself.
820
pub trait Int:
821
    Copy
822
    + std::fmt::Debug
823
    + PartialOrd
824
    + Ord
825
    + ops::Sub<Self, Output = Self>
826
    + ops::Rem<Self, Output = Self>
827
    + ops::Shr<Self, Output = Self>
828
    + ops::Shl<usize, Output = Self>
829
    + ops::BitOr<Self, Output = Self>
830
{
831
    #[doc(hidden)]
832
    type Unsigned: Int;
833
834
    #[doc(hidden)]
835
    const ZERO: Self;
836
837
    #[doc(hidden)]
838
    const ONE: Self;
839
840
    #[doc(hidden)]
841
    const MAX: Self;
842
843
    #[doc(hidden)]
844
    fn from_u8(b: u8) -> Self;
845
846
    #[doc(hidden)]
847
    fn from_usize(u: usize) -> Self;
848
849
    #[doc(hidden)]
850
    fn checked_add(self, rhs: Self) -> Option<Self>;
851
852
    #[doc(hidden)]
853
    fn wrapping_add(self, rhs: Self) -> Self;
854
855
    #[doc(hidden)]
856
    fn wrapping_sub(self, rhs: Self) -> Self;
857
858
    #[doc(hidden)]
859
    fn to_unsigned(self) -> Self::Unsigned;
860
861
    #[doc(hidden)]
862
    fn from_unsigned(unsigned: Self::Unsigned) -> Self;
863
}
864
865
macro_rules! impl_int {
866
    ( $( $ty:ty : $unsigned_ty: ty ; )* ) => {
867
        $(
868
            impl Int for $ty {
869
                type Unsigned = $unsigned_ty;
870
871
                const ZERO: Self = 0;
872
873
                const ONE: Self = 1;
874
875
                const MAX: Self = Self::MAX;
876
877
4.31M
                fn from_u8(b: u8) -> Self {
878
3.26M
                    b as Self
879
4.31M
                }
<u8 as arbitrary::unstructured::Int>::from_u8
Line
Count
Source
877
3.26M
                fn from_u8(b: u8) -> Self {
878
3.26M
                    b as Self
879
3.26M
                }
<u16 as arbitrary::unstructured::Int>::from_u8
Line
Count
Source
877
87.4k
                fn from_u8(b: u8) -> Self {
878
87.4k
                    b as Self
879
87.4k
                }
<u32 as arbitrary::unstructured::Int>::from_u8
Line
Count
Source
877
955k
                fn from_u8(b: u8) -> Self {
878
955k
                    b as Self
879
955k
                }
Unexecuted instantiation: <u64 as arbitrary::unstructured::Int>::from_u8
Unexecuted instantiation: <u128 as arbitrary::unstructured::Int>::from_u8
<usize as arbitrary::unstructured::Int>::from_u8
Line
Count
Source
877
584
                fn from_u8(b: u8) -> Self {
878
584
                    b as Self
879
584
                }
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
880
881
19.7M
                fn from_usize(u: usize) -> Self {
882
1.15k
                    u as Self
883
19.7M
                }
<u8 as arbitrary::unstructured::Int>::from_usize
Line
Count
Source
881
7.13M
                fn from_usize(u: usize) -> Self {
882
7.13M
                    u as Self
883
7.13M
                }
<u16 as arbitrary::unstructured::Int>::from_usize
Line
Count
Source
881
87.4k
                fn from_usize(u: usize) -> Self {
882
87.4k
                    u as Self
883
87.4k
                }
<u32 as arbitrary::unstructured::Int>::from_usize
Line
Count
Source
881
12.5M
                fn from_usize(u: usize) -> Self {
882
12.5M
                    u as Self
883
12.5M
                }
Unexecuted instantiation: <u64 as arbitrary::unstructured::Int>::from_usize
Unexecuted instantiation: <u128 as arbitrary::unstructured::Int>::from_usize
<usize as arbitrary::unstructured::Int>::from_usize
Line
Count
Source
881
1.15k
                fn from_usize(u: usize) -> Self {
882
1.15k
                    u as Self
883
1.15k
                }
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
884
885
18.7M
                fn checked_add(self, rhs: Self) -> Option<Self> {
886
18.7M
                    <$ty>::checked_add(self, rhs)
887
18.7M
                }
<u8 as arbitrary::unstructured::Int>::checked_add
Line
Count
Source
885
7.13M
                fn checked_add(self, rhs: Self) -> Option<Self> {
886
7.13M
                    <$ty>::checked_add(self, rhs)
887
7.13M
                }
<u16 as arbitrary::unstructured::Int>::checked_add
Line
Count
Source
885
43.7k
                fn checked_add(self, rhs: Self) -> Option<Self> {
886
43.7k
                    <$ty>::checked_add(self, rhs)
887
43.7k
                }
<u32 as arbitrary::unstructured::Int>::checked_add
Line
Count
Source
885
11.5M
                fn checked_add(self, rhs: Self) -> Option<Self> {
886
11.5M
                    <$ty>::checked_add(self, rhs)
887
11.5M
                }
Unexecuted instantiation: <u64 as arbitrary::unstructured::Int>::checked_add
Unexecuted instantiation: <u128 as arbitrary::unstructured::Int>::checked_add
<usize as arbitrary::unstructured::Int>::checked_add
Line
Count
Source
885
574
                fn checked_add(self, rhs: Self) -> Option<Self> {
886
574
                    <$ty>::checked_add(self, rhs)
887
574
                }
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
888
889
18.7M
                fn wrapping_add(self, rhs: Self) -> Self {
890
18.7M
                    <$ty>::wrapping_add(self, rhs)
891
18.7M
                }
<u8 as arbitrary::unstructured::Int>::wrapping_add
Line
Count
Source
889
7.13M
                fn wrapping_add(self, rhs: Self) -> Self {
890
7.13M
                    <$ty>::wrapping_add(self, rhs)
891
7.13M
                }
<u16 as arbitrary::unstructured::Int>::wrapping_add
Line
Count
Source
889
43.7k
                fn wrapping_add(self, rhs: Self) -> Self {
890
43.7k
                    <$ty>::wrapping_add(self, rhs)
891
43.7k
                }
<u32 as arbitrary::unstructured::Int>::wrapping_add
Line
Count
Source
889
11.5M
                fn wrapping_add(self, rhs: Self) -> Self {
890
11.5M
                    <$ty>::wrapping_add(self, rhs)
891
11.5M
                }
Unexecuted instantiation: <u64 as arbitrary::unstructured::Int>::wrapping_add
Unexecuted instantiation: <u128 as arbitrary::unstructured::Int>::wrapping_add
<usize as arbitrary::unstructured::Int>::wrapping_add
Line
Count
Source
889
574
                fn wrapping_add(self, rhs: Self) -> Self {
890
574
                    <$ty>::wrapping_add(self, rhs)
891
574
                }
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
892
893
18.7M
                fn wrapping_sub(self, rhs: Self) -> Self {
894
18.7M
                    <$ty>::wrapping_sub(self, rhs)
895
18.7M
                }
<u8 as arbitrary::unstructured::Int>::wrapping_sub
Line
Count
Source
893
7.13M
                fn wrapping_sub(self, rhs: Self) -> Self {
894
7.13M
                    <$ty>::wrapping_sub(self, rhs)
895
7.13M
                }
<u16 as arbitrary::unstructured::Int>::wrapping_sub
Line
Count
Source
893
43.7k
                fn wrapping_sub(self, rhs: Self) -> Self {
894
43.7k
                    <$ty>::wrapping_sub(self, rhs)
895
43.7k
                }
<u32 as arbitrary::unstructured::Int>::wrapping_sub
Line
Count
Source
893
11.5M
                fn wrapping_sub(self, rhs: Self) -> Self {
894
11.5M
                    <$ty>::wrapping_sub(self, rhs)
895
11.5M
                }
Unexecuted instantiation: <u64 as arbitrary::unstructured::Int>::wrapping_sub
Unexecuted instantiation: <u128 as arbitrary::unstructured::Int>::wrapping_sub
<usize as arbitrary::unstructured::Int>::wrapping_sub
Line
Count
Source
893
574
                fn wrapping_sub(self, rhs: Self) -> Self {
894
574
                    <$ty>::wrapping_sub(self, rhs)
895
574
                }
Unexecuted instantiation: <i8 as arbitrary::unstructured::Int>::wrapping_sub
Unexecuted instantiation: <i16 as arbitrary::unstructured::Int>::wrapping_sub
Unexecuted instantiation: <i32 as arbitrary::unstructured::Int>::wrapping_sub
Unexecuted instantiation: <i64 as arbitrary::unstructured::Int>::wrapping_sub
Unexecuted instantiation: <i128 as arbitrary::unstructured::Int>::wrapping_sub
Unexecuted instantiation: <isize as arbitrary::unstructured::Int>::wrapping_sub
896
897
37.5M
                fn to_unsigned(self) -> Self::Unsigned {
898
37.5M
                    self as $unsigned_ty
899
37.5M
                }
<u8 as arbitrary::unstructured::Int>::to_unsigned
Line
Count
Source
897
14.2M
                fn to_unsigned(self) -> Self::Unsigned {
898
14.2M
                    self as $unsigned_ty
899
14.2M
                }
<u16 as arbitrary::unstructured::Int>::to_unsigned
Line
Count
Source
897
87.4k
                fn to_unsigned(self) -> Self::Unsigned {
898
87.4k
                    self as $unsigned_ty
899
87.4k
                }
<u32 as arbitrary::unstructured::Int>::to_unsigned
Line
Count
Source
897
634k
                fn to_unsigned(self) -> Self::Unsigned {
898
634k
                    self as $unsigned_ty
899
634k
                }
Unexecuted instantiation: <u64 as arbitrary::unstructured::Int>::to_unsigned
Unexecuted instantiation: <u128 as arbitrary::unstructured::Int>::to_unsigned
<usize as arbitrary::unstructured::Int>::to_unsigned
Line
Count
Source
897
1.14k
                fn to_unsigned(self) -> Self::Unsigned {
898
1.14k
                    self as $unsigned_ty
899
1.14k
                }
Unexecuted instantiation: <i8 as arbitrary::unstructured::Int>::to_unsigned
Unexecuted instantiation: <i16 as arbitrary::unstructured::Int>::to_unsigned
<i32 as arbitrary::unstructured::Int>::to_unsigned
Line
Count
Source
897
22.5M
                fn to_unsigned(self) -> Self::Unsigned {
898
22.5M
                    self as $unsigned_ty
899
22.5M
                }
Unexecuted instantiation: <i64 as arbitrary::unstructured::Int>::to_unsigned
Unexecuted instantiation: <i128 as arbitrary::unstructured::Int>::to_unsigned
Unexecuted instantiation: <isize as arbitrary::unstructured::Int>::to_unsigned
900
901
18.7M
                fn from_unsigned(unsigned: $unsigned_ty) -> Self {
902
7.50M
                    unsigned as Self
903
18.7M
                }
<u8 as arbitrary::unstructured::Int>::from_unsigned
Line
Count
Source
901
7.13M
                fn from_unsigned(unsigned: $unsigned_ty) -> Self {
902
7.13M
                    unsigned as Self
903
7.13M
                }
<u16 as arbitrary::unstructured::Int>::from_unsigned
Line
Count
Source
901
43.7k
                fn from_unsigned(unsigned: $unsigned_ty) -> Self {
902
43.7k
                    unsigned as Self
903
43.7k
                }
<u32 as arbitrary::unstructured::Int>::from_unsigned
Line
Count
Source
901
317k
                fn from_unsigned(unsigned: $unsigned_ty) -> Self {
902
317k
                    unsigned as Self
903
317k
                }
Unexecuted instantiation: <u64 as arbitrary::unstructured::Int>::from_unsigned
Unexecuted instantiation: <u128 as arbitrary::unstructured::Int>::from_unsigned
<usize as arbitrary::unstructured::Int>::from_unsigned
Line
Count
Source
901
574
                fn from_unsigned(unsigned: $unsigned_ty) -> Self {
902
574
                    unsigned as Self
903
574
                }
Unexecuted instantiation: <i8 as arbitrary::unstructured::Int>::from_unsigned
Unexecuted instantiation: <i16 as arbitrary::unstructured::Int>::from_unsigned
<i32 as arbitrary::unstructured::Int>::from_unsigned
Line
Count
Source
901
11.2M
                fn from_unsigned(unsigned: $unsigned_ty) -> Self {
902
11.2M
                    unsigned as Self
903
11.2M
                }
Unexecuted instantiation: <i64 as arbitrary::unstructured::Int>::from_unsigned
Unexecuted instantiation: <i128 as arbitrary::unstructured::Int>::from_unsigned
Unexecuted instantiation: <isize as arbitrary::unstructured::Int>::from_unsigned
904
            }
905
        )*
906
    }
907
}
908
909
impl_int! {
910
    u8: u8;
911
    u16: u16;
912
    u32: u32;
913
    u64: u64;
914
    u128: u128;
915
    usize: usize;
916
    i8: u8;
917
    i16: u16;
918
    i32: u32;
919
    i64: u64;
920
    i128: u128;
921
    isize: usize;
922
}
923
924
#[cfg(test)]
925
mod tests {
926
    use super::*;
927
928
    #[test]
929
    fn test_byte_size() {
930
        let mut u = Unstructured::new(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 6]);
931
        // Should take one byte off the end
932
        assert_eq!(u.arbitrary_byte_size().unwrap(), 6);
933
        assert_eq!(u.len(), 9);
934
        let mut v = vec![0; 260];
935
        v.push(1);
936
        v.push(4);
937
        let mut u = Unstructured::new(&v);
938
        // Should read two bytes off the end
939
        assert_eq!(u.arbitrary_byte_size().unwrap(), 0x104);
940
        assert_eq!(u.len(), 260);
941
    }
942
943
    #[test]
944
    fn int_in_range_of_one() {
945
        let mut u = Unstructured::new(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 6]);
946
        let x = u.int_in_range(0..=0).unwrap();
947
        assert_eq!(x, 0);
948
        let choice = *u.choose(&[42]).unwrap();
949
        assert_eq!(choice, 42)
950
    }
951
952
    #[test]
953
    fn int_in_range_uses_minimal_amount_of_bytes() {
954
        let mut u = Unstructured::new(&[1, 2]);
955
        assert_eq!(1, u.int_in_range::<u8>(0..=u8::MAX).unwrap());
956
        assert_eq!(u.len(), 1);
957
958
        let mut u = Unstructured::new(&[1, 2]);
959
        assert_eq!(1, u.int_in_range::<u32>(0..=u8::MAX as u32).unwrap());
960
        assert_eq!(u.len(), 1);
961
962
        let mut u = Unstructured::new(&[1]);
963
        assert_eq!(1, u.int_in_range::<u32>(0..=u8::MAX as u32 + 1).unwrap());
964
        assert!(u.is_empty());
965
    }
966
967
    #[test]
968
    fn int_in_range_in_bounds() {
969
        for input in u8::MIN..=u8::MAX {
970
            let input = [input];
971
972
            let mut u = Unstructured::new(&input);
973
            let x = u.int_in_range(1..=u8::MAX).unwrap();
974
            assert_ne!(x, 0);
975
976
            let mut u = Unstructured::new(&input);
977
            let x = u.int_in_range(0..=u8::MAX - 1).unwrap();
978
            assert_ne!(x, u8::MAX);
979
        }
980
    }
981
982
    #[test]
983
    fn int_in_range_covers_unsigned_range() {
984
        // Test that we generate all values within the range given to
985
        // `int_in_range`.
986
987
        let mut full = [false; u8::MAX as usize + 1];
988
        let mut no_zero = [false; u8::MAX as usize];
989
        let mut no_max = [false; u8::MAX as usize];
990
        let mut narrow = [false; 10];
991
992
        for input in u8::MIN..=u8::MAX {
993
            let input = [input];
994
995
            let mut u = Unstructured::new(&input);
996
            let x = u.int_in_range(0..=u8::MAX).unwrap();
997
            full[x as usize] = true;
998
999
            let mut u = Unstructured::new(&input);
1000
            let x = u.int_in_range(1..=u8::MAX).unwrap();
1001
            no_zero[x as usize - 1] = true;
1002
1003
            let mut u = Unstructured::new(&input);
1004
            let x = u.int_in_range(0..=u8::MAX - 1).unwrap();
1005
            no_max[x as usize] = true;
1006
1007
            let mut u = Unstructured::new(&input);
1008
            let x = u.int_in_range(100..=109).unwrap();
1009
            narrow[x as usize - 100] = true;
1010
        }
1011
1012
        for (i, covered) in full.iter().enumerate() {
1013
            assert!(covered, "full[{}] should have been generated", i);
1014
        }
1015
        for (i, covered) in no_zero.iter().enumerate() {
1016
            assert!(covered, "no_zero[{}] should have been generated", i);
1017
        }
1018
        for (i, covered) in no_max.iter().enumerate() {
1019
            assert!(covered, "no_max[{}] should have been generated", i);
1020
        }
1021
        for (i, covered) in narrow.iter().enumerate() {
1022
            assert!(covered, "narrow[{}] should have been generated", i);
1023
        }
1024
    }
1025
1026
    #[test]
1027
    fn int_in_range_covers_signed_range() {
1028
        // Test that we generate all values within the range given to
1029
        // `int_in_range`.
1030
1031
        let mut full = [false; u8::MAX as usize + 1];
1032
        let mut no_min = [false; u8::MAX as usize];
1033
        let mut no_max = [false; u8::MAX as usize];
1034
        let mut narrow = [false; 21];
1035
1036
        let abs_i8_min: isize = 128;
1037
1038
        for input in 0..=u8::MAX {
1039
            let input = [input];
1040
1041
            let mut u = Unstructured::new(&input);
1042
            let x = u.int_in_range(i8::MIN..=i8::MAX).unwrap();
1043
            full[(x as isize + abs_i8_min) as usize] = true;
1044
1045
            let mut u = Unstructured::new(&input);
1046
            let x = u.int_in_range(i8::MIN + 1..=i8::MAX).unwrap();
1047
            no_min[(x as isize + abs_i8_min - 1) as usize] = true;
1048
1049
            let mut u = Unstructured::new(&input);
1050
            let x = u.int_in_range(i8::MIN..=i8::MAX - 1).unwrap();
1051
            no_max[(x as isize + abs_i8_min) as usize] = true;
1052
1053
            let mut u = Unstructured::new(&input);
1054
            let x = u.int_in_range(-10..=10).unwrap();
1055
            narrow[(x as isize + 10) as usize] = true;
1056
        }
1057
1058
        for (i, covered) in full.iter().enumerate() {
1059
            assert!(covered, "full[{}] should have been generated", i);
1060
        }
1061
        for (i, covered) in no_min.iter().enumerate() {
1062
            assert!(covered, "no_min[{}] should have been generated", i);
1063
        }
1064
        for (i, covered) in no_max.iter().enumerate() {
1065
            assert!(covered, "no_max[{}] should have been generated", i);
1066
        }
1067
        for (i, covered) in narrow.iter().enumerate() {
1068
            assert!(covered, "narrow[{}] should have been generated", i);
1069
        }
1070
    }
1071
}