Skip to main content

heed3/envs/
on_commit.rs

1use std::num::NonZero;
2
3use crate::Env;
4
5/// A provided token used to make sure databases
6/// can be used outside of the current transaction.
7pub struct CommitToken {
8    /// This is the env identifier to make sure that the env
9    /// used to commit a database
10    env_ident: NonZero<usize>,
11}
12
13impl CommitToken {
14    pub(crate) fn new<T>(env: &Env<T>) -> CommitToken {
15        CommitToken { env_ident: env.env_mut_ptr().addr() }
16    }
17
18    pub(crate) fn env_ident(&self) -> NonZero<usize> {
19        self.env_ident
20    }
21}
22
23/// A trait that must be implemented to be able to
24/// convert databases from local ones to static ones.
25pub trait OnCommit {
26    /// The output struct after a commit use successful.
27    type Committed;
28
29    /// Convert a struct after the commit is successful.
30    fn on_commit(self, token: &CommitToken) -> Self::Committed;
31}
32
33impl OnCommit for () {
34    type Committed = ();
35
36    fn on_commit(self, _token: &CommitToken) -> Self::Committed {}
37}
38
39impl<A: OnCommit> OnCommit for Option<A> {
40    type Committed = Option<A::Committed>;
41
42    fn on_commit(self, token: &CommitToken) -> Self::Committed {
43        self.map(|a| a.on_commit(token))
44    }
45}
46
47impl<T: OnCommit, E> OnCommit for Result<T, E> {
48    type Committed = Result<T::Committed, E>;
49
50    fn on_commit(self, token: &CommitToken) -> Self::Committed {
51        self.map(|t| t.on_commit(token))
52    }
53}
54
55impl<T: OnCommit, const N: usize> OnCommit for [T; N] {
56    type Committed = [T::Committed; N];
57
58    fn on_commit(self, token: &CommitToken) -> Self::Committed {
59        self.map(|t| t.on_commit(token))
60    }
61}
62
63macro_rules! impl_on_commit_for_tuple {
64    ( $( $name:ident )+ ) => {
65        impl<$($name: OnCommit),+> OnCommit for ($($name,)+) {
66            type Committed = ($($name::Committed,)+);
67
68            // Allow non snake case identifier as we use the
69            // struct names, i.e. A, B, to decompose the tuple.
70            #[allow(non_snake_case)]
71            fn on_commit(self, token: &crate::CommitToken) -> Self::Committed {
72                let ($($name,)+) = self;
73                ($($name.on_commit(token),)+)
74            }
75        }
76    };
77}
78
79impl_on_commit_for_tuple! { A }
80impl_on_commit_for_tuple! { A B }
81impl_on_commit_for_tuple! { A B C }
82impl_on_commit_for_tuple! { A B C D }
83impl_on_commit_for_tuple! { A B C D E }
84impl_on_commit_for_tuple! { A B C D E F }
85impl_on_commit_for_tuple! { A B C D E F G }
86impl_on_commit_for_tuple! { A B C D E F G H }
87impl_on_commit_for_tuple! { A B C D E F G H I }
88impl_on_commit_for_tuple! { A B C D E F G H I J }
89impl_on_commit_for_tuple! { A B C D E F G H I J K }
90impl_on_commit_for_tuple! { A B C D E F G H I J K L }