pack/src/util.rs

66 lines
2.0 KiB
Rust

// use std::{
// collections::HashMap,
// hash::Hash,
// marker::Send,
// sync::mpsc::{channel, Sender, TryRecvError},
// sync::{Arc, Mutex},
// thread,
// time::{Duration, SystemTime},
// };
// pub struct TimedHashMap<K, V> {
// map: Arc<Mutex<HashMap<K, (SystemTime, V)>>>,
// duration: Arc<Mutex<Duration>>,
// tx: Sender<i32>,
// }
// // Insert and cleanup send message to a main thread
// // the main looping thread which reads messages to know its next action
// impl<K, V> TimedHashMap<K, V>
// where
// K: std::cmp::Eq + Hash + Send + 'static,
// V: Send + 'static,
// {
// pub fn new() -> Self {
// let (tx, rx) = channel();
// let thp = Self {
// map: Arc::new(Mutex::new(HashMap::<K, (SystemTime, V)>::new())),
// duration: Arc::new(Mutex::new(Duration::new(60, 0))),
// tx,
// };
// let map2 = Arc::clone(&thp.map);
// let dur2 = Arc::clone(&thp.duration);
// // Cleanup thread.
// thread::spawn(move || loop {
// thread::sleep(*dur2.lock().unwrap());
// map2.lock().unwrap().retain(|_, v| v.0 < SystemTime::now());
// match rx.try_recv() {
// // Thread should get killed when tx drops.
// Ok(_) | Err(TryRecvError::Disconnected) => break,
// Err(TryRecvError::Empty) => {}
// }
// });
// thp
// }
// pub fn insert(&mut self, key: K, value: V, time: Duration) -> Option<V> {
// let map2 = Arc::clone(&self.map);
// match map2
// .lock()
// .unwrap()
// .insert(key, (SystemTime::now() + time, value))
// {
// Some(x) => Some(x.1),
// None => None,
// }
// }
// pub fn set_interval(&mut self, duration: Duration) {
// let dur2 = Arc::clone(&self.duration);
// *dur2.lock().unwrap() = duration
// }
// }