Skip to main content

sqlive/
commit_scope.rs

1//! Commits attributed to the work that made them, so an observation can leave
2//! one piece of work's own commits out: an operation attempt's own commits are
3//! never evidence against the wait it ends in (§6.7, §21.2; IO
4//! `WaitingEvidence`).
5
6use std::cell::Cell;
7use std::sync::atomic::{AtomicU64, Ordering};
8
9/// The work a commit belongs to: a commit made on a thread running inside
10/// `enter(scope, ..)` belongs to `scope`.
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub struct CommitScope(u64);
13
14thread_local! {
15    // Clippy asks for a `const` initializer this already has where the
16    // target has no native thread locals, as Android: std builds those
17    // from a function, which the lint reads as the initializer.
18    #[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    /// A scope no other scope equals.
24    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
36/// Run `run` with commits made on this thread attributed to `scope`, if any.
37pub 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
48/// The scope of the call committing on this thread.
49pub fn committing() -> Option<CommitScope> {
50    THREAD.with(Cell::get)
51}