1use std::cell::Cell;
7use std::sync::atomic::{AtomicU64, Ordering};
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub struct CommitScope(u64);
13
14thread_local! {
15 #[cfg_attr(target_os = "android", allow(clippy::missing_const_for_thread_local))]
19 static THREAD: Cell<Option<CommitScope>> = const { Cell::new(None) };
20}
21
22impl CommitScope {
23 pub fn new() -> Self {
25 static NEXT: AtomicU64 = AtomicU64::new(1);
26 Self(NEXT.fetch_add(1, Ordering::Relaxed))
27 }
28}
29
30impl Default for CommitScope {
31 fn default() -> Self {
32 Self::new()
33 }
34}
35
36pub fn enter<R>(scope: Option<CommitScope>, run: impl FnOnce() -> R) -> R {
38 struct Restore(Option<CommitScope>);
39 impl Drop for Restore {
40 fn drop(&mut self) {
41 THREAD.with(|thread| thread.set(self.0));
42 }
43 }
44 let _restore = Restore(THREAD.with(|thread| thread.replace(scope)));
45 run()
46}
47
48pub fn committing() -> Option<CommitScope> {
50 THREAD.with(Cell::get)
51}