hosts.rs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. use async_std::sync::{Arc, Mutex};
  2. use fxhash::FxHashSet;
  3. use url::Url;
  4. /// Pointer to hosts class.
  5. pub type HostsPtr = Arc<Hosts>;
  6. /// Manages a store of network addresses.
  7. pub struct Hosts {
  8. addrs: Mutex<Vec<Url>>,
  9. }
  10. impl Hosts {
  11. /// Create a new host list.
  12. pub fn new() -> Arc<Self> {
  13. Arc::new(Self { addrs: Mutex::new(Vec::new()) })
  14. }
  15. /// Checks if a host address is in the host list.
  16. async fn contains(&self, addrs: &[Url]) -> bool {
  17. let a_set: FxHashSet<_> = addrs.iter().cloned().collect();
  18. self.addrs.lock().await.iter().any(|item| a_set.contains(item))
  19. }
  20. /// Add a new host to the host list.
  21. pub async fn store(&self, addrs: Vec<Url>) {
  22. if !self.contains(&addrs).await {
  23. self.addrs.lock().await.extend(addrs)
  24. }
  25. }
  26. /// Return the list of hosts.
  27. pub async fn load_all(&self) -> Vec<Url> {
  28. self.addrs.lock().await.clone()
  29. }
  30. /// Check if the host list is empty.
  31. pub async fn is_empty(&self) -> bool {
  32. self.addrs.lock().await.is_empty()
  33. }
  34. }