1use std::ops::{Deref, DerefMut};
12use std::sync::atomic::{AtomicU8, Ordering};
13use std::cell::UnsafeCell;
14
15#[derive(Debug, PartialEq, Eq, Clone, Copy)]
19#[repr(u8)]
20pub enum SovereignState {
21 Domestic = 0,
22 Exiled = 1,
23}
24
25pub struct Sovereign<T> {
29 inner: UnsafeCell<T>,
30 state: AtomicU8,
31}
32
33impl<T> Sovereign<T> {
34 pub fn new(value: T) -> Self {
36 Self {
37 inner: UnsafeCell::new(value),
38 state: AtomicU8::new(SovereignState::Domestic as u8),
39 }
40 }
41
42 pub fn annex(&self) -> Result<(), String> {
47 let current = self.state.load(Ordering::SeqCst);
48 if current == SovereignState::Exiled as u8 {
49 return Err("Resource is already under foreign jurisdiction.".to_string());
50 }
51
52 self.state.store(SovereignState::Exiled as u8, Ordering::SeqCst);
54 Ok(())
55 }
56
57 fn verify_jurisdiction(&self) {
59 if self.state.load(Ordering::SeqCst) == SovereignState::Exiled as u8 {
60 panic!("SOVEREIGNTY VIOLATION: Resource is under foreign jurisdiction.");
61 }
62 }
63}
64
65impl<T> Deref for Sovereign<T> {
66 type Target = T;
67
68 fn deref(&self) -> &Self::Target {
69 self.verify_jurisdiction();
70 unsafe { &*self.inner.get() }
71 }
72}
73
74impl<T> DerefMut for Sovereign<T> {
75 fn deref_mut(&mut self) -> &mut Self::Target {
76 self.verify_jurisdiction();
77 unsafe { &mut *self.inner.get() }
78 }
79}
80
81unsafe impl<T: Send> Send for Sovereign<T> {}
84unsafe impl<T: Sync> Sync for Sovereign<T> {}
85
86pub trait CheckProtocol {
88 fn enforce_law(&self);
89}
90
91#[derive(Debug, Clone, PartialEq, Eq)]
93pub enum LeaseError {
94 AlreadyLeased,
96 ForeignJurisdiction,
98}
99
100pub struct Lease<T> {
102 pub holder: u128,
104 pub duration: std::time::Duration,
106 _phantom: std::marker::PhantomData<T>,
108}
109
110impl<T> Lease<T> {
111 pub fn new(holder: u128, duration: std::time::Duration) -> Self {
113 Self {
114 holder,
115 duration,
116 _phantom: std::marker::PhantomData,
117 }
118 }
119}
120
121pub trait DistributedBorrow<T> {
123 fn try_hire(&self, candidate_id: u128, term: std::time::Duration) -> Result<Lease<T>, LeaseError>;
125}
126
127impl<T> DistributedBorrow<T> for Sovereign<T> {
128 fn try_hire(&self, candidate_id: u128, term: std::time::Duration) -> Result<Lease<T>, LeaseError> {
129 let current = self.state.load(Ordering::SeqCst);
130 if current == SovereignState::Exiled as u8 {
131 return Err(LeaseError::AlreadyLeased);
132 }
133
134 self.state.store(SovereignState::Exiled as u8, Ordering::SeqCst);
136 Ok(Lease::new(candidate_id, term))
137 }
138}