2022-07-17 12:15:38 -05:00
|
|
|
use std::collections::{HashMap, VecDeque};
|
|
|
|
use tokio::sync::RwLock;
|
|
|
|
|
|
|
|
pub struct MessageHistory {
|
|
|
|
map: RwLock<HashMap<String, VecDeque<String>>>,
|
2022-07-17 13:10:34 -05:00
|
|
|
maxlen: usize,
|
2022-07-17 12:15:38 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
impl MessageHistory {
|
|
|
|
pub fn new(maxlen: usize) -> MessageHistory {
|
|
|
|
MessageHistory {
|
|
|
|
map: RwLock::new(HashMap::new()),
|
2022-07-17 13:10:34 -05:00
|
|
|
maxlen,
|
2022-07-17 12:15:38 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn last_msg(&self, user: &str) -> Option<String> {
|
|
|
|
let map = self.map.read().await;
|
|
|
|
map.get(user).and_then(|d| d.get(0)).map(|s| s.to_string())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn last_msgs(&self, user: &str, count: usize) -> Option<Vec<String>> {
|
|
|
|
let map = self.map.read().await;
|
|
|
|
if let Some(deque) = map.get(user) {
|
2022-07-17 13:10:34 -05:00
|
|
|
let count = if deque.len() < count {
|
|
|
|
deque.len()
|
|
|
|
} else {
|
|
|
|
count
|
|
|
|
};
|
|
|
|
Some(
|
|
|
|
deque
|
|
|
|
.range(..count)
|
|
|
|
.rev()
|
|
|
|
.map(ToString::to_string)
|
|
|
|
.collect(),
|
|
|
|
)
|
2022-07-17 12:15:38 -05:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-17 13:10:34 -05:00
|
|
|
pub async fn edit_message(&self, user: &str, pos: usize, edited: String) -> bool {
|
|
|
|
let mut map = self.map.write().await;
|
|
|
|
if let Some(deque) = map.get_mut(user) {
|
|
|
|
if let Some(old) = deque.get_mut(pos) {
|
|
|
|
*old = edited;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
false
|
|
|
|
}
|
|
|
|
|
2022-07-17 12:15:38 -05:00
|
|
|
pub async fn add_message(&self, user: &str, message: &str) {
|
|
|
|
let mut map = self.map.write().await;
|
|
|
|
if let Some(deque) = map.get_mut(user) {
|
|
|
|
if deque.len() == self.maxlen {
|
2022-07-17 13:10:34 -05:00
|
|
|
deque.remove(deque.len() - 1);
|
2022-07-17 12:15:38 -05:00
|
|
|
}
|
|
|
|
deque.push_front(message.to_string());
|
|
|
|
} else {
|
|
|
|
let mut deque = VecDeque::with_capacity(self.maxlen);
|
|
|
|
deque.push_front(message.to_string());
|
|
|
|
map.insert(user.to_string(), deque);
|
|
|
|
}
|
|
|
|
}
|
2022-07-17 13:10:34 -05:00
|
|
|
}
|