mod handler;
mod protocol;
use handler::Handler;
pub use handler::{Config, Failure, Success};
use libp2p_core::{connection::ConnectionId, PeerId};
use libp2p_swarm::{NetworkBehaviour, NetworkBehaviourAction, PollParameters};
use std::{
collections::VecDeque,
task::{Context, Poll},
};
#[deprecated(
since = "0.30.0",
note = "Use re-exports that omit `Ping` prefix, i.e. `libp2p::ping::Config` etc"
)]
pub use self::{
Config as PingConfig, Event as PingEvent, Failure as PingFailure, Result as PingResult,
Success as PingSuccess,
};
#[deprecated(since = "0.30.0", note = "Use libp2p::ping::Behaviour instead.")]
pub use Behaviour as Ping;
pub type Result = std::result::Result<Success, Failure>;
pub struct Behaviour {
config: Config,
events: VecDeque<Event>,
}
#[derive(Debug)]
pub struct Event {
pub peer: PeerId,
pub result: Result,
}
impl Behaviour {
pub fn new(config: Config) -> Self {
Self {
config,
events: VecDeque::new(),
}
}
}
impl Default for Behaviour {
fn default() -> Self {
Self::new(Config::new())
}
}
impl NetworkBehaviour for Behaviour {
type ConnectionHandler = Handler;
type OutEvent = Event;
fn new_handler(&mut self) -> Self::ConnectionHandler {
Handler::new(self.config.clone())
}
fn inject_event(&mut self, peer: PeerId, _: ConnectionId, result: Result) {
self.events.push_front(Event { peer, result })
}
fn poll(
&mut self,
_: &mut Context<'_>,
_: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
if let Some(e) = self.events.pop_back() {
let Event { result, peer } = &e;
match result {
Ok(Success::Ping { .. }) => log::debug!("Ping sent to {:?}", peer),
Ok(Success::Pong) => log::debug!("Ping received from {:?}", peer),
_ => {}
}
Poll::Ready(NetworkBehaviourAction::GenerateEvent(e))
} else {
Poll::Pending
}
}
}