use futures::channel::oneshot::Sender as OneshotSender;
use rand::RngCore;
use std::{collections::HashMap, sync::Arc, time::Instant};
use tokio::sync::RwLock;
pub type RequestKey = u64;
pub fn generate_request_key<R>(rng: &mut R) -> RequestKey
where R: RngCore {
rng.next_u64()
}
#[allow(clippy::type_complexity)]
pub struct WaitingRequests<T> {
requests: Arc<RwLock<HashMap<RequestKey, Option<(OneshotSender<T>, Instant)>>>>,
}
impl<T> WaitingRequests<T> {
pub fn new() -> Self {
Self {
requests: Arc::new(RwLock::new(HashMap::new())),
}
}
pub async fn insert(&self, key: RequestKey, reply_tx: OneshotSender<T>) {
self.requests
.write()
.await
.insert(key, Some((reply_tx, Instant::now())));
}
pub async fn remove(&self, key: RequestKey) -> Option<(OneshotSender<T>, Instant)> {
self.requests.write().await.remove(&key).unwrap_or(None)
}
}
impl<T> Clone for WaitingRequests<T> {
fn clone(&self) -> Self {
Self {
requests: self.requests.clone(),
}
}
}
impl<T> Default for WaitingRequests<T> {
fn default() -> Self {
WaitingRequests::new()
}
}