icydb_core/db/store/
mod.rs1mod 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#[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#[derive(Default)]
32pub struct StoreRegistry<T: 'static>(HashMap<&'static str, &'static LocalKey<RefCell<T>>>);
33
34impl<T: 'static> StoreRegistry<T> {
35 #[must_use]
37 pub fn new() -> Self {
39 Self(HashMap::new())
40 }
41
42 pub fn iter(&self) -> impl Iterator<Item = (&'static str, &'static LocalKey<RefCell<T>>)> {
45 self.0.iter().map(|(k, v)| (*k, *v))
46 }
47
48 pub fn for_each<R>(&self, mut f: impl FnMut(&'static str, &T) -> R) {
51 for (path, accessor) in &self.0 {
52 accessor.with(|cell| {
53 let store = cell.borrow();
54 f(path, &store);
55 });
56 }
57 }
58
59 pub fn register(&mut self, name: &'static str, accessor: &'static LocalKey<RefCell<T>>) {
62 self.0.insert(name, accessor);
63 }
64
65 pub fn try_get_store(&self, path: &str) -> Result<&'static LocalKey<RefCell<T>>, Error> {
68 self.0
69 .get(path)
70 .copied()
71 .ok_or_else(|| StoreError::StoreNotFound(path.to_string()).into())
72 }
73
74 pub fn with_store<R>(&self, path: &str, f: impl FnOnce(&T) -> R) -> Result<R, Error> {
77 let store = self.try_get_store(path)?;
78
79 Ok(store.with_borrow(|s| f(s)))
80 }
81
82 pub fn with_store_mut<R>(&self, path: &str, f: impl FnOnce(&mut T) -> R) -> Result<R, Error> {
85 let store = self.try_get_store(path)?;
86
87 Ok(store.with_borrow_mut(|s| f(s)))
88 }
89}