use crate::{
collections::HashMap,
prelude::*,
shared_values::{
OwnedSharedContainer, PointerAddress, ReferenceMutability,
ReferencedSharedContainer, SharedContainer, SharedContainerOwnership,
errors::{
UnexpectedImmutableReferenceError,
UnexpectedSharedContainerOwnershipError,
},
traits::SharedContainerCommon,
},
values::{
core_values::callable::Callable, value_container::ValueContainer,
},
};
use core::{
fmt::Display,
hash::{Hash, Hasher},
};
#[derive(Debug, Default)]
pub struct SharedValuesCache {
values: HashMap<PointerAddress, SharedContainer>,
callables: HashMap<u64, Callable>,
vecs: HashMap<usize, Box<dyn core::any::Any>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValueNotFoundInCacheError(pub PointerAddress);
impl Display for ValueNotFoundInCacheError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "Value not found in cache: {}", self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CacheValueRetrievalError {
UnexpectedImmutableReference(UnexpectedImmutableReferenceError),
UnexpectedSharedContainerOwnership(UnexpectedSharedContainerOwnershipError),
ValueNotFoundInCache(ValueNotFoundInCacheError),
}
impl Display for CacheValueRetrievalError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
CacheValueRetrievalError::UnexpectedImmutableReference(err) => {
write!(f, "Unexpected immutable reference: {}", err)
}
CacheValueRetrievalError::UnexpectedSharedContainerOwnership(
err,
) => {
write!(f, "Unexpected shared container ownership: {}", err)
}
CacheValueRetrievalError::ValueNotFoundInCache(err) => {
write!(f, "{}", err)
}
}
}
}
impl From<UnexpectedImmutableReferenceError> for CacheValueRetrievalError {
fn from(error: UnexpectedImmutableReferenceError) -> Self {
CacheValueRetrievalError::UnexpectedImmutableReference(error)
}
}
impl From<ValueNotFoundInCacheError> for CacheValueRetrievalError {
fn from(error: ValueNotFoundInCacheError) -> Self {
CacheValueRetrievalError::ValueNotFoundInCache(error)
}
}
impl From<UnexpectedSharedContainerOwnershipError>
for CacheValueRetrievalError
{
fn from(error: UnexpectedSharedContainerOwnershipError) -> Self {
CacheValueRetrievalError::UnexpectedSharedContainerOwnership(error)
}
}
impl SharedValuesCache {
pub fn new(values: Vec<SharedContainer>) -> Self {
SharedValuesCache {
values: values
.into_iter()
.map(|container| (container.pointer_address(), container))
.collect(),
callables: HashMap::new(),
vecs: HashMap::new(),
}
}
pub fn store_shared_container(&mut self, container: SharedContainer) {
if let Some(existing) = self.values.get(&container.pointer_address())
&& existing.ownership() > container.ownership()
{
return;
}
self.values.insert(container.pointer_address(), container);
}
pub fn store_callable(&mut self, callable: Callable) -> u64 {
let mut hasher = default_hasher();
callable.hash(&mut hasher);
let hash = hasher.finish();
self.callables.insert(hash, callable);
hash
}
pub fn store_vec<T: 'static>(&mut self, vec: Vec<T>) -> usize {
let ptr = vec.as_ptr() as usize;
self.vecs.insert(ptr, Box::new(vec));
ptr
}
pub fn remove_stored_vec(&mut self, handle: usize) {
self.vecs.remove(&handle);
}
pub fn get_callable(&self, hash: u64) -> Option<Callable> {
self.callables.get(&hash).cloned()
}
pub fn remove_callable_with_hash(&mut self, hash: u64) {
self.callables.remove(&hash);
}
pub fn remove_shared_container(
&mut self,
pointer_address: &PointerAddress,
) {
self.values.remove(pointer_address);
}
pub fn try_take_owned_shared_container(
&mut self,
pointer_address: &PointerAddress,
) -> Result<OwnedSharedContainer, CacheValueRetrievalError> {
match self.values.get(pointer_address) {
Some(container) => {
match container {
SharedContainer::Owned(container) => {
match self.values.insert(
pointer_address.clone(),
SharedContainer::Referenced(
container.derive_with_max_mutability(),
),
) {
Some(SharedContainer::Owned(owned_container)) => {
Ok(owned_container)
}
_ => unreachable!(),
}
}
SharedContainer::Referenced(reference) => {
Err(UnexpectedSharedContainerOwnershipError {
actual: SharedContainerOwnership::Referenced(
reference.reference_mutability(),
),
expected: SharedContainerOwnership::Owned,
}
.into())
}
}
}
_ => Err(ValueNotFoundInCacheError(pointer_address.clone()).into()),
}
}
pub fn try_get_shared_container(
&self,
pointer_address: &PointerAddress,
) -> Result<&SharedContainer, ValueNotFoundInCacheError> {
self.values
.get(pointer_address)
.ok_or(ValueNotFoundInCacheError(pointer_address.clone()))
}
pub fn try_get_shared_container_reference(
&self,
pointer_address: &PointerAddress,
mutability: ReferenceMutability,
) -> Result<ReferencedSharedContainer, CacheValueRetrievalError> {
match mutability {
ReferenceMutability::Mutable => {
self.try_get_shared_container_mutable_reference(pointer_address)
}
ReferenceMutability::Immutable => Ok(self
.try_get_shared_container_immutable_reference(
pointer_address,
)?),
}
}
pub fn try_get_shared_container_mutable_reference(
&self,
pointer_address: &PointerAddress,
) -> Result<ReferencedSharedContainer, CacheValueRetrievalError> {
Ok(self
.values
.get(pointer_address)
.ok_or(ValueNotFoundInCacheError(pointer_address.clone()))?
.try_derive_mutable_reference()?)
}
pub fn try_get_shared_container_immutable_reference(
&self,
pointer_address: &PointerAddress,
) -> Result<ReferencedSharedContainer, ValueNotFoundInCacheError> {
Ok(self
.values
.get(pointer_address)
.ok_or(ValueNotFoundInCacheError(pointer_address.clone()))?
.derive_immutable_reference())
}
pub fn try_get_shared_container_with_ownership(
&mut self,
pointer_address: &PointerAddress,
ownership: SharedContainerOwnership,
) -> Result<SharedContainer, CacheValueRetrievalError> {
match ownership {
SharedContainerOwnership::Owned => self
.try_take_owned_shared_container(pointer_address)
.map(SharedContainer::Owned),
SharedContainerOwnership::Referenced(
ReferenceMutability::Mutable,
) => self
.try_get_shared_container_mutable_reference(pointer_address)
.map(SharedContainer::Referenced),
SharedContainerOwnership::Referenced(
ReferenceMutability::Immutable,
) => Ok(self
.try_get_shared_container_immutable_reference(pointer_address)
.map(SharedContainer::Referenced)?),
}
}
pub fn has_address_with_ownership(
&self,
pointer_address: &PointerAddress,
ownership: SharedContainerOwnership,
) -> bool {
self.values
.get(pointer_address)
.is_some_and(|container| container.ownership() >= ownership)
}
}
#[cfg(feature = "decompiler")]
impl Display for SharedValuesCache {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
use crate::decompiler::{ast_to_source_code::value_to_source_code, *};
writeln!(f, "Values:")?;
for (address, value) in &self.values {
writeln!(
f,
" {}: {}",
address,
value_to_source_code(
&ValueContainer::Shared(
value.clone_with_move_indicator_if_owned()
),
DecompileOptions::default()
)
)?;
}
Ok(())
}
}