use rand::seq::IndexedRandom;
use std::convert::Infallible;
use super::TransformField;
use crate::{
StaticStr,
actions::transforms::result::{OptionUnwrapTransformResultExt, TransformResult as TrRes},
};
#[derive(Debug)]
pub enum Set {
Single(StaticStr),
Random(Vec<StaticStr>),
Empty,
}
impl Set {
pub fn single<S>(string: S) -> Self
where
S: Into<StaticStr>,
{
Self::Single(string.into())
}
pub fn random<I, S>(iter: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<StaticStr>,
{
Self::Random(iter.into_iter().map(Into::into).collect())
}
}
impl TransformField for Set {
type Err = Infallible;
async fn transform_field(&mut self, _value: Option<&str>) -> Result<TrRes<String>, Self::Err> {
Ok(match self {
Set::Single(x) => TrRes::New(x.to_string()),
Set::Random(vec) => vec
.choose(&mut rand::rng())
.map(ToString::to_string)
.unwrap_or_empty(),
Set::Empty => TrRes::Empty,
})
}
}