term-detect 0.1.8

Terminal emulator detector
Documentation
//! Contains code related to caching the results

use crate::Terminal;
use once_cell::sync::Lazy;
use std::sync::Mutex;
use std::sync::{MutexGuard, PoisonError};
use thiserror::Error;

pub(crate) static TERMINAL: Lazy<Mutex<Option<Terminal>>> = Lazy::new(|| Mutex::new(None));

#[derive(Error, Debug)]
pub enum CacheError {
    #[error("mutex poisoned")]
    MutexError(#[from] PoisonError<MutexGuard<'static, Option<Terminal>>>),
    #[error("cache is empty")]
    EmptyError,
}

/// Try to get the terminal from the cache
pub fn cache_get() -> Result<Terminal, CacheError> {
    let term_lock = TERMINAL.lock()?;
    match term_lock.clone() {
        Some(term) => Ok(term),
        None => Err(CacheError::EmptyError),
    }
}

/// Save the provided terminal in the cache
pub fn cache_set(term: Terminal) -> Result<(), CacheError> {
    let mut term_lock = TERMINAL.lock()?;
    term_lock.replace(term);
    Ok(())
}

/// Remove the cached terminal
pub fn cache_clear() -> Result<Option<Terminal>, CacheError> {
    let mut term_lock = TERMINAL.lock()?;
    Ok(term_lock.take())
}