From 7da5daf5226fa306a9efbf3aa8a3e40696670584 Mon Sep 17 00:00:00 2001 From: MedzikUser Date: Wed, 17 Aug 2022 15:40:11 +0200 Subject: [PATCH] feat(client): HashMap add Mutex and functions Changed map type in Client struct to Arc>>. Implemented functions insert_key, get_value and delete_key to the Client type. Re-export servers::server::ClientMapValue in servers::plugins::prelude. --- src/plugins/mod.rs | 2 +- src/server/client.rs | 35 +++++++++++++++++++++++++++-------- 2 files changed, 28 insertions(+), 9 deletions(-) diff --git a/src/plugins/mod.rs b/src/plugins/mod.rs index 1cbb1b9..38ef9bf 100644 --- a/src/plugins/mod.rs +++ b/src/plugins/mod.rs @@ -12,5 +12,5 @@ pub mod prelude { pub use async_trait::async_trait; pub use self::types::*; - pub use crate::server::Client; + pub use crate::server::{Client, ClientMapValue}; } diff --git a/src/server/client.rs b/src/server/client.rs index 53e33df..5f1480e 100644 --- a/src/server/client.rs +++ b/src/server/client.rs @@ -22,7 +22,7 @@ pub struct Client { /// Connection stream of the client pub stream: ClientStream, /// Custom Client Map - pub map: HashMap, + pub map: Arc>>, /// Plugins Manager pub plugins_manager: PluginsManagerType, } @@ -38,15 +38,10 @@ pub struct Client { /// Value type of the client map entry #[derive(Debug, Clone)] pub enum ClientMapValue { - /// String type String(String), - /// Vector with String type Array(Vec), - /// bool type Bool(bool), - /// isize type Int(isize), - /// usize type UInt(usize), } @@ -64,7 +59,7 @@ impl From for Client { Self { id: 0, stream: ClientStream::TCP(Arc::new(stream)), - map: HashMap::new(), + map: Arc::new(Mutex::new(HashMap::new())), plugins_manager: PLUGINS_MANAGER.clone(), } } @@ -75,7 +70,7 @@ impl From> for Client { Self { id: 0, stream: ClientStream::WebSocket(Arc::new(Mutex::new(stream))), - map: HashMap::new(), + map: Arc::new(Mutex::new(HashMap::new())), plugins_manager: PLUGINS_MANAGER.clone(), } } @@ -189,6 +184,30 @@ impl Client { Ok(()) } + /// Inserts a key-value pair into the map. + pub fn insert_key(&self, key: S, value: ClientMapValue) -> Option + where + S: ToString, + { + self.map.lock().unwrap().insert(key.to_string(), value) + } + + /// Returns the value from the key. + pub fn get_value(&self, key: S) -> Option + where + S: ToString, + { + self.map.lock().unwrap().get(&key.to_string()).cloned() + } + + /// Delete key from the map. + pub fn delete_key(&self, key: S) -> Option + where + S: ToString, + { + self.map.lock().unwrap().remove(&key.to_string()) + } + pub async fn run_events(&self, event_type: EventType) -> anyhow::Result<()> { for event in self.plugins_manager.events.iter() { if event.event() == event_type {