use super::*;
use std::mem;
#[derive(Clone, Debug, Default)]
pub struct HashSet<M> {
mutator: M,
}
pub fn hash_set<M>(mutator: M) -> HashSet<M> {
HashSet { mutator }
}
impl<M, T> Mutate<std::collections::HashSet<T>> for HashSet<M>
where
M: Generate<T>,
T: Eq + Hash,
{
#[inline]
fn mutation_count(
&self,
value: &std::collections::HashSet<T>,
shrink: bool,
) -> core::option::Option<u32> {
let mut count = 0u32;
count += !shrink as u32;
count += !value.is_empty() as u32;
for x in value.iter() {
count += self.mutator.mutation_count(x, shrink)?;
}
Some(count)
}
#[inline]
fn mutate(
&mut self,
c: &mut Candidates,
value: &mut std::collections::HashSet<T>,
) -> Result<()> {
if !c.shrink() {
c.mutation(|ctx| {
let elem = self.mutator.generate(ctx)?;
value.insert(elem);
Ok(())
})?;
}
if !value.is_empty() {
c.mutation(|ctx| {
let target = ctx.rng().gen_index(value.len()).unwrap();
let mut i = 0;
value.retain(|_| {
let keep = i != target;
i += 1;
keep
});
Ok(())
})?;
}
if !value.is_empty() {
let elems = mem::take(value).into_iter();
value.reserve(elems.len());
let mut early_exit = None;
for mut elem in elems {
if early_exit.is_none() {
match self.mutator.mutate(c, &mut elem) {
Ok(()) => {}
Err(e) if e.is_early_exit() => {
early_exit = Some(e);
}
Err(e) => return Err(e),
}
}
value.insert(elem);
}
if let Some(e) = early_exit {
return Err(e);
}
}
Ok(())
}
}
impl<M, T> Generate<std::collections::HashSet<T>> for HashSet<M>
where
M: Generate<T>,
T: Eq + Hash,
{
#[inline]
fn generate(&mut self, ctx: &mut Context) -> Result<std::collections::HashSet<T>> {
self.generate_via_mutate(ctx, 1)
}
}
impl<T> DefaultMutate for std::collections::HashSet<T>
where
T: DefaultMutate + Eq + Hash,
T::DefaultMutate: Generate<T>,
{
type DefaultMutate = HashSet<T::DefaultMutate>;
}