Generate an arbitrary instance of the specified type.
(
ty: &component::Type,
fuel: &mut u32,
input: &mut Unstructured,
)
| 32 | |
| 33 | /// Generate an arbitrary instance of the specified type. |
| 34 | fn arbitrary_val( |
| 35 | ty: &component::Type, |
| 36 | fuel: &mut u32, |
| 37 | input: &mut Unstructured, |
| 38 | ) -> arbitrary::Result<Val> { |
| 39 | use component::Type; |
| 40 | |
| 41 | *fuel = fuel.saturating_sub(1); |
| 42 | Ok(match ty { |
| 43 | Type::Bool => Val::Bool(input.arbitrary()?), |
| 44 | Type::S8 => Val::S8(input.arbitrary()?), |
| 45 | Type::U8 => Val::U8(input.arbitrary()?), |
| 46 | Type::S16 => Val::S16(input.arbitrary()?), |
| 47 | Type::U16 => Val::U16(input.arbitrary()?), |
| 48 | Type::S32 => Val::S32(input.arbitrary()?), |
| 49 | Type::U32 => Val::U32(input.arbitrary()?), |
| 50 | Type::S64 => Val::S64(input.arbitrary()?), |
| 51 | Type::U64 => Val::U64(input.arbitrary()?), |
| 52 | Type::Float32 => Val::Float32(input.arbitrary()?), |
| 53 | Type::Float64 => Val::Float64(input.arbitrary()?), |
| 54 | Type::Char => Val::Char(input.arbitrary()?), |
| 55 | Type::String => { |
| 56 | let string = if *fuel == 0 { |
| 57 | String::new() |
| 58 | } else { |
| 59 | input.arbitrary()? |
| 60 | }; |
| 61 | *fuel = fuel.saturating_sub(string.len() as u32); |
| 62 | Val::String(string) |
| 63 | } |
| 64 | Type::List(list) => { |
| 65 | let mut values = Vec::new(); |
| 66 | input.arbitrary_loop(Some(MIN_LIST_LENGTH), Some(MAX_LIST_LENGTH), |input| { |
| 67 | if *fuel == 0 { |
| 68 | return Ok(ControlFlow::Break(())); |
| 69 | } |
| 70 | values.push(arbitrary_val(&list.ty(), fuel, input)?); |
| 71 | |
| 72 | Ok(ControlFlow::Continue(())) |
| 73 | })?; |
| 74 | |
| 75 | Val::List(values) |
| 76 | } |
| 77 | Type::Record(record) => Val::Record( |
| 78 | record |
| 79 | .fields() |
| 80 | .map(|field| { |
| 81 | Ok(( |
| 82 | field.name.to_string(), |
| 83 | arbitrary_val(&field.ty, fuel, input)?, |
| 84 | )) |
| 85 | }) |
| 86 | .collect::<arbitrary::Result<_>>()?, |
| 87 | ), |
| 88 | Type::Tuple(tuple) => Val::Tuple( |
| 89 | tuple |
| 90 | .types() |
| 91 | .map(|ty| arbitrary_val(&ty, fuel, input)) |
no test coverage detected