use alloc::vec::Vec;
use crate::{
data::support::not_found,
errors::BunsenResult,
};
pub type PrefabTable<C> = &'static [(&'static str, fn() -> C)];
pub trait Prefabs: Sized + 'static {
const PREFAB_TABLE: &'static str;
const PREFABS: PrefabTable<Self>;
fn prefab_names() -> Vec<&'static str> {
Self::PREFABS.iter().map(|(name, _)| *name).collect()
}
fn prefab(name: &str) -> Option<Self> {
Self::PREFABS
.iter()
.find(|(n, _)| *n == name)
.map(|(_, build)| build())
}
fn try_prefab(name: &str) -> BunsenResult<Self> {
Self::prefab(name).ok_or_else(|| {
not_found(
Some(Self::PREFAB_TABLE),
"prefab",
name,
&Self::prefab_names(),
)
})
}
fn expect_prefab(name: &str) -> Self {
Self::try_prefab(name).unwrap_or_else(|e| panic!("{e}"))
}
fn find_prefab(mut pred: impl FnMut(&Self) -> bool) -> Option<&'static str> {
Self::PREFABS
.iter()
.find(|(_, build)| pred(&build()))
.map(|(name, _)| *name)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::errors::{
BunsenErrorKind,
LookupError,
testing::{
ErrorMatcher,
predicate,
text,
},
};
#[derive(Debug, PartialEq)]
struct Toy {
width: usize,
}
impl Prefabs for Toy {
const PREFABS: PrefabTable<Self> = &[
("narrow", || Toy { width: 1 }),
("wide", || Toy { width: 2 }),
];
const PREFAB_TABLE: &'static str = "toys";
}
#[test]
fn test_names_lookups_and_find() {
assert_eq!(Toy::prefab_names(), ["narrow", "wide"]);
assert_eq!(Toy::prefab("wide"), Some(Toy { width: 2 }));
assert_eq!(Toy::prefab("huge"), None);
assert_eq!(Toy::expect_prefab("narrow"), Toy { width: 1 });
assert_eq!(Toy::find_prefab(|c| c.width == 2), Some("wide"));
assert!(Toy::find_prefab(|c| c.width == 3).is_none());
}
#[test]
fn test_a_miss_names_what_there_is() {
ErrorMatcher::kind(BunsenErrorKind::Lookup)
.display(text::eq(
"toys: no prefab \"huge\"; there are: narrow, wide",
))
.cause(predicate("candidates narrow, wide", |c: &LookupError| {
c.key == "huge" && c.candidates == ["narrow", "wide"]
}))
.assert_err(&Toy::try_prefab("huge"));
}
}