godrays 0.1.0

Peer Discovery library for Cluster Formation
Documentation
use std::hash::{Hash, Hasher};
use std::net::IpAddr;
use libp2p::{Multiaddr, PeerId};
use libp2p::multiaddr::Protocol;
use local_ip_address::local_ip;
use log::info;
use serde::{Deserialize, Serialize};


#[derive(Serialize, Deserialize, Clone, PartialOrd, Ord, PartialEq, Eq)]
pub struct DiscoveredAddr {
    pub peer_id: PeerId,
    pub addr: Multiaddr,
}

impl DiscoveredAddr {
    pub fn new(peer_id: PeerId, addr: Multiaddr) -> Self {
        Self { peer_id, addr }
    }

    pub fn get_ip(&self) -> String {
        let components = self.addr.iter().collect::<Vec<_>>();
        match components[0] {
            Protocol::Ip4(ip4) => {
                ip4.to_string()
            }
            Protocol::Ip6(ip6) => {
                ip6.to_string()
            }
            _ => {
                local_ip().unwrap().to_string()
            }
        }
    }
}

impl Hash for DiscoveredAddr {
    fn hash<H: Hasher>(&self, state: &mut H) {
        state.write(&self.addr.to_vec().as_slice());
        state.finish();
    }
}

#[derive(Serialize, Deserialize)]
pub struct ClusterAddresses {
    pub addresses: Vec<String>,
}

impl ClusterAddresses {
    pub fn new() -> Self {
        Self {
            addresses: Vec::new(),
        }
    }

    pub fn add(&mut self, addr: String) {
        if !self.addresses.contains(&addr) {
            self.addresses.push(addr);
        }
    }

    pub fn remove(&mut self, addr: String) {
        self.addresses.retain(|a| a != &addr);
    }
}