use core::convert::Infallible;
use super::{AsyncConstructor, Resources};
use crate::{AsyncResource, Shared};
struct Egemma(usize);
impl AsyncResource for Egemma {
type Error = Infallible;
type Options = usize;
async fn build(_ctx: &Resources, dim: usize) -> Result<Self, Self::Error> {
Ok(Self(dim))
}
}
#[derive(Debug)]
struct Decode {
threads: usize,
dim: usize,
}
struct DecodeOptions {
threads: usize,
}
impl Default for DecodeOptions {
fn default() -> Self {
Self { threads: 4 }
}
}
impl AsyncConstructor for Decode {
type Error = DecodeError;
type Options = DecodeOptions;
async fn with_options(ctx: &Resources, options: DecodeOptions) -> Result<Self, Self::Error> {
if options.threads == 0 {
return Err(DecodeError);
}
Ok(Self {
threads: options.threads,
dim: ctx.shared::<Egemma>().map_err(|_| DecodeError)?.0,
})
}
}
#[derive(Debug, PartialEq, Eq)]
struct DecodeError;
struct Watchdog;
impl AsyncConstructor for Watchdog {
type Error = Infallible;
type Options = ();
async fn with_options(_ctx: &Resources, (): ()) -> Result<Self, Self::Error> {
Ok(Self)
}
}
fn context() -> Resources {
Resources::new().with(Shared::new(Egemma(768)))
}
#[tokio::test]
async fn with_options_takes_the_sections_own_options() {
let decode = Decode::with_options(&context(), DecodeOptions { threads: 8 })
.await
.expect("eight threads is a legal budget");
assert_eq!(decode.threads, 8);
}
#[tokio::test]
async fn new_delegates_to_with_options_at_the_options_default() {
let decode = Decode::new(&context()).await.expect("the default builds");
assert_eq!(decode.threads, DecodeOptions::default().threads);
assert_eq!(decode.threads, 4);
}
#[tokio::test]
async fn both_doors_reach_the_shared_resource() {
let ctx = context();
let tuned = Decode::with_options(&ctx, DecodeOptions { threads: 2 })
.await
.expect("it builds");
let plain = Decode::new(&ctx).await.expect("it builds");
assert_eq!((tuned.dim, plain.dim), (768, 768));
}
#[tokio::test]
async fn a_refused_construction_reports_in_the_authors_own_currency() {
let refusal = Decode::with_options(&context(), DecodeOptions { threads: 0 })
.await
.expect_err("no threads is no decoder");
assert_eq!(refusal, DecodeError);
}
#[tokio::test]
async fn a_construction_reaching_past_its_declaration_is_refused() {
let refusal = Decode::with_options(&Resources::new(), DecodeOptions { threads: 8 })
.await
.expect_err("nothing built an `Egemma`");
assert_eq!(refusal, DecodeError);
}
#[tokio::test]
async fn a_zero_knob_node_takes_the_unit_options() {
let Watchdog = Watchdog::new(&Resources::new())
.await
.expect("nothing can refuse");
}