1use std::fmt;
4use std::sync::Arc;
5
6use crate::error::Error;
7use crate::module::Module;
8
9pub struct Link<M> {
14 module: Option<Arc<M>>,
15}
16
17impl<M> Link<M> {
18 pub(crate) fn on(module: Arc<M>) -> Self {
19 Self {
20 module: Some(module),
21 }
22 }
23
24 pub(crate) fn off() -> Self {
25 Self { module: None }
26 }
27
28 pub fn get(&self) -> Option<&Arc<M>> {
30 self.module.as_ref()
31 }
32
33 pub fn is_on(&self) -> bool {
35 self.module.is_some()
36 }
37}
38
39impl<M: Module> Link<M> {
40 pub fn required(&self) -> Result<Arc<M>, Error> {
42 self.module.clone().ok_or(Error::Off { module: M::NAME })
43 }
44}
45
46impl<M> Clone for Link<M> {
47 fn clone(&self) -> Self {
48 Self {
49 module: self.module.clone(),
50 }
51 }
52}
53
54impl<M> fmt::Debug for Link<M> {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 f.debug_struct("Link")
57 .field("on", &self.module.is_some())
58 .finish()
59 }
60}
61
62#[cfg(test)]
63mod tests {
64 use std::sync::Arc;
65
66 use super::Link;
67 use crate::error::Error;
68
69 struct Supplier;
70
71 #[async_trait::async_trait]
72 impl crate::Module for Supplier {
73 const NAME: &'static str = "Supplier";
74 type Config = crate::NoSettings;
75 type Args = ();
76
77 async fn create(
78 _: Self::Config,
79 (): Self::Args,
80 _: &mut crate::Context<'_>,
81 ) -> Result<Self, crate::ModuleError> {
82 Ok(Self)
83 }
84 }
85
86 #[test]
87 fn on_link_gives_the_module() {
88 let link = Link::on(Arc::new(Supplier));
89 assert!(link.is_on());
90 assert!(link.get().is_some());
91 assert!(link.required().is_ok());
92 }
93
94 #[test]
95 fn off_link_is_empty_and_required_names_the_module() {
96 let link: Link<Supplier> = Link::off();
97 assert!(!link.is_on());
98 assert!(link.get().is_none());
99 let error = link.required().err().expect("the module is off");
100 assert!(matches!(error, Error::Off { module: "Supplier" }));
101 }
102}