1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//! 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())
}