simple_counter/
simple_counter.rs1use actor12::{Actor, Envelope, Exec, Init, MpscChannel, spawn};
2use std::future::Future;
3
4pub struct Counter {
6 count: i32,
7}
8
9type CounterMessage = Envelope<CounterRequest, anyhow::Result<CounterResponse>>;
11
12#[derive(Debug)]
13pub enum CounterRequest {
14 Increment,
15 GetCount,
16}
17
18#[derive(Debug)]
19pub enum CounterResponse {
20 Unit,
21 Count(i32),
22}
23
24impl Actor for Counter {
25 type Spec = i32; type Message = CounterMessage;
27 type Channel = MpscChannel<Self::Message>;
28 type Cancel = ();
29 type State = ();
30
31 fn state(_spec: &Self::Spec) -> Self::State {}
32
33 fn init(ctx: Init<'_, Self>) -> impl Future<Output = Result<Self, Self::Cancel>> + Send + 'static {
34 let initial_count = ctx.spec;
35 println!("Counter actor initialized with count: {}", initial_count);
36 futures::future::ready(Ok(Counter { count: initial_count }))
37 }
38
39 async fn handle(&mut self, _ctx: Exec<'_, Self>, msg: Self::Message) {
40 match msg.value {
41 CounterRequest::Increment => {
42 self.count += 1;
43 println!("Count incremented to: {}", self.count);
44 msg.reply.send(Ok(CounterResponse::Unit)).unwrap();
45 }
46 CounterRequest::GetCount => {
47 println!("Current count requested: {}", self.count);
48 msg.reply.send(Ok(CounterResponse::Count(self.count))).unwrap();
49 }
50 }
51 }
52}
53
54#[tokio::main]
55async fn main() -> anyhow::Result<()> {
56 let counter = spawn::<Counter>(0);
58
59 let _: anyhow::Result<CounterResponse> = counter.send(CounterRequest::Increment).await;
61 let _: anyhow::Result<CounterResponse> = counter.send(CounterRequest::Increment).await;
62 let _: anyhow::Result<CounterResponse> = counter.send(CounterRequest::Increment).await;
63
64 let response: anyhow::Result<CounterResponse> = counter.send(CounterRequest::GetCount).await;
66 match response? {
67 CounterResponse::Count(count) => println!("Final count: {}", count),
68 _ => println!("Unexpected response"),
69 }
70
71 Ok(())
72}