-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
7 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,49 +1,36 @@ | ||
#![no_std] | ||
|
||
use gstd::{collections::HashMap, errors::Result, msg, prelude::*, ActorId}; | ||
use gstd::{collections::HashMap, msg, prelude::*, ActorId}; | ||
use template_io::*; | ||
|
||
static mut STATE: Option<HashMap<ActorId, u128>> = None; | ||
|
||
fn state_mut() -> &'static mut HashMap<ActorId, u128> { | ||
unsafe { STATE.as_mut().expect("state isn't initialized") } | ||
} | ||
|
||
// The `init()` entry point. | ||
#[no_mangle] | ||
extern fn init() { | ||
unsafe { STATE = Some(HashMap::new()) } | ||
unsafe { STATE = Some(Default::default()) } | ||
} | ||
|
||
// The `handle()` entry point. | ||
#[no_mangle] | ||
extern fn handle() { | ||
process_handle().expect("failed to load, decode, encode, or reply from `handle()`") | ||
} | ||
|
||
fn process_handle() -> Result<()> { | ||
let payload = msg::load()?; | ||
let payload = msg::load().expect("Failed to load payload"); | ||
|
||
if let PingPong::Ping = payload { | ||
let pingers = state_mut(); | ||
let pingers = unsafe { STATE.as_mut().expect("State isn't initialized") }; | ||
|
||
pingers | ||
.entry(msg::source()) | ||
.and_modify(|ping_count| *ping_count = ping_count.saturating_add(1)) | ||
.or_insert(1); | ||
|
||
reply(PingPong::Pong)?; | ||
msg::reply(PingPong::Pong, 0).expect("Failed to reply from `handle()`"); | ||
} | ||
|
||
Ok(()) | ||
} | ||
|
||
// The `state()` entry point. | ||
#[no_mangle] | ||
extern fn state() { | ||
reply(State::from_iter(state_mut().clone())).expect("failed to encode or reply from `state()`") | ||
} | ||
|
||
fn reply(payload: impl Encode) -> Result<()> { | ||
msg::reply(payload, 0).map(|_| ()) | ||
let state = unsafe { STATE.take().expect("State isn't initialized") }; | ||
msg::reply(State::from_iter(state), 0).expect("Failed to reply from `state()`"); | ||
} |