use super::*;
use core::mem;
#[derive(Clone, Debug, Default)]
pub struct BTreeSet<M> {
mutator: M,
}
pub fn btree_set<M>(mutator: M) -> BTreeSet<M> {
BTreeSet { mutator }
}
impl<M, T> Mutate<alloc::collections::BTreeSet<T>> for BTreeSet<M>
where
M: Generate<T>,
T: Ord,
{
#[inline]
fn mutation_count(
&self,
value: &alloc::collections::BTreeSet<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 alloc::collections::BTreeSet<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| {
if ctx.rng().gen_bool() {
value.pop_first();
} else {
value.pop_last();
}
Ok(())
})?;
}
if !value.is_empty() {
let mut early_exit = None;
for mut elem in mem::take(value) {
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<alloc::collections::BTreeSet<T>> for BTreeSet<M>
where
M: Generate<T>,
T: Ord,
{
#[inline]
fn generate(&mut self, ctx: &mut Context) -> Result<alloc::collections::BTreeSet<T>> {
self.generate_via_mutate(ctx, 1)
}
}
impl<T> DefaultMutate for alloc::collections::BTreeSet<T>
where
T: DefaultMutate + Ord,
T::DefaultMutate: Generate<T>,
{
type DefaultMutate = BTreeSet<T::DefaultMutate>;
}