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
44 operation(&mut claims)
45}
46
47pub(super) struct BackingClaim(BackingIdentity);
48
49impl BackingClaim {
50 pub fn acquire(memory: &impl MemoryBacking) -> Result<Self, RuntimeConstructionError> {
51 let identity = memory.backing_identity();
52
53 if with_claims(|claims| claims.insert(identity)) {
54 Ok(Self(identity))
55 } else {
56 Err(RuntimeConstructionError::BackingAlreadyClaimed)
57 }
58 }
59}
60
61impl Drop for BackingClaim {
62 fn drop(&mut self) {
63 with_claims(|claims| claims.remove(&self.0));
64 }
65}