Skip to content

Commit

Permalink
Truncate cache if max_messages is set to a lower value at runtime
Browse files Browse the repository at this point in the history
  • Loading branch information
Ivin committed Aug 26, 2024
1 parent ba73120 commit 60c5163
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/cache/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -644,6 +644,27 @@ impl Cache {
///
/// By default, no messages will be cached.
pub fn set_max_messages(&self, max: usize) {
let current_max_messages = self.settings.read().max_messages;

// Check if the cache needs to be truncated
if max < current_max_messages {
let difference = current_max_messages - max;

// Iterate over the queues that each correspond to a channel
for mut channel_queue in self.message_queue.iter_mut() {
let channel_id = *channel_queue.key();

for _ in 0..difference {
// Get the message ID from the front of the queue and
// remove it from the corresponding channel's message map
if let Some(message_id) = channel_queue.value_mut().pop_front() {
if let Some(mut channel_messages) = self.messages.get_mut(&channel_id) {
channel_messages.remove(&message_id);
}
}
}
}
}
self.settings.write().max_messages = max;
}

Expand Down

0 comments on commit 60c5163

Please sign in to comment.