hosts.rs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. use async_std::sync::Mutex;
  2. use rand::seq::SliceRandom;
  3. use std::{collections::HashSet, net::SocketAddr, sync::Arc};
  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<SocketAddr>>,
  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: &[SocketAddr]) -> bool {
  17. let a_set: HashSet<_> = addrs.iter().copied().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<SocketAddr>) {
  22. if !self.contains(&addrs).await {
  23. self.addrs.lock().await.extend(addrs)
  24. }
  25. }
  26. /// Return a single host address.
  27. pub async fn load_single(&self) -> Option<SocketAddr> {
  28. self.addrs.lock().await.choose(&mut rand::thread_rng()).cloned()
  29. }
  30. /// Return the list of hosts.
  31. pub async fn load_all(&self) -> Vec<SocketAddr> {
  32. self.addrs.lock().await.clone()
  33. }
  34. /// Check if the host list is empty.
  35. pub async fn is_empty(&self) -> bool {
  36. self.addrs.lock().await.is_empty()
  37. }
  38. }