praborrow_core/lib.rs
1//! Core primitives for distributed ownership enforcement.
2//!
3//! This crate provides `Sovereign<T>`, a wrapper type that tracks ownership
4//! across network boundaries. When a resource is "annexed" (moved to another node),
5//! local access is prohibited.
6//!
7//! # The Garuda Proof System
8//!
9//! With `praborrow-prover`, this crate now supports **formally verified** state
10//! transitions. Use `annex_verified()` to require SMT proof before annexation.
11//!
12//! # Safety
13//! Uses `UnsafeCell` and `AtomicU8` for interior mutability with thread-safety.
14//! The `Send`/`Sync` implementations are safe when `T` is `Send`/`Sync`.
15
16#![cfg_attr(not(feature = "std"), no_std)]
17
18extern crate alloc;
19
20use alloc::collections::BTreeMap;
21use alloc::string::String;
22use core::cell::UnsafeCell;
23use core::marker::PhantomData;
24use core::ops::{Deref, DerefMut};
25use core::sync::atomic::{AtomicU8, Ordering};
26
27/// The state of a Sovereign resource.
28/// 0: Domestic (Local jurisdiction)
29/// 1: Exiled (Foreign jurisdiction - moved to another node)
30#[derive(Debug, PartialEq, Eq, Clone, Copy)]
31#[repr(u8)]
32pub enum SovereignState {
33 Domestic = 0,
34 Exiled = 1,
35}
36
37impl core::fmt::Display for SovereignState {
38 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
39 match self {
40 SovereignState::Domestic => f.write_str("Domestic"),
41 SovereignState::Exiled => f.write_str("Exiled"),
42 }
43 }
44}
45
46/// A token that proves a resource has been returned to domestic jurisdiction.
47///
48/// This token is required to call `Sovereign::repatriate`. It can only be constructed
49/// by trusted system components (like the lease manager) that can guarantee the
50/// resource is safe to reclaim.
51pub struct RepatriationToken {
52 _private: (),
53}
54
55impl RepatriationToken {
56 /// Creates a new repatriation token.
57 ///
58 /// # Safety
59 ///
60 /// This function is unsafe because creating a token allows the holder to
61 /// repatriate a sovereign resource. The caller must guarantee that the
62 /// resource is indeed back in domestic jurisdiction and no longer accessed
63 /// remotely.
64 pub unsafe fn new() -> Self {
65 Self { _private: () }
66 }
67}
68
69/// A wrapper that enforces ownership semantics across network boundaries.
70///
71/// "Memory safety with sovereign integrity."
72pub struct Sovereign<T> {
73 inner: UnsafeCell<T>,
74 state: AtomicU8,
75}
76
77/// Error enforcing constitutional invariants.
78#[non_exhaustive]
79#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
80pub enum ConstitutionError {
81 #[error("Invariant violated: {expression}. Values: {values:?}")]
82 InvariantViolation {
83 expression: String,
84 values: BTreeMap<String, String>,
85 },
86}
87
88/// Error returned when accessing a Sovereign resource fails.
89#[non_exhaustive]
90#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
91pub enum SovereigntyError {
92 /// Resource is under foreign jurisdiction (Exiled).
93 #[error("SOVEREIGNTY VIOLATION: Resource is under foreign jurisdiction.")]
94 ForeignJurisdiction,
95}
96
97impl<T> Sovereign<T> {
98 /// Creates a new Sovereign resource under domestic jurisdiction.
99 ///
100 /// # Atomic Ordering
101 ///
102 /// Uses `SeqCst` ordering for maximum safety in distributed scenarios.
103 /// This ensures all threads see state changes in a consistent order,
104 /// which is critical for ownership semantics across network boundaries.
105 #[must_use = "Sovereign resources must be managed carefully"]
106 pub fn new(value: T) -> Self {
107 Self {
108 inner: UnsafeCell::new(value),
109 state: AtomicU8::new(SovereignState::Domestic as u8),
110 }
111 }
112
113 /// Creates a new Sovereign resource that is already under foreign jurisdiction.
114 ///
115 /// This is useful for nodes receiving data that has been transferred from
116 /// another node - the resource starts in an Exiled state.
117 ///
118 /// # Example
119 ///
120 /// ```
121 /// use praborrow_core::{Sovereign, SovereignState};
122 ///
123 /// let foreign_data = Sovereign::new_exiled(42i32);
124 /// assert!(foreign_data.is_exiled());
125 /// ```
126 #[must_use = "Sovereign resources must be managed carefully"]
127 pub fn new_exiled(value: T) -> Self {
128 Self {
129 inner: UnsafeCell::new(value),
130 state: AtomicU8::new(SovereignState::Exiled as u8),
131 }
132 }
133
134 /// Annexes the resource, moving it to foreign jurisdiction.
135 ///
136 /// Once annexed, the resource cannot be accessed locally.
137 /// Access attempts will result in a Sovereignty Violation.
138 #[must_use = "Annexation result should be checked"]
139 pub fn annex(&self) -> Result<(), AnnexError> {
140 let current = self.state.load(Ordering::SeqCst);
141 if current == SovereignState::Exiled as u8 {
142 return Err(AnnexError::AlreadyExiled);
143 }
144
145 // Diplomatically transition state
146 self.state
147 .store(SovereignState::Exiled as u8, Ordering::SeqCst);
148
149 tracing::debug!(
150 from = "Domestic",
151 to = "Exiled",
152 "Resource annexed to foreign jurisdiction"
153 );
154
155 Ok(())
156 }
157
158 /// Returns a reference to the inner value without jurisdiction check.
159 ///
160 /// # Safety
161 ///
162 /// This is safe because we're returning a shared reference and the caller
163 /// is responsible for ensuring the resource is domestic. Use `try_get()`
164 /// for safe access with jurisdiction verification.
165 pub fn inner_ref(&self) -> &T {
166 // SAFETY: We're only reading, and this is safe when called from
167 // contexts that have already verified jurisdiction.
168 unsafe { &*self.inner.get() }
169 }
170
171 /// Returns the current state of the resource.
172 #[inline]
173 pub fn state(&self) -> SovereignState {
174 match self.state.load(Ordering::SeqCst) {
175 0 => SovereignState::Domestic,
176 _ => SovereignState::Exiled,
177 }
178 }
179
180 /// Returns `true` if the resource is under domestic jurisdiction.
181 #[inline]
182 pub fn is_domestic(&self) -> bool {
183 self.state.load(Ordering::SeqCst) == SovereignState::Domestic as u8
184 }
185
186 /// Returns `true` if the resource is under foreign jurisdiction (exiled).
187 #[inline]
188 pub fn is_exiled(&self) -> bool {
189 self.state.load(Ordering::SeqCst) == SovereignState::Exiled as u8
190 }
191
192 /// Attempts to get a reference to the value, returning an error if Exiled.
193 #[must_use = "Check jurisdiction result"]
194 pub fn try_get(&self) -> Result<&T, SovereigntyError> {
195 if self.is_exiled() {
196 return Err(SovereigntyError::ForeignJurisdiction);
197 }
198 // SAFETY: We verified the resource is domestic.
199 unsafe { Ok(&*self.inner.get()) }
200 }
201
202 /// Attempts to get a mutable reference to the value, returning an error if Exiled.
203 #[must_use = "Check jurisdiction result"]
204 pub fn try_get_mut(&mut self) -> Result<&mut T, SovereigntyError> {
205 if self.is_exiled() {
206 return Err(SovereigntyError::ForeignJurisdiction);
207 }
208 // SAFETY: We verified resource is domestic and have &mut self.
209 unsafe { Ok(&mut *self.inner.get()) }
210 }
211
212 /// Repatriates a resource, transitioning it from Exiled back to Domestic.
213 ///
214 /// Requires a `RepatriationToken` as proof that the resource is safe to reclaim.
215 ///
216 /// # Example
217 ///
218 /// ```
219 /// use praborrow_core::{Sovereign, SovereignState, RepatriationToken};
220 ///
221 /// let resource = Sovereign::new(42i32);
222 /// resource.annex().unwrap();
223 /// assert!(resource.is_exiled());
224 ///
225 /// // ... resource is sent to foreign node and returned ...
226 ///
227 /// // SAFETY: construction of token implies safety verification
228 /// let token = unsafe { RepatriationToken::new() };
229 /// resource.repatriate(token);
230 /// assert!(resource.is_domestic());
231 /// ```
232 pub fn repatriate(&self, _token: RepatriationToken) {
233 let previous = self
234 .state
235 .swap(SovereignState::Domestic as u8, Ordering::SeqCst);
236
237 if previous == SovereignState::Exiled as u8 {
238 tracing::debug!(
239 from = "Exiled",
240 to = "Domestic",
241 "Resource repatriated to domestic jurisdiction"
242 );
243 }
244 }
245
246 /// Checks if the resource is currently domestic, panicking if not.
247 ///
248 /// Used internally by Deref/DerefMut. Prefer `try_get()` for non-panicking access.
249 #[track_caller]
250 fn verify_jurisdiction(&self) {
251 if self.is_exiled() {
252 panic!("SOVEREIGNTY VIOLATION: Resource is under foreign jurisdiction.");
253 }
254 }
255
256 /// Maps a function over the domestic sovereign value.
257 ///
258 /// If the resource is Exiled, returns `Err(SovereigntyError::ForeignJurisdiction)`
259 /// without evaluating the function.
260 ///
261 /// # Example
262 ///
263 /// ```
264 /// use praborrow_core::Sovereign;
265 /// let s = Sovereign::new(5);
266 /// let result = s.map(|x| x * 2).unwrap();
267 /// assert_eq!(result, 10);
268 /// ```
269 pub fn map<F, U>(&self, f: F) -> Result<U, SovereigntyError>
270 where
271 F: FnOnce(&T) -> U,
272 {
273 if self.is_exiled() {
274 return Err(SovereigntyError::ForeignJurisdiction);
275 }
276 // SAFETY: We verified resource is domestic.
277 Ok(f(unsafe { &*self.inner.get() }))
278 }
279
280 /// Chains a function that returns a Result over the domestic sovereign value.
281 ///
282 /// This is useful for sequencing operations that might fail or themselves require
283 /// jurisdiction checks.
284 pub fn and_then<F, U>(&self, f: F) -> Result<U, SovereigntyError>
285 where
286 F: FnOnce(&T) -> Result<U, SovereigntyError>,
287 {
288 if self.is_exiled() {
289 return Err(SovereigntyError::ForeignJurisdiction);
290 }
291 // SAFETY: We verified resource is domestic.
292 f(unsafe { &*self.inner.get() })
293 }
294
295 /// Returns a reference to the inner value if it matches the predicate.
296 ///
297 /// # Returns
298 ///
299 /// - `Ok(Some(&T))` if domestic and predicate is true
300 /// - `Ok(None)` if domestic and predicate is false
301 /// - `Err(ForeignJurisdiction)` if exiled
302 pub fn filter<P>(&self, predicate: P) -> Result<Option<&T>, SovereigntyError>
303 where
304 P: FnOnce(&T) -> bool,
305 {
306 if self.is_exiled() {
307 return Err(SovereigntyError::ForeignJurisdiction);
308 }
309 // SAFETY: We verified resource is domestic.
310 let val = unsafe { &*self.inner.get() };
311 if predicate(val) {
312 Ok(Some(val))
313 } else {
314 Ok(None)
315 }
316 }
317
318 /// Modifies the value in-place if domestic.
319 ///
320 /// # Example
321 ///
322 /// ```
323 /// use praborrow_core::Sovereign;
324 /// let mut s = Sovereign::new(5);
325 /// s.modify(|x| *x += 1).unwrap();
326 /// assert_eq!(*s, 6);
327 /// ```
328 pub fn modify<F>(&mut self, f: F) -> Result<(), SovereigntyError>
329 where
330 F: FnOnce(&mut T),
331 {
332 if self.is_exiled() {
333 return Err(SovereigntyError::ForeignJurisdiction);
334 }
335 // SAFETY: We verified resource is domestic and have &mut self.
336 f(unsafe { &mut *self.inner.get() });
337 Ok(())
338 }
339}
340
341impl<T: core::fmt::Debug> core::fmt::Debug for Sovereign<T> {
342 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
343 let state = self.state();
344 match state {
345 SovereignState::Domestic => {
346 // SAFETY: We checked state is Domestic.
347 let val = unsafe { &*self.inner.get() };
348 f.debug_struct("Sovereign")
349 .field("state", &state)
350 .field("inner", val)
351 .finish()
352 }
353 SovereignState::Exiled => f
354 .debug_struct("Sovereign")
355 .field("state", &state)
356 .field("inner", &"<Inaccessible>")
357 .finish(),
358 }
359 }
360}
361
362impl<T> Deref for Sovereign<T> {
363 type Target = T;
364
365 #[track_caller]
366 fn deref(&self) -> &Self::Target {
367 self.verify_jurisdiction();
368 // SAFETY: We've verified the resource is domestic, so access is valid.
369 unsafe { &*self.inner.get() }
370 }
371}
372
373impl<T> DerefMut for Sovereign<T> {
374 #[track_caller]
375 fn deref_mut(&mut self) -> &mut Self::Target {
376 self.verify_jurisdiction();
377 // SAFETY: We've verified the resource is domestic and have &mut self.
378 unsafe { &mut *self.inner.get() }
379 }
380}
381
382// SAFETY: Sovereign<T> is Send/Sync if T is Send/Sync, as we use AtomicU8 for state
383// and check it before access. The UnsafeCell is protected by the atomic state check.
384unsafe impl<T: Send> Send for Sovereign<T> {}
385unsafe impl<T: Sync> Sync for Sovereign<T> {}
386
387/// Protocol for enforcing constitutional invariants (runtime checks).
388///
389/// Types implementing this trait can validate their internal state against
390/// a set of invariants defined via the `#[derive(Constitution)]` macro.
391pub trait CheckProtocol {
392 /// Enforces all invariants, returning an error if any are violated.
393 ///
394 /// # Returns
395 ///
396 /// - `Ok(())` if all invariants are satisfied
397 /// - `Err(ConstitutionError)` containing a description of the violated invariant
398 ///
399 /// # Example
400 ///
401 /// ```ignore
402 /// use praborrow_core::CheckProtocol;
403 ///
404 /// let data = MyStruct { value: -1 };
405 /// match data.enforce_law() {
406 /// Ok(()) => println!("All invariants satisfied"),
407 /// Err(e) => println!("Invariant violated: {}", e),
408 /// }
409 /// ```
410 fn enforce_law(&self) -> Result<(), ConstitutionError>;
411}
412
413/// A value carrying cryptographic proof of verification.
414///
415/// This type can only be constructed by successful SMT verification.
416/// Its existence in a type signature proves that formal verification occurred.
417///
418/// # Type Safety Guarantee
419///
420/// `ProofCarrying<T>` cannot be forged - the private `_proof` field
421/// ensures only the prover crate can construct it.
422#[derive(Debug)]
423pub struct ProofCarrying<T> {
424 /// The carried value.
425 pub value: T,
426 /// Private marker ensuring construction only via verification.
427 _proof: PhantomData<()>,
428}
429
430impl<T> ProofCarrying<T> {
431 /// Creates a new proof-carrying value.
432 ///
433 /// This should only be called after successful verification.
434 #[doc(hidden)]
435 pub fn new_unchecked(value: T) -> Self {
436 Self {
437 value,
438 _proof: PhantomData,
439 }
440 }
441
442 /// Extracts the inner value, consuming the proof.
443 pub fn into_inner(self) -> T {
444 self.value
445 }
446}
447
448impl<T: Clone> Clone for ProofCarrying<T> {
449 fn clone(&self) -> Self {
450 Self {
451 value: self.value.clone(),
452 _proof: PhantomData,
453 }
454 }
455}
456
457/// Error type for verified annexation operations.
458#[non_exhaustive]
459#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
460pub enum AnnexError {
461 /// Resource is already under foreign jurisdiction.
462 #[error("Resource is already under foreign jurisdiction")]
463 AlreadyExiled,
464 /// SMT verification failed.
465 #[error("Verification failed: {0}")]
466 VerificationFailed(String),
467 /// Prover encountered an error.
468 #[error("Prover error: {0}")]
469 ProverError(String),
470}
471
472/// Error returned when a lease operation fails.
473#[non_exhaustive]
474#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
475pub enum LeaseError {
476 /// Resource is already leased to another holder.
477 #[error("Resource is already leased to another holder")]
478 AlreadyLeased,
479 /// Resource is under foreign jurisdiction.
480 #[error("Resource is under foreign jurisdiction")]
481 ForeignJurisdiction,
482 /// Lease duration must be non-zero.
483 #[error("Lease duration must be non-zero")]
484 InvalidDuration,
485}
486
487/// Represents a lease on a Sovereign resource.
488pub struct Lease<T> {
489 /// The holder's unique identifier.
490 pub holder: u128,
491 /// Duration of the lease.
492 pub duration: core::time::Duration,
493 /// Phantom data for the resource type.
494 _phantom: PhantomData<T>,
495}
496
497impl<T> Lease<T> {
498 /// Creates a new lease.
499 ///
500 /// # Duration Validation
501 ///
502 /// If `duration` is zero, returns `Err(LeaseError::InvalidDuration)`.
503 pub fn new(holder: u128, duration: core::time::Duration) -> Result<Self, LeaseError> {
504 if duration.is_zero() {
505 return Err(LeaseError::InvalidDuration);
506 }
507
508 Ok(Self {
509 holder,
510 duration,
511 _phantom: PhantomData,
512 })
513 }
514
515 /// Returns the duration of the lease.
516 #[inline]
517 pub fn duration(&self) -> core::time::Duration {
518 self.duration
519 }
520
521 /// Returns the holder ID.
522 #[inline]
523 pub fn holder(&self) -> u128 {
524 self.holder
525 }
526}
527
528/// Trait for distributed borrow operations.
529pub trait DistributedBorrow<T> {
530 /// Attempt to acquire a lease on the resource.
531 fn try_hire(
532 &self,
533 candidate_id: u128,
534 term: core::time::Duration,
535 ) -> Result<Lease<T>, LeaseError>;
536}
537
538impl<T> DistributedBorrow<T> for Sovereign<T> {
539 fn try_hire(
540 &self,
541 candidate_id: u128,
542 term: core::time::Duration,
543 ) -> Result<Lease<T>, LeaseError> {
544 let current = self.state.load(Ordering::SeqCst);
545 if current == SovereignState::Exiled as u8 {
546 return Err(LeaseError::AlreadyLeased);
547 }
548
549 // Transition to exiled state (leased)
550 self.state
551 .store(SovereignState::Exiled as u8, Ordering::SeqCst);
552 Lease::<T>::new(candidate_id, term)
553 }
554}
555
556/// Extension trait for Sovereign types whose inner types implement formal verification.
557///
558/// This trait is automatically implemented for `Sovereign<T>` where `T` can be
559/// formally verified via the Garuda Proof System.
560pub trait VerifiedAnnex<T> {
561 /// Annexes the resource after successful formal verification.
562 ///
563 /// Unlike `annex()`, this method requires mathematical proof that all
564 /// invariants are satisfied before the state transition occurs.
565 ///
566 /// # Returns
567 ///
568 /// - `Ok(ProofCarrying<()>)` - Verification passed, resource is now Exiled
569 /// - `Err(AnnexError)` - Verification failed or resource already Exiled
570 ///
571 /// # Example
572 ///
573 /// ```ignore
574 /// use praborrow_core::{Sovereign, VerifiedAnnex};
575 ///
576 /// let resource = Sovereign::new(MyVerifiableStruct { balance: 100 });
577 ///
578 /// // This will run SMT verification before annexing
579 /// match resource.annex_verified() {
580 /// Ok(proof) => println!("Annexation proven safe!"),
581 /// Err(e) => println!("Cannot annex: {}", e),
582 /// }
583 /// ```
584 fn annex_verified(&self) -> Result<ProofCarrying<()>, AnnexError>;
585}
586
587// Note: The actual implementation of VerifiedAnnex requires praborrow-prover,
588// which would create a circular dependency. Instead, the implementation is
589// provided via blanket impl in praborrow-prover or via the facade crate.
590//
591// Users should use the `praborrow` facade crate for full functionality.
592
593#[cfg(test)]
594mod tests {
595 use super::*;
596
597 #[test]
598 fn test_sovereign_new() {
599 let s = Sovereign::new(42i32);
600 assert_eq!(s.state(), SovereignState::Domestic);
601 assert!(s.is_domestic());
602 assert!(!s.is_exiled());
603 }
604
605 #[test]
606 fn test_sovereign_new_exiled() {
607 let s = Sovereign::new_exiled(42i32);
608 assert_eq!(s.state(), SovereignState::Exiled);
609 assert!(s.is_exiled());
610 assert!(!s.is_domestic());
611 }
612
613 #[test]
614 fn test_sovereign_deref() {
615 let s = Sovereign::new(42i32);
616 assert_eq!(*s, 42);
617 }
618
619 #[test]
620 fn test_sovereign_deref_mut() {
621 let mut s = Sovereign::new(42i32);
622 *s = 100;
623 assert_eq!(*s, 100);
624 }
625
626 #[test]
627 fn test_sovereign_annex() {
628 let s = Sovereign::new(42i32);
629 assert!(s.annex().is_ok());
630 assert_eq!(s.state(), SovereignState::Exiled);
631 assert!(s.is_exiled());
632 }
633
634 #[test]
635 fn test_sovereign_double_annex() {
636 let s = Sovereign::new(42i32);
637 assert!(s.annex().is_ok());
638 assert!(s.annex().is_err());
639 }
640
641 #[test]
642 fn test_sovereign_repatriate() {
643 let s = Sovereign::new(42i32);
644 s.annex().unwrap();
645 assert!(s.is_exiled());
646
647 // SAFETY: In test context, we control both sides
648 // SAFETY: In test context, we control both sides
649 let token = unsafe { RepatriationToken::new() };
650 s.repatriate(token);
651 assert!(s.is_domestic());
652
653 // Should be able to access again
654 assert_eq!(*s, 42);
655 }
656
657 #[test]
658 #[should_panic(expected = "SOVEREIGNTY VIOLATION")]
659 fn test_sovereignty_violation() {
660 let s = Sovereign::new(42i32);
661 s.annex().unwrap();
662 let _ = *s; // This should panic
663 }
664
665 #[test]
666 fn test_try_get_domestic() {
667 let s = Sovereign::new(42i32);
668 assert_eq!(*s.try_get().unwrap(), 42);
669 }
670
671 #[test]
672 fn test_try_get_exiled() {
673 let s = Sovereign::new(42i32);
674 s.annex().unwrap();
675 assert!(matches!(
676 s.try_get(),
677 Err(SovereigntyError::ForeignJurisdiction)
678 ));
679 }
680
681 #[test]
682 fn test_proof_carrying() {
683 let proof = ProofCarrying::new_unchecked(42i32);
684 assert_eq!(proof.value, 42);
685 assert_eq!(proof.into_inner(), 42);
686 }
687
688 #[test]
689 fn test_annex_error_display() {
690 let e = AnnexError::AlreadyExiled;
691 assert!(e.to_string().contains("foreign jurisdiction"));
692
693 let e = AnnexError::VerificationFailed("test".to_string());
694 assert!(e.to_string().contains("test"));
695 }
696
697 #[test]
698 fn test_lease_zero_duration_fails() {
699 let lease = Lease::<i32>::new(1, core::time::Duration::ZERO);
700 assert!(matches!(lease, Err(LeaseError::InvalidDuration)));
701 }
702
703 #[test]
704 fn test_lease_normal_duration() {
705 let duration = core::time::Duration::from_secs(10);
706 let lease = Lease::<i32>::new(1, duration).unwrap();
707 assert_eq!(lease.duration(), duration);
708 assert_eq!(lease.holder(), 1);
709 }
710
711 #[test]
712 fn test_map_domestic() {
713 let s = Sovereign::new(10);
714 let res = s.map(|x| x * 2);
715 assert_eq!(res, Ok(20));
716 }
717
718 #[test]
719 fn test_map_exiled() {
720 let s = Sovereign::new(10);
721 s.annex().unwrap();
722 let res = s.map(|x| x * 2);
723 assert_eq!(res, Err(SovereigntyError::ForeignJurisdiction));
724 }
725
726 #[test]
727 fn test_and_then() {
728 let s = Sovereign::new(10);
729 let res = s.and_then(|x| {
730 if *x > 5 {
731 Ok(*x * 2)
732 } else {
733 Err(SovereigntyError::ForeignJurisdiction) // Just using this error for test
734 }
735 });
736 assert_eq!(res, Ok(20));
737 }
738
739 #[test]
740 fn test_filter() {
741 let s = Sovereign::new(10);
742
743 // Match
744 let res1 = s.filter(|x| *x > 5);
745 assert_eq!(res1, Ok(Some(&10)));
746
747 // No match
748 let res2 = s.filter(|x| *x < 5);
749 assert_eq!(res2, Ok(None));
750
751 // Exiled
752 s.annex().unwrap();
753 let res3 = s.filter(|x| *x > 5);
754 assert_eq!(res3, Err(SovereigntyError::ForeignJurisdiction));
755 }
756
757 #[test]
758 fn test_modify() {
759 let mut s = Sovereign::new(10);
760 s.modify(|x| *x += 1).unwrap();
761 assert_eq!(*s, 11);
762
763 s.annex().unwrap();
764 let res = s.modify(|x| *x += 1);
765 assert_eq!(res, Err(SovereigntyError::ForeignJurisdiction));
766 }
767}