use tokactor::{Actor, Ask, AskResult, Ctx};
use tracing::Level;
pub struct PingPong {
counter: u8,
}
#[derive(Debug, Clone)]
pub enum Msg {
Ping,
Pong,
}
impl Msg {
fn next(&self) -> Self {
match self {
Self::Ping => Self::Pong,
Self::Pong => Self::Ping,
}
}
fn print(&self) {
match self {
Self::Ping => print!("ping.."),
Self::Pong => print!("pong.."),
}
}
}
impl Actor for PingPong {}
impl Ask<Msg> for PingPong {
type Result = Msg;
fn handle(&mut self, message: Msg, _: &mut Ctx<Self>) -> AskResult<Self::Result> {
message.print();
self.counter += 1;
AskResult::Reply(message.next())
}
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.pretty()
.with_max_level(Level::TRACE)
.with_writer(std::io::stdout)
.init();
tracing::info!("Starting up...");
let handle = PingPong { counter: 0 }.start();
let mut message = Msg::Ping;
for _ in 0..10 {
message = handle.ask(message).await.unwrap();
}
let actor = handle
.await
.expect("Ping-pong actor failed to exit properly");
assert_eq!(actor.counter, 10);
println!("\nProcessed {} messages", actor.counter);
}