salsa 0.28.6

A generic framework for on-demand, incrementalized computation (experimental)
Documentation
pub use shim::*;

pub(crate) fn max_parallelism() -> usize {
    static MAX_PARALLELISM: std::sync::OnceLock<usize> = std::sync::OnceLock::new();

    *MAX_PARALLELISM.get_or_init(|| {
        std::thread::available_parallelism()
            .map(usize::from)
            .unwrap_or(1)
    })
}

#[cfg(feature = "shuttle")]
pub mod shim {
    pub use shuttle::sync::*;
    pub use shuttle::{thread, thread_local};

    /// A wrapper around shuttle's `Mutex` to mirror parking-lot's API.
    #[derive(Default, Debug)]
    pub struct Mutex<T>(shuttle::sync::Mutex<T>);

    impl<T> Mutex<T> {
        pub const fn new(value: T) -> Mutex<T> {
            Mutex(shuttle::sync::Mutex::new(value))
        }

        pub fn lock(&self) -> MutexGuard<'_, T> {
            self.0.lock().unwrap()
        }

        pub fn get_mut(&mut self) -> &mut T {
            self.0.get_mut().unwrap()
        }
    }

    /// A wrapper around shuttle's `Condvar` to mirror parking-lot's API.
    #[derive(Default, Debug)]
    pub struct Condvar(shuttle::sync::Condvar);

    impl Condvar {
        // We cannot match parking-lot identically because shuttle's version takes ownership of the `MutexGuard`.
        pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>) -> MutexGuard<'a, T> {
            self.0.wait(guard).unwrap()
        }

        pub fn notify_one(&self) {
            self.0.notify_one();
        }

        pub fn notify_all(&self) {
            self.0.notify_all();
        }
    }
}

#[cfg(not(feature = "shuttle"))]
pub mod shim {
    pub use std::sync::*;
    pub use std::{thread, thread_local};

    pub use parking_lot::{Mutex, MutexGuard};

    pub mod atomic {
        pub use portable_atomic::AtomicU64;
        pub use std::sync::atomic::*;
    }

    /// A wrapper around parking-lot's `Condvar` to mirror shuttle's API.
    pub struct Condvar(parking_lot::Condvar);

    // this is not derived because it confuses rust-analyzer ... https://github.com/rust-lang/rust-analyzer/issues/19755
    #[allow(clippy::derivable_impls)]
    impl Default for Condvar {
        fn default() -> Self {
            Self(Default::default())
        }
    }

    // this is not derived because it confuses rust-analyzer ... https://github.com/rust-lang/rust-analyzer/issues/19755
    impl std::fmt::Debug for Condvar {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.debug_tuple("Condvar").field(&self.0).finish()
        }
    }

    impl Condvar {
        pub fn wait<'a, T>(&self, mut guard: MutexGuard<'a, T>) -> MutexGuard<'a, T> {
            self.0.wait(&mut guard);
            guard
        }

        pub fn notify_one(&self) {
            self.0.notify_one();
        }

        pub fn notify_all(&self) {
            self.0.notify_all();
        }
    }
}