pub mod protocol;
pub mod handler;
pub use handler::{PingConfig, PingResult, PingSuccess, PingFailure};
use handler::PingHandler;
use libp2p_core::{Multiaddr, PeerId, connection::ConnectionId};
use libp2p_swarm::{NetworkBehaviour, NetworkBehaviourAction, PollParameters};
use std::{collections::VecDeque, task::Context, task::Poll};
use void::Void;
pub struct Ping {
config: PingConfig,
events: VecDeque<PingEvent>,
}
#[derive(Debug)]
pub struct PingEvent {
pub peer: PeerId,
pub result: PingResult,
}
impl Ping {
pub fn new(config: PingConfig) -> Self {
Ping {
config,
events: VecDeque::new(),
}
}
}
impl Default for Ping {
fn default() -> Self {
Ping::new(PingConfig::new())
}
}
impl NetworkBehaviour for Ping {
type ProtocolsHandler = PingHandler;
type OutEvent = PingEvent;
fn new_handler(&mut self) -> Self::ProtocolsHandler {
PingHandler::new(self.config.clone())
}
fn addresses_of_peer(&mut self, _peer_id: &PeerId) -> Vec<Multiaddr> {
Vec::new()
}
fn inject_connected(&mut self, _: &PeerId) {}
fn inject_disconnected(&mut self, _: &PeerId) {}
fn inject_event(&mut self, peer: PeerId, _: ConnectionId, result: PingResult) {
self.events.push_front(PingEvent { peer, result })
}
fn poll(&mut self, _: &mut Context<'_>, _: &mut impl PollParameters)
-> Poll<NetworkBehaviourAction<Void, PingEvent>>
{
if let Some(e) = self.events.pop_back() {
Poll::Ready(NetworkBehaviourAction::GenerateEvent(e))
} else {
Poll::Pending
}
}
}