use std::collections::HashMap;
use std::sync::{Arc, PoisonError, RwLock};
use super::{RenderFormat, StrptimeDialect, TimeError, TimeFormat};
#[derive(Debug)]
pub struct FormatCache {
parse: Shelf<TimeFormat>,
render: Shelf<RenderFormat>,
limit: usize,
}
impl Default for FormatCache {
fn default() -> Self {
Self::new(Self::DEFAULT_LIMIT)
}
}
impl FormatCache {
pub const DEFAULT_LIMIT: usize = 1024;
#[must_use]
pub fn new(limit: usize) -> Self {
Self {
parse: Shelf::default(),
render: Shelf::default(),
limit,
}
}
#[must_use]
pub const fn limit(&self) -> usize {
self.limit
}
pub fn time_format(
&self,
dialect: StrptimeDialect,
text: &str,
) -> Result<Arc<TimeFormat>, TimeError> {
self.parse.get(dialect, text, self.limit, || {
TimeFormat::strptime(dialect, text)
})
}
pub fn render_format(
&self,
dialect: StrptimeDialect,
text: &str,
) -> Result<Arc<RenderFormat>, TimeError> {
self.render.get(dialect, text, self.limit, || {
RenderFormat::strftime(dialect, text)
})
}
#[must_use]
pub fn len(&self) -> (usize, usize) {
(self.parse.len(), self.render.len())
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == (0, 0)
}
}
type Built<T> = HashMap<Box<str>, Vec<(StrptimeDialect, Arc<T>)>>;
#[derive(Debug)]
struct Shelf<T>(RwLock<Built<T>>);
impl<T> Default for Shelf<T> {
fn default() -> Self {
Self(RwLock::new(HashMap::new()))
}
}
impl<T> Shelf<T> {
fn get(
&self,
dialect: StrptimeDialect,
text: &str,
limit: usize,
make: impl FnOnce() -> Result<T, TimeError>,
) -> Result<Arc<T>, TimeError> {
let found = |shelf: &Built<T>| {
shelf
.get(text)?
.iter()
.find(|(d, _)| *d == dialect)
.map(|(_, format)| Arc::clone(format))
};
let held = found(&self.0.read().unwrap_or_else(PoisonError::into_inner));
if let Some(format) = held {
return Ok(format);
}
let format = Arc::new(make()?);
let mut writer = self.0.write().unwrap_or_else(PoisonError::into_inner);
if let Some(raced) = found(&writer) {
return Ok(raced);
}
if let Some(entry) = writer.get_mut(text) {
entry.push((dialect, Arc::clone(&format)));
} else if writer.len() < limit {
writer.insert(text.into(), vec![(dialect, Arc::clone(&format))]);
}
drop(writer);
Ok(format)
}
fn len(&self) -> usize {
self.0.read().unwrap_or_else(PoisonError::into_inner).len()
}
}