1
//! A testing implementation of [`NetDirProvider`].
2

            
3
use std::sync::{Arc, Mutex};
4

            
5
use crate::{DirEvent, Error, NetDir, NetDirProvider, Result};
6

            
7
/// Helper implementation of a [`NetDirProvider`].
8
///
9
/// A [`TestNetDirProvider`] can be used to provide a netdir in a single
10
/// situation that requires a [`NetDirProvider`].  It does not yet notify its
11
/// owner of any changes; it only provides a [`NetDir`].
12
#[derive(Debug, Default)]
13
pub struct TestNetDirProvider {
14
    /// The latest netdir that this will return.
15
    current: Mutex<Option<Arc<NetDir>>>,
16
}
17

            
18
impl TestNetDirProvider {
19
    /// Create a new [`TestNetDirProvider`] with no netdir available.
20
144
    pub fn new() -> Self {
21
144
        Self {
22
144
            current: Mutex::new(None),
23
144
        }
24
144
    }
25

            
26
    /// Replace the `NetDir` in this [`TestNetDirProvider`].
27
144
    pub fn set_netdir(&self, dir: impl Into<Arc<NetDir>>) {
28
144
        *self.current.lock().expect("lock poisoned") = Some(dir.into());
29
144
    }
30
}
31

            
32
impl From<NetDir> for TestNetDirProvider {
33
144
    fn from(nd: NetDir) -> Self {
34
144
        let rv = Self::new();
35
144
        rv.set_netdir(nd);
36
144
        rv
37
144
    }
38
}
39

            
40
impl NetDirProvider for TestNetDirProvider {
41
352
    fn netdir(&self, _timeliness: crate::Timeliness) -> Result<Arc<NetDir>> {
42
352
        match self.current.lock().expect("lock poisoned").as_ref() {
43
352
            Some(netdir) => Ok(Arc::clone(netdir)),
44
            None => Err(Error::NoInfo),
45
        }
46
352
    }
47

            
48
284
    fn events(&self) -> futures::stream::BoxStream<'static, DirEvent> {
49
284
        Box::pin(futures::stream::pending())
50
284
    }
51

            
52
56
    fn params(&self) -> Arc<dyn AsRef<crate::params::NetParameters>> {
53
56
        if let Ok(nd) = self.netdir(crate::Timeliness::Unchecked) {
54
56
            nd
55
        } else {
56
            Arc::new(crate::params::NetParameters::default())
57
        }
58
56
    }
59
}