-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmap.rs
76 lines (65 loc) · 2.21 KB
/
map.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/// Deprecated now I'm using a Dashmap for thread-safe lazy instantiation of static variables i.e User HashMap !
use std::{
collections::HashMap,
sync::Mutex
};
use crate::{
structs::UserLimits,
util::get_request_limit_from_plan_name
};
pub static mut CONNECTION_HASH: Mutex<Option<HashMap<String, UserLimits>>> = Mutex::new(None);
pub fn init_map() {
let mut guarded_hash = unsafe { CONNECTION_HASH.lock().unwrap() };
*guarded_hash = Some(HashMap::<String, UserLimits>::new());
}
pub fn get_user_hash_map() -> Result<String, serde_json::Error> {
let guarded_hash = unsafe { CONNECTION_HASH.lock().unwrap() };
serde_json::to_string(guarded_hash.as_ref().unwrap())
}
pub fn reset_all_users_values() {
let mut guarded_hash = unsafe { CONNECTION_HASH.lock().unwrap() };
if let Some(map) = guarded_hash.as_mut() {
for (_, user) in map.iter_mut() {
user.hits = get_request_limit_from_plan_name(&user.plan);
user.connections = 0
}
}
}
pub fn add_user_to_hash(key: String, user: UserLimits) {
let mut guarded_hash = unsafe { CONNECTION_HASH.lock().unwrap() };
if let Some(map) = guarded_hash.as_mut() {
map.insert(key, user);
}
println!("HashMap length: `{}`", guarded_hash.as_ref().unwrap().len());
}
pub fn remove_user_from_hash(key: &str) {
let mut guarded_hash = unsafe { CONNECTION_HASH.lock().unwrap() };
if let Some(map) = guarded_hash.as_mut() {
map.remove(key);
}
}
pub fn decrement_user_hits(key: &str) {
let mut guarded_hash = unsafe { CONNECTION_HASH.lock().unwrap() };
if let Some(map) = guarded_hash.as_mut() {
if let Some(user) = map.get_mut(key) {
user.hits -= 1;
}
}
}
pub fn get_user_from_hash(key: &str) -> Option<UserLimits> {
let guarded_hash = unsafe { CONNECTION_HASH.lock().unwrap() };
if let Some(map) = guarded_hash.as_ref() {
map.get(key).cloned()
}
else {
None
}
}
pub fn increment_user_connections(key: &str) {
let mut guarded_hash = unsafe { CONNECTION_HASH.lock().unwrap() };
if let Some(map) = guarded_hash.as_mut() {
if let Some(user) = map.get_mut(key) {
user.connections += 1;
}
}
}