From b2fc648e78319ae8998f6e841ddba20523177563 Mon Sep 17 00:00:00 2001 From: Shamil <66209982+shamilsan@users.noreply.github.com> Date: Tue, 12 Dec 2023 21:15:37 +0300 Subject: [PATCH] chore: simplify template (#63) --- src/lib.rs | 27 +++++++-------------------- 1 file changed, 7 insertions(+), 20 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 35daa40..49d7be6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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> = None; -fn state_mut() -> &'static mut HashMap { - 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()`"); }