use std::sync::{Arc, Mutex};
use crate::{DirEvent, Error, NetDir, NetDirProvider, Result};
#[derive(Debug, Default)]
pub struct TestNetDirProvider {
current: Mutex<Option<Arc<NetDir>>>,
}
impl TestNetDirProvider {
pub fn new() -> Self {
Self {
current: Mutex::new(None),
}
}
pub fn set_netdir(&self, dir: impl Into<Arc<NetDir>>) {
*self.current.lock().expect("lock poisoned") = Some(dir.into());
}
}
impl From<NetDir> for TestNetDirProvider {
fn from(nd: NetDir) -> Self {
let rv = Self::new();
rv.set_netdir(nd);
rv
}
}
impl NetDirProvider for TestNetDirProvider {
fn netdir(&self, _timeliness: crate::Timeliness) -> Result<Arc<NetDir>> {
match self.current.lock().expect("lock poisoned").as_ref() {
Some(netdir) => Ok(Arc::clone(netdir)),
None => Err(Error::NoInfo),
}
}
fn events(&self) -> futures::stream::BoxStream<'static, DirEvent> {
Box::pin(futures::stream::pending())
}
fn params(&self) -> Arc<dyn AsRef<crate::params::NetParameters>> {
if let Ok(nd) = self.netdir(crate::Timeliness::Unchecked) {
nd
} else {
Arc::new(crate::params::NetParameters::default())
}
}
}