Skip to main content

map

Function map 

Source
pub fn map<E0, E1>(
    gen0: BoxGen<E0>,
    map_fn: fn(E0) -> E1,
    unmap_fn: fn(E1) -> E0,
) -> BoxGen<E1>
where E0: Clone + 'static, E1: Clone + 'static,
Expand description

Convert a generator of type E0 to a generator of type E1.

This enables generating examples of type E1 by piggybacking on a generator of type E0, produce examples of type E0 that is then mapped to type E1.

The unmapping function is used for reverse the mapping back to type E0 from E1, enabling piggybacking of the associated shrinker of type E0, to automatically also get shrinking of type E1. This requires that there is an associated shrinker of type E0.

use monkey_test::*;

let number_string_generator: BoxGen<String> = gens::map(
    gens::i64::any(),
    |i: i64| i.to_string(),
    |s: String| s.parse().unwrap(),
);

let even_numbers_only_generator: BoxGen<u64> = gens::map(
    gens::u64::ranged(..10_000),
    |i: u64| i * 2,
    |even: u64| even / 2,
);

// Shorthand way to do the same thing
let even_numbers_only_generator_2: BoxGen<u64> = gens::u64::ranged(..10_000)
    .map(|i| i * 2, |e| e / 2);