icydb_core/db/store/
mod.rs

1mod data;
2mod index;
3
4pub use data::*;
5pub use index::*;
6
7use crate::{Error, db::DbError};
8use std::{cell::RefCell, collections::HashMap, thread::LocalKey};
9use thiserror::Error as ThisError;
10
11///
12/// StoreError
13///
14
15#[derive(Debug, ThisError)]
16pub enum StoreError {
17    #[error("store '{0}' not found")]
18    StoreNotFound(String),
19}
20
21impl From<StoreError> for Error {
22    fn from(err: StoreError) -> Self {
23        DbError::from(err).into()
24    }
25}
26
27///
28/// StoreRegistry
29///
30
31#[derive(Default)]
32pub struct StoreRegistry<T: 'static>(HashMap<&'static str, &'static LocalKey<RefCell<T>>>);
33
34impl<T: 'static> StoreRegistry<T> {
35    // new
36    #[must_use]
37    pub fn new() -> Self {
38        Self(HashMap::new())
39    }
40
41    // iter
42    pub fn iter(&self) -> impl Iterator<Item = (&'static str, &'static LocalKey<RefCell<T>>)> {
43        self.0.iter().map(|(k, v)| (*k, *v))
44    }
45
46    // for_each
47    pub fn for_each<R>(&self, mut f: impl FnMut(&'static str, &T) -> R) {
48        for (path, accessor) in &self.0 {
49            accessor.with(|cell| {
50                let store = cell.borrow();
51                f(path, &store);
52            });
53        }
54    }
55
56    // register
57    pub fn register(&mut self, name: &'static str, accessor: &'static LocalKey<RefCell<T>>) {
58        self.0.insert(name, accessor);
59    }
60
61    // try_get_store
62    pub fn try_get_store(&self, path: &str) -> Result<&'static LocalKey<RefCell<T>>, Error> {
63        self.0
64            .get(path)
65            .copied()
66            .ok_or_else(|| StoreError::StoreNotFound(path.to_string()).into())
67    }
68
69    // with_store
70    pub fn with_store<R>(&self, path: &str, f: impl FnOnce(&T) -> R) -> Result<R, Error> {
71        let store = self.try_get_store(path)?;
72
73        Ok(store.with_borrow(|s| f(s)))
74    }
75
76    // with_store_mut
77    pub fn with_store_mut<R>(&self, path: &str, f: impl FnOnce(&mut T) -> R) -> Result<R, Error> {
78        let store = self.try_get_store(path)?;
79
80        Ok(store.with_borrow_mut(|s| f(s)))
81    }
82}