Skip to main content

datex_core/runtime/cache/
shared_values_cache.rs

1use crate::{
2    collections::HashMap,
3    prelude::*,
4    shared_values::{
5        OwnedSharedContainer, PointerAddress, ReferenceMutability,
6        ReferencedSharedContainer, SharedContainer, SharedContainerOwnership,
7        errors::{
8            UnexpectedImmutableReferenceError,
9            UnexpectedSharedContainerOwnershipError,
10        },
11    },
12};
13use core::fmt::Display;
14use strum_macros::Display;
15/// Cache layer that stores references or owned and referenced shared containers
16#[derive(Debug, Default)]
17pub struct SharedValuesCache {
18    values: HashMap<PointerAddress, SharedContainer>,
19}
20
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct ValueNotFoundInCacheError;
23
24impl Display for ValueNotFoundInCacheError {
25    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
26        write!(f, "Value not found in cache")
27    }
28}
29
30#[derive(Debug, Clone, PartialEq, Eq, Display)]
31pub enum CacheValueRetrievalError {
32    UnexpectedImmutableReference(UnexpectedImmutableReferenceError),
33    UnexpectedSharedContainerOwnership(UnexpectedSharedContainerOwnershipError),
34    ValueNotFoundInCache(ValueNotFoundInCacheError),
35}
36
37impl From<UnexpectedImmutableReferenceError> for CacheValueRetrievalError {
38    fn from(error: UnexpectedImmutableReferenceError) -> Self {
39        CacheValueRetrievalError::UnexpectedImmutableReference(error)
40    }
41}
42
43impl From<ValueNotFoundInCacheError> for CacheValueRetrievalError {
44    fn from(error: ValueNotFoundInCacheError) -> Self {
45        CacheValueRetrievalError::ValueNotFoundInCache(error)
46    }
47}
48
49impl From<UnexpectedSharedContainerOwnershipError>
50    for CacheValueRetrievalError
51{
52    fn from(error: UnexpectedSharedContainerOwnershipError) -> Self {
53        CacheValueRetrievalError::UnexpectedSharedContainerOwnership(error)
54    }
55}
56
57impl SharedValuesCache {
58    /// Creates a new SharedValuesCache and populates it with the provided shared containers.
59    /// Assumes that all provided containers have unique pointer addresses.
60    pub fn new(values: Vec<SharedContainer>) -> Self {
61        SharedValuesCache {
62            values: values
63                .into_iter()
64                .map(|container| (container.pointer_address(), container))
65                .collect(),
66        }
67    }
68
69    /// Stores a shared container in the cache, indexed by its pointer address.
70    /// If a container already exists at the address, the container with the maximum ownership is kept.
71    pub fn store_shared_container(&mut self, container: SharedContainer) {
72        if let Some(existing) = self.values.get(&container.pointer_address())
73            && existing.ownership() > container.ownership()
74        {
75            return;
76        }
77        self.values.insert(container.pointer_address(), container);
78    }
79
80    /// Removes the shared container for the given pointer address from the cache, if it exists.
81    pub fn remove_shared_container(
82        &mut self,
83        pointer_address: &PointerAddress,
84    ) {
85        self.values.remove(pointer_address);
86    }
87
88    /// Tries to take an owned shared container from the cache for the given pointer address.
89    /// If the container for the address is not an owned shared container, or if there is no container for the address, None is returned and the cache is not modified.
90    /// If an owned shared container is found for the address, it is replaced with a reference in the cache and the owned container is returned
91    pub fn try_take_owned_shared_container(
92        &mut self,
93        pointer_address: &PointerAddress,
94    ) -> Result<OwnedSharedContainer, CacheValueRetrievalError> {
95        match self.values.get(pointer_address) {
96            Some(container) => {
97                match container {
98                    SharedContainer::Owned(container) => {
99                        // replace owned with reference in cache and return owned
100                        match self.values.insert(
101                            pointer_address.clone(),
102                            SharedContainer::Referenced(
103                                container.derive_with_max_mutability(),
104                            ),
105                        ) {
106                            Some(SharedContainer::Owned(owned_container)) => {
107                                Ok(owned_container)
108                            }
109                            _ => unreachable!(),
110                        }
111                    }
112                    SharedContainer::Referenced(reference) => {
113                        Err(UnexpectedSharedContainerOwnershipError {
114                            actual: SharedContainerOwnership::Referenced(
115                                reference.reference_mutability(),
116                            ),
117                            expected: SharedContainerOwnership::Owned,
118                        }
119                        .into())
120                    }
121                }
122            }
123            _ => Err(ValueNotFoundInCacheError.into()),
124        }
125    }
126
127    pub fn try_get_shared_container(
128        &self,
129        pointer_address: &PointerAddress,
130    ) -> Result<&SharedContainer, ValueNotFoundInCacheError> {
131        self.values
132            .get(pointer_address)
133            .ok_or(ValueNotFoundInCacheError)
134    }
135
136    /// Tries to get a mutable reference to a shared container from the cache at the given pointer address.
137    /// If the container for the address is not in the cache, a [ValueNotFoundInCacheError] is returned.
138    /// If the container cannot be accessed as a mutable reference, an [UnexpectedImmutableReferenceError] error is returned.
139    pub fn try_get_shared_container_mutable_reference(
140        &self,
141        pointer_address: &PointerAddress,
142    ) -> Result<ReferencedSharedContainer, CacheValueRetrievalError> {
143        Ok(self
144            .values
145            .get(pointer_address)
146            .ok_or(ValueNotFoundInCacheError)?
147            .try_derive_mutable_reference()?)
148    }
149
150    /// Tries to get an immutable reference to a shared container from the cache at the given pointer address.
151    /// If the container for the address is not in the cache, a [ValueNotFoundInCacheError] is returned.
152    pub fn try_get_shared_container_immutable_reference(
153        &self,
154        pointer_address: &PointerAddress,
155    ) -> Result<ReferencedSharedContainer, ValueNotFoundInCacheError> {
156        Ok(self
157            .values
158            .get(pointer_address)
159            .ok_or(ValueNotFoundInCacheError)?
160            .derive_immutable_reference())
161    }
162
163    /// Tries to get a shared container from the cache at the given pointer address with the specified ownership.
164    /// If the container for the address is not in the cache, or if the container cannot be accessed with the specified ownership, a [CacheValueRetrievalError] is returned.
165    pub fn try_get_shared_container_with_ownership(
166        &mut self,
167        pointer_address: &PointerAddress,
168        ownership: SharedContainerOwnership,
169    ) -> Result<SharedContainer, CacheValueRetrievalError> {
170        match ownership {
171            SharedContainerOwnership::Owned => self
172                .try_take_owned_shared_container(pointer_address)
173                .map(SharedContainer::Owned),
174            SharedContainerOwnership::Referenced(
175                ReferenceMutability::Mutable,
176            ) => self
177                .try_get_shared_container_mutable_reference(pointer_address)
178                .map(SharedContainer::Referenced),
179            SharedContainerOwnership::Referenced(
180                ReferenceMutability::Immutable,
181            ) => Ok(self
182                .try_get_shared_container_immutable_reference(pointer_address)
183                .map(SharedContainer::Referenced)?),
184        }
185    }
186    pub fn has_address_with_ownership(
187        &self,
188        pointer_address: &PointerAddress,
189        ownership: SharedContainerOwnership,
190    ) -> bool {
191        self.values
192            .get(pointer_address)
193            .is_some_and(|container| container.ownership() >= ownership)
194    }
195}