Skip to main content

anathema_store/store/
shared.rs

1use std::cell::RefCell;
2
3use super::OwnedKey;
4use crate::slab::{RcElement, RcSlab, SharedSlab};
5
6// -----------------------------------------------------------------------------
7//   - Shared key -
8// -----------------------------------------------------------------------------
9#[derive(Debug, Copy, Clone, PartialEq)]
10pub struct SharedKey(pub u32, pub OwnedKey);
11
12impl From<SharedKey> for usize {
13    fn from(key: SharedKey) -> usize {
14        key.0 as usize
15    }
16}
17
18impl From<SharedKey> for OwnedKey {
19    fn from(key: SharedKey) -> OwnedKey {
20        key.1
21    }
22}
23
24// -----------------------------------------------------------------------------
25//   - Shared storage -
26// -----------------------------------------------------------------------------
27pub struct Shared<T> {
28    inner: RefCell<RcSlab<usize, T>>,
29}
30
31impl<T> Shared<T> {
32    pub const fn empty() -> Self {
33        Self {
34            inner: RefCell::new(RcSlab::empty()),
35        }
36    }
37
38    // Get a shared value under the assumption that the value exists.
39    // This should only be called if the Rc::strong count is greater than one
40    pub fn get(&self, key: SharedKey) -> RcElement<T> {
41        self.inner
42            .borrow_mut()
43            .get(key.into())
44            .expect("the value exists because the shared key exists")
45    }
46
47    pub fn insert(&self, owned_key: OwnedKey, value: T) -> SharedKey {
48        let key = self.inner.borrow_mut().insert(value);
49        SharedKey(key as u32, owned_key)
50    }
51
52    pub fn try_evict(&self, key: SharedKey) -> Option<T> {
53        self.inner.borrow_mut().try_remove(key.into())
54    }
55
56    pub fn for_each<F>(&self, mut f: F)
57    where
58        F: FnMut(usize, &T),
59    {
60        self.inner.borrow().iter().for_each(|(k, v)| f(k, v));
61    }
62}
63
64impl<T: std::fmt::Debug> Shared<T> {
65    pub fn dump_state(&self) -> String {
66        self.inner.borrow().dump_state()
67    }
68}