ic_storage/runtime/custody/
mod.rs1use super::RuntimeConstructionError;
3use crate::{BackingIdentity, Memory, VectorMemory};
4use std::{
5 collections::BTreeSet,
6 rc::Rc,
7 sync::{Mutex, PoisonError},
8};
9
10pub trait MemoryBacking: Memory {
23 fn backing_identity(&self) -> BackingIdentity;
25}
26
27impl MemoryBacking for VectorMemory {
28 fn backing_identity(&self) -> BackingIdentity {
29 BackingIdentity::of_rc(self)
30 }
31}
32
33impl<M: MemoryBacking> MemoryBacking for Rc<M> {
34 fn backing_identity(&self) -> BackingIdentity {
35 self.as_ref().backing_identity()
36 }
37}
38
39static CLAIMS: Mutex<BTreeSet<BackingIdentity>> = Mutex::new(BTreeSet::new());
40
41fn with_claims<T>(operation: impl FnOnce(&mut BTreeSet<BackingIdentity>) -> T) -> T {
42 let mut claims = CLAIMS.lock().unwrap_or_else(PoisonError::into_inner);
43 operation(&mut claims)
44}
45
46pub(super) struct BackingClaim(BackingIdentity);
47
48impl BackingClaim {
49 pub fn acquire(memory: &impl MemoryBacking) -> Result<Self, RuntimeConstructionError> {
50 let identity = memory.backing_identity();
51 if with_claims(|claims| claims.insert(identity)) {
52 Ok(Self(identity))
53 } else {
54 Err(RuntimeConstructionError::BackingAlreadyClaimed)
55 }
56 }
57}
58
59impl Drop for BackingClaim {
60 fn drop(&mut self) {
61 with_claims(|claims| claims.remove(&self.0));
62 }
63}