grippo 0.1.1

Parse, match and scrub data at scale.
Documentation
// Project:   grippo
// File:      src/time/cache.rs
// Purpose:   Time formats built from text at run time, each built once and shared
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

use std::collections::HashMap;
use std::sync::{Arc, PoisonError, RwLock};

use super::{RenderFormat, StrptimeDialect, TimeError, TimeFormat};

/// Formats a caller gets as text at run time, such as a format argument read
/// per record, each built the first time its text is seen and shared after.
///
/// Up to [`FormatCache::limit`] texts are kept for each of parsing and
/// rendering. Past it a text is built on every call and not kept, so a
/// stream of distinct formats can't grow the cache. A format that doesn't
/// build isn't kept either.
#[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 {
    /// The texts kept by [`FormatCache::default`].
    pub const DEFAULT_LIMIT: usize = 1024;

    /// A cache that keeps up to `limit` texts for each of parsing and
    /// rendering.
    #[must_use]
    pub fn new(limit: usize) -> Self {
        Self {
            parse: Shelf::default(),
            render: Shelf::default(),
            limit,
        }
    }

    /// How many texts it keeps for each of parsing and rendering.
    #[must_use]
    pub const fn limit(&self) -> usize {
        self.limit
    }

    /// The format [`TimeFormat::strptime`] builds from `text` in `dialect`.
    ///
    /// # Errors
    ///
    /// As [`TimeFormat::strptime`].
    pub fn time_format(
        &self,
        dialect: StrptimeDialect,
        text: &str,
    ) -> Result<Arc<TimeFormat>, TimeError> {
        self.parse.get(dialect, text, self.limit, || {
            TimeFormat::strptime(dialect, text)
        })
    }

    /// The format [`RenderFormat::strftime`] builds from `text` in `dialect`.
    ///
    /// # Errors
    ///
    /// As [`RenderFormat::strftime`].
    pub fn render_format(
        &self,
        dialect: StrptimeDialect,
        text: &str,
    ) -> Result<Arc<RenderFormat>, TimeError> {
        self.render.get(dialect, text, self.limit, || {
            RenderFormat::strftime(dialect, text)
        })
    }

    /// How many texts it holds for parsing and for rendering.
    #[must_use]
    pub fn len(&self) -> (usize, usize) {
        (self.parse.len(), self.render.len())
    }

    /// It holds no text.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == (0, 0)
    }
}

/// Built formats by text, each text with one for each dialect it was asked in.
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()
    }
}