praborrow_core/
lib.rs

1use std::ops::{Deref, DerefMut};
2use std::sync::atomic::{AtomicU8, Ordering};
3use std::cell::UnsafeCell;
4
5/// The state of a Sovereign resource.
6/// 0: Domestic (Local jurisdiction)
7/// 1: Exiled (Foreign jurisdiction - moved to another node)
8#[derive(Debug, PartialEq, Eq, Clone, Copy)]
9#[repr(u8)]
10pub enum SovereignState {
11    Domestic = 0,
12    Exiled = 1,
13}
14
15/// A wrapper that enforces ownership semantics across network boundaries.
16///
17/// "Memory safety with sovereign integrity."
18pub struct Sovereign<T> {
19    inner: UnsafeCell<T>,
20    state: AtomicU8,
21}
22
23impl<T> Sovereign<T> {
24    /// Creates a new Sovereign resource under domestic jurisdiction.
25    pub fn new(value: T) -> Self {
26        Self {
27            inner: UnsafeCell::new(value),
28            state: AtomicU8::new(SovereignState::Domestic as u8),
29        }
30    }
31
32    /// Annexes the resource, moving it to foreign jurisdiction.
33    ///
34    /// Once annexed, the resource cannot be accessed locally.
35    /// Access attempts will result in a Sovereignty Violation (panic).
36    pub fn annex(&self) -> Result<(), String> {
37        let current = self.state.load(Ordering::SeqCst);
38        if current == SovereignState::Exiled as u8 {
39            return Err("Resource is already under foreign jurisdiction.".to_string());
40        }
41
42        // Diplomatically transition state
43        self.state.store(SovereignState::Exiled as u8, Ordering::SeqCst);
44        Ok(())
45    }
46
47    /// Checks if the resource is currently domestic.
48    fn verify_jurisdiction(&self) {
49        if self.state.load(Ordering::SeqCst) == SovereignState::Exiled as u8 {
50            panic!("SOVEREIGNTY VIOLATION: Resource is under foreign jurisdiction.");
51        }
52    }
53}
54
55impl<T> Deref for Sovereign<T> {
56    type Target = T;
57
58    fn deref(&self) -> &Self::Target {
59        self.verify_jurisdiction();
60        unsafe { &*self.inner.get() }
61    }
62}
63
64impl<T> DerefMut for Sovereign<T> {
65    fn deref_mut(&mut self) -> &mut Self::Target {
66        self.verify_jurisdiction();
67        unsafe { &mut *self.inner.get() }
68    }
69}
70
71// Safety: Sovereign<T> is Send/Sync if T is Send/Sync, as we use AtomicU8 for state
72// and check it before access.
73unsafe impl<T: Send> Send for Sovereign<T> {}
74unsafe impl<T: Sync> Sync for Sovereign<T> {}
75
76/// Protocol for enforcing constitutional invariants.
77/// Defined in Core to ensure universal application.
78pub trait CheckProtocol {
79    fn enforce_law(&self);
80}