use crate::{validation::SharedContext, Fallible};
use core::{any::TypeId, fmt};
#[cfg(not(feature = "std"))]
use hashbrown::HashMap;
#[cfg(feature = "std")]
use std::collections::HashMap;
#[derive(Debug)]
pub enum SharedError {
TypeMismatch {
previous: TypeId,
current: TypeId,
},
}
impl fmt::Display for SharedError {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SharedError::TypeMismatch { previous, current } => write!(
f,
"the same memory region has been claimed as two different types ({:?} and {:?})",
previous, current
),
}
}
}
#[cfg(feature = "std")]
const _: () = {
use std::error::Error;
impl Error for SharedError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
SharedError::TypeMismatch { .. } => None,
}
}
}
};
#[derive(Debug)]
pub struct SharedValidator {
shared: HashMap<*const u8, TypeId>,
}
unsafe impl Send for SharedValidator {}
unsafe impl Sync for SharedValidator {}
impl SharedValidator {
#[inline]
pub fn new() -> Self {
Self {
shared: HashMap::new(),
}
}
}
impl Default for SharedValidator {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl Fallible for SharedValidator {
type Error = SharedError;
}
impl SharedContext for SharedValidator {
#[inline]
fn register_shared_ptr(
&mut self,
ptr: *const u8,
type_id: TypeId,
) -> Result<bool, Self::Error> {
if let Some(previous_type_id) = self.shared.get(&ptr) {
if previous_type_id != &type_id {
Err(SharedError::TypeMismatch {
previous: *previous_type_id,
current: type_id,
})
} else {
Ok(false)
}
} else {
self.shared.insert(ptr, type_id);
Ok(true)
}
}
}