use std::fmt;
use std::sync::Arc;
use crate::error::Error;
use crate::module::Module;
pub struct Link<M> {
module: Option<Arc<M>>,
}
impl<M> Link<M> {
pub(crate) fn on(module: Arc<M>) -> Self {
Self {
module: Some(module),
}
}
pub(crate) fn off() -> Self {
Self { module: None }
}
pub fn get(&self) -> Option<&Arc<M>> {
self.module.as_ref()
}
pub fn is_on(&self) -> bool {
self.module.is_some()
}
}
impl<M: Module> Link<M> {
pub fn required(&self) -> Result<Arc<M>, Error> {
self.module.clone().ok_or(Error::Off { module: M::NAME })
}
}
impl<M> Clone for Link<M> {
fn clone(&self) -> Self {
Self {
module: self.module.clone(),
}
}
}
impl<M> fmt::Debug for Link<M> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Link")
.field("on", &self.module.is_some())
.finish()
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::Link;
use crate::error::Error;
struct Supplier;
#[async_trait::async_trait]
impl crate::Module for Supplier {
const NAME: &'static str = "Supplier";
type Config = crate::NoSettings;
type Args = ();
async fn create(
_: Self::Config,
(): Self::Args,
_: &mut crate::Context<'_>,
) -> Result<Self, crate::ModuleError> {
Ok(Self)
}
}
#[test]
fn on_link_gives_the_module() {
let link = Link::on(Arc::new(Supplier));
assert!(link.is_on());
assert!(link.get().is_some());
assert!(link.required().is_ok());
}
#[test]
fn off_link_is_empty_and_required_names_the_module() {
let link: Link<Supplier> = Link::off();
assert!(!link.is_on());
assert!(link.get().is_none());
let error = link.required().err().expect("the module is off");
assert!(matches!(error, Error::Off { module: "Supplier" }));
}
}