-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdesign-authentication-manager.rs
50 lines (43 loc) · 1.36 KB
/
design-authentication-manager.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
#![allow(dead_code, unused, unused_variables, non_snake_case)]
fn main() {}
struct Solution;
struct AuthenticationManager {
storage: std::collections::HashMap<String, i32>,
ttl: i32,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
/**
* Your AuthenticationManager object will be instantiated and called as such:
* let obj = AuthenticationManager::new(timeToLive);
* obj.generate(tokenId, currentTime);
* obj.renew(tokenId, currentTime);
* let ret_3: i32 = obj.count_unexpired_tokens(currentTime);
*/
impl AuthenticationManager {
fn new(timeToLive: i32) -> Self {
Self {
ttl: timeToLive,
storage: std::collections::HashMap::new(),
}
}
fn generate(&mut self, token_id: String, current_time: i32) {
self.storage.insert(token_id, current_time);
}
fn renew(&mut self, token_id: String, current_time: i32) {
match self.storage.remove(&token_id) {
Some(x) if x + self.ttl > current_time => {
self.storage.insert(token_id, current_time);
}
_ => {}
}
}
fn count_unexpired_tokens(&self, current_time: i32) -> i32 {
self.storage
.values()
.filter(|x| *x + self.ttl > current_time)
.count() as i32
}
}