use actix_web::web::Bytes;
use linked_hash_map::LinkedHashMap;
use parking_lot::RwLock;
use rand::{Rng, distr::Alphanumeric, rng};
use std::{cell::RefCell, sync::LazyLock};
pub type PasteStore = RwLock<LinkedHashMap<String, Bytes>>;
static BUFFER_SIZE: LazyLock<usize> =
LazyLock::new(|| argh::from_env::<crate::BinArgs>().buffer_size);
fn purge_old(entries: &mut LinkedHashMap<String, Bytes>) {
if entries.len() > *BUFFER_SIZE {
let to_remove = entries.len() - *BUFFER_SIZE;
for _ in 0..to_remove {
entries.pop_front();
}
}
}
pub fn generate_id() -> String {
thread_local!(static KEYGEN: RefCell<gpw::PasswordGenerator> = RefCell::new(gpw::PasswordGenerator::default()));
KEYGEN.with(|k| k.borrow_mut().next()).unwrap_or_else(|| {
rng()
.sample_iter(&Alphanumeric)
.take(6)
.map(char::from)
.collect()
})
}
pub fn store_paste(entries: &PasteStore, id: String, content: Bytes) {
let mut entries = entries.write();
purge_old(&mut entries);
entries.insert(id, content);
}
pub fn get_paste(entries: &PasteStore, id: &str) -> Option<Bytes> {
entries.read().get(id).cloned()
}