use alloc::{
collections::BTreeMap,
format,
string::{
String,
ToString,
},
sync::Arc,
vec::Vec,
};
use core::fmt::Debug;
use burn::config::Config;
use super::not_found;
use crate::errors::BunsenResult;
pub struct StaticPreFabConfig<C>
where
C: 'static + Config + Debug + Clone,
{
pub name: &'static str,
pub description: &'static str,
pub builder: fn() -> C,
}
impl<C> StaticPreFabConfig<C>
where
C: 'static + Config + Debug + Clone,
{
pub fn to_prefab(&self) -> PreFabConfig<C> {
let builder = self.builder;
PreFabConfig {
name: self.name.to_string(),
description: self.description.to_string(),
builder: Arc::new(builder),
}
}
pub fn to_config(&self) -> C {
(self.builder)()
}
}
impl<C> From<&StaticPreFabConfig<C>> for PreFabConfig<C>
where
C: 'static + Config + Debug + Clone,
{
fn from(config: &StaticPreFabConfig<C>) -> Self {
config.to_prefab()
}
}
impl<C> Debug for StaticPreFabConfig<C>
where
C: 'static + Config + Debug + Clone,
{
fn fmt(
&self,
f: &mut core::fmt::Formatter<'_>,
) -> core::fmt::Result {
self.to_prefab().fmt(f)
}
}
#[derive(Clone)]
pub struct PreFabConfig<C>
where
C: 'static + Config + Debug + Clone,
{
pub name: String,
pub description: String,
pub builder: Arc<dyn Fn() -> C + Send + Sync>,
}
impl<C> Debug for PreFabConfig<C>
where
C: 'static + Config + Debug + Clone,
{
fn fmt(
&self,
f: &mut core::fmt::Formatter<'_>,
) -> core::fmt::Result {
let pretty = f.alternate();
let type_name = core::any::type_name::<C>();
let mut handle = f.debug_struct(&format!("PreFabConfig<{}>", type_name));
handle
.field("name", &self.name)
.field("description", &self.description);
if pretty {
handle.field("config", &self.to_config());
}
handle.finish()
}
}
impl<C> PreFabConfig<C>
where
C: 'static + Config + Debug + Clone,
{
pub fn to_config(&self) -> C {
(self.builder)()
}
}
#[derive(Debug)]
pub struct StaticPreFabMap<C>
where
C: 'static + Config + Debug + Clone,
{
pub name: &'static str,
pub description: &'static str,
pub items: &'static [&'static StaticPreFabConfig<C>],
}
impl<C> StaticPreFabMap<C>
where
C: 'static + Config + Debug + Clone,
{
pub fn to_prefab_map(&self) -> PreFabMap<C> {
PreFabMap {
name: self.name.to_string(),
description: self.description.to_string(),
items: self
.items
.iter()
.map(|c| (c.name.to_string(), c.to_prefab()))
.collect(),
}
}
pub fn iter(&self) -> impl Iterator<Item = &'static StaticPreFabConfig<C>> + '_ {
self.items.iter().copied()
}
pub fn find(
&self,
mut pred: impl FnMut(&C) -> bool,
) -> Option<&'static StaticPreFabConfig<C>> {
self.iter().find(|p| pred(&p.to_config()))
}
pub fn names(&self) -> Vec<&'static str> {
self.iter().map(|p| p.name).collect()
}
pub fn lookup_prefab(
&self,
name: &str,
) -> Option<PreFabConfig<C>> {
self.iter().find(|c| c.name == name).map(|c| c.to_prefab())
}
pub fn try_lookup_prefab(
&self,
name: &str,
) -> BunsenResult<PreFabConfig<C>> {
self.lookup_prefab(name)
.ok_or_else(|| not_found(Some(self.name), "prefab", name, &self.names()))
}
pub fn expect_lookup_prefab(
&self,
name: &str,
) -> PreFabConfig<C> {
self.try_lookup_prefab(name)
.unwrap_or_else(|e| panic!("{e}"))
}
}
#[derive(Debug, Clone)]
pub struct PreFabMap<C>
where
C: 'static + Config + Debug + Clone,
{
pub name: String,
pub description: String,
pub items: BTreeMap<String, PreFabConfig<C>>,
}
impl<C> PreFabMap<C>
where
C: 'static + Config + Debug + Clone,
{
pub fn names(&self) -> Vec<&str> {
self.items.keys().map(String::as_str).collect()
}
pub fn lookup_prefab(
&self,
name: &str,
) -> Option<PreFabConfig<C>> {
self.items.get(name).cloned()
}
pub fn try_lookup_prefab(
&self,
name: &str,
) -> BunsenResult<PreFabConfig<C>> {
self.lookup_prefab(name)
.ok_or_else(|| not_found(Some(&self.name), "prefab", name, &self.names()))
}
pub fn expect_lookup_prefab(
&self,
name: &str,
) -> PreFabConfig<C> {
self.try_lookup_prefab(name)
.unwrap_or_else(|e| panic!("{e}"))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::errors::{
BunsenErrorKind,
LookupError,
testing::{
ErrorMatcher,
predicate,
text,
},
};
#[derive(Config, Debug)]
struct Toy {
width: usize,
}
static NARROW: StaticPreFabConfig<Toy> = StaticPreFabConfig {
name: "narrow",
description: "width 1",
builder: || Toy::new(1),
};
static WIDE: StaticPreFabConfig<Toy> = StaticPreFabConfig {
name: "wide",
description: "width 2",
builder: || Toy::new(2),
};
static TOYS: StaticPreFabMap<Toy> = StaticPreFabMap {
name: "toys",
description: "two toys",
items: &[&NARROW, &WIDE],
};
#[test]
fn test_iter_find_and_names() {
assert_eq!(TOYS.names(), ["narrow", "wide"]);
assert_eq!(TOYS.iter().count(), 2);
assert_eq!(TOYS.find(|c| c.width == 2).map(|p| p.name), Some("wide"));
assert!(TOYS.find(|c| c.width == 3).is_none());
assert_eq!(TOYS.lookup_prefab("wide").unwrap().to_config().width, 2);
let owned = TOYS.to_prefab_map();
assert_eq!(owned.names(), ["narrow", "wide"]);
assert_eq!(owned.lookup_prefab("narrow").unwrap().to_config().width, 1);
}
#[test]
fn test_a_miss_names_what_there_is() {
let miss = || {
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"]
}))
};
miss().assert_err(&TOYS.try_lookup_prefab("huge"));
miss().assert_err(&TOYS.to_prefab_map().try_lookup_prefab("huge"));
}
}