Skip to content

Commit

Permalink
Implement Arbitrary for various types
Browse files Browse the repository at this point in the history
  • Loading branch information
brson committed Mar 16, 2023
1 parent bfbb3a5 commit 05704f4
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 1 deletion.
22 changes: 22 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion soroban-env-common/Cargo.toml
Expand Up @@ -20,12 +20,13 @@ wasmi = { workspace = true, optional = true }
serde = { version = "1.0.0", features = ["derive"], optional = true }
static_assertions = "1.1.0"
ethnum = "1.3.2"
arbitrary = { version = "1.1.3", features = ["derive"], optional = true }

[features]
std = ["stellar-xdr/std", "stellar-xdr/base64"]
serde = ["dep:serde", "stellar-xdr/serde"]
vm = ["wasmi"]
testutils = []
testutils = ["dep:arbitrary", "stellar-xdr/arbitrary"]

[package.metadata.docs.rs]
all-features = true
48 changes: 48 additions & 0 deletions soroban-env-common/src/arbitrary.rs
@@ -0,0 +1,48 @@
//! Implementations of [`Arbitrary`] for contract types.

#![cfg(feature = "testutils")]

extern crate alloc;

use crate::SymbolSmall;
use crate::xdr::{ScStatus};
use crate::{Status};
use alloc::string::String;
use alloc::vec::Vec as RustVec;
use arbitrary::{Arbitrary, Unstructured};

impl<'a> Arbitrary<'a> for SymbolSmall {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
let choices = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
let choices: RustVec<char> = choices.chars().collect();

let mut buf = String::new();

let len = u.int_in_range(0..=10)?;

for _ in 0..len {
let choice = u.choose(&choices);
match choice {
Ok(ch) => {
buf.push(*ch);
}
Err(_) => {
break;
}
}
}

let symbol = SymbolSmall::try_from_str(&buf).expect("SymbolSmall");

Ok(symbol)
}
}

impl<'a> Arbitrary<'a> for Status {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
let scstatus = ScStatus::arbitrary(u)?;
let status = Status::from(scstatus);

Ok(status)
}
}
1 change: 1 addition & 0 deletions soroban-env-common/src/lib.rs
Expand Up @@ -36,6 +36,7 @@ pub const VERSION: Version = Version {

mod wrapper_macros;

mod arbitrary;
mod bytes;
mod compare;
mod convert;
Expand Down

0 comments on commit 05704f4

Please sign in to comment.