Skip to content

Commit

Permalink
chore: simplify template (#63)
Browse files Browse the repository at this point in the history
  • Loading branch information
shamilsan authored Dec 12, 2023
1 parent 6dda8b5 commit b2fc648
Showing 1 changed file with 7 additions and 20 deletions.
27 changes: 7 additions & 20 deletions src/lib.rs
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()`");
}

0 comments on commit b2fc648

Please sign in to comment.