hosts.rs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. use async_std::sync::Mutex;
  2. use rand::seq::SliceRandom;
  3. use std::collections::HashSet;
  4. use std::net::SocketAddr;
  5. use std::sync::Arc;
  6. /// Pointer to hosts class.
  7. pub type HostsPtr = Arc<Hosts>;
  8. /// Manages a store of network addresses.
  9. pub struct Hosts {
  10. addrs: Mutex<Vec<SocketAddr>>,
  11. }
  12. impl Hosts {
  13. /// Create a new host list.
  14. pub fn new() -> Arc<Self> {
  15. Arc::new(Self {
  16. addrs: Mutex::new(Vec::new()),
  17. })
  18. }
  19. /// Checks if a host address is in the host list.
  20. async fn contains(&self, addrs: &[SocketAddr]) -> bool {
  21. let a_set: HashSet<_> = addrs.iter().copied().collect();
  22. self.addrs
  23. .lock()
  24. .await
  25. .iter()
  26. .any(|item| a_set.contains(item))
  27. }
  28. /// Add a new host to the host list.
  29. pub async fn store(&self, addrs: Vec<SocketAddr>) {
  30. if !self.contains(&addrs).await {
  31. self.addrs.lock().await.extend(addrs)
  32. }
  33. }
  34. /// Return a single host address.
  35. pub async fn load_single(&self) -> Option<SocketAddr> {
  36. self.addrs
  37. .lock()
  38. .await
  39. .choose(&mut rand::thread_rng())
  40. .cloned()
  41. }
  42. /// Return the list of hosts.
  43. pub async fn load_all(&self) -> Vec<SocketAddr> {
  44. self.addrs.lock().await.clone()
  45. }
  46. /// Check if the host list is empty.
  47. pub async fn is_empty(&self) -> bool {
  48. self.addrs.lock().await.is_empty()
  49. }
  50. }