1use crate::view::Validator;
2use std::{
3 marker::PhantomData,
4 mem::{ManuallyDrop, MaybeUninit},
5};
6
7#[derive(Debug)]
8pub struct Guard<'a, T: 'static, E, U: Validator<Item = T, Error = E>>(
9 pub(crate) MaybeUninit<T>,
10 pub(crate) &'a mut T,
11 pub(crate) PhantomData<U>,
12);
13
14impl<'a, T, E, U: Validator<Item = T, Error = E>> std::ops::Deref for Guard<'a, T, E, U> {
15 type Target = T;
16
17 #[inline(always)]
18 fn deref(&self) -> &Self::Target {
19 unsafe { self.0.assume_init_ref() }
20 }
21}
22
23impl<'a, T, E, U: Validator<Item = T, Error = E>> std::ops::DerefMut for Guard<'a, T, E, U> {
24 #[inline(always)]
25 fn deref_mut(&mut self) -> &mut Self::Target {
26 unsafe { self.0.assume_init_mut() }
27 }
28}
29
30impl<'a, T, E, U: Validator<Item = T, Error = E>> AsRef<T> for Guard<'a, T, E, U> {
31 #[inline(always)]
32 fn as_ref(&self) -> &T {
33 unsafe { self.0.assume_init_ref() }
34 }
35}
36
37impl<'a, T, E, U: Validator<Item = T, Error = E>> AsMut<T> for Guard<'a, T, E, U> {
38 #[inline(always)]
39 fn as_mut(&mut self) -> &mut T {
40 unsafe { self.0.assume_init_mut() }
41 }
42}
43
44impl<'a, T, E, U: Validator<Item = T, Error = E>> Drop for Guard<'a, T, E, U> {
45 fn drop(&mut self) {
46 #[cfg(debug_assertions)]
47 {
48 eprintln!("A `Guard` was dropped without calling `commit` or `discard` first");
49 }
50 }
51}
52
53impl<'a, T, E, U: Validator<Item = T, Error = E>> Guard<'a, T, E, U> {
54 #[inline(always)]
55 pub(super) fn new(dst: &'a mut T) -> Self {
56 Self(
57 MaybeUninit::new(unsafe { std::ptr::read(&*dst) }),
58 dst,
59 PhantomData,
60 )
61 }
62
63 #[inline(always)]
64 pub fn is_changed(&self) -> bool
65 where
66 T: PartialEq,
67 {
68 let a = unsafe { self.0.assume_init_ref() };
69 let b = &*self.1;
70
71 a != b
72 }
73
74 #[inline(always)]
75 pub fn check(&self) -> Result<(), E> {
76 U::validate(unsafe { self.0.assume_init_ref() })
77 }
78
79 #[inline(always)]
80 pub fn commit(self) -> Result<(), Self> {
81 let mut this = std::mem::ManuallyDrop::new(self);
82
83 match this.check() {
84 Ok(_) => {
85 *this.1 = unsafe { this.0.assume_init_read() };
86 Ok(())
87 }
88 Err(_) => Err(ManuallyDrop::into_inner(this)),
89 }
90 }
91
92 #[inline(always)]
93 pub fn discard(self) {
94 std::mem::forget(self);
95 }
96}
97
98#[macro_export]
99macro_rules! commit_or_bail {
100 ($guard:expr) => {
101 match $guard.check() {
102 Ok(_) => {
103 $guard.commit().unwrap();
104 }
105 Err(e) => {
106 return Err(e.into());
107 }
108 }
109 };
110}