#[cfg(not(target_arch = "wasm32"))]
mod native;
#[cfg(target_arch = "wasm32")]
mod wasm;
#[cfg(not(target_arch = "wasm32"))]
use native::with_claims;
#[cfg(target_arch = "wasm32")]
use wasm::with_claims;
use super::RuntimeConstructionError;
use crate::{Memory, VectorMemory};
use std::{rc::Rc, sync::Arc};
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct BackingIdentity(usize);
impl BackingIdentity {
#[must_use]
pub fn of_rc<T: ?Sized>(backing: &Rc<T>) -> Self {
Self(Rc::as_ptr(backing).cast::<()>() as usize)
}
#[must_use]
pub fn of_arc<T: ?Sized>(backing: &Arc<T>) -> Self {
Self(Arc::as_ptr(backing).cast::<()>() as usize)
}
}
pub trait MemoryBacking: Memory {
fn backing_identity(&self) -> BackingIdentity;
}
impl MemoryBacking for VectorMemory {
fn backing_identity(&self) -> BackingIdentity {
BackingIdentity::of_rc(self)
}
}
impl<M: MemoryBacking> MemoryBacking for Rc<M> {
fn backing_identity(&self) -> BackingIdentity {
self.as_ref().backing_identity()
}
}
pub(super) struct BackingClaim(BackingIdentity);
impl BackingClaim {
pub fn acquire(memory: &impl MemoryBacking) -> Result<Self, RuntimeConstructionError> {
let identity = memory.backing_identity();
if with_claims(|claims| claims.insert(identity)) {
Ok(Self(identity))
} else {
Err(RuntimeConstructionError::BackingAlreadyClaimed)
}
}
}
impl Drop for BackingClaim {
fn drop(&mut self) {
with_claims(|claims| claims.remove(&self.0));
}
}