From aad911fb0cd772e809270be3e0a526d4738b9dd5 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Tue, 18 Aug 2020 17:20:10 +0200 Subject: Speedup ty tests Closes #5792 --- crates/stdx/src/lib.rs | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) (limited to 'crates/stdx') diff --git a/crates/stdx/src/lib.rs b/crates/stdx/src/lib.rs index 265d19288..5d60f0219 100644 --- a/crates/stdx/src/lib.rs +++ b/crates/stdx/src/lib.rs @@ -1,5 +1,8 @@ //! Missing batteries for standard libraries. -use std::time::Instant; +use std::{ + sync::atomic::{AtomicUsize, Ordering}, + time::Instant, +}; mod macros; @@ -134,6 +137,31 @@ where left } +pub struct RacyFlag(AtomicUsize); + +impl RacyFlag { + pub const fn new() -> RacyFlag { + RacyFlag(AtomicUsize::new(0)) + } + + pub fn get(&self, init: impl FnMut() -> bool) -> bool { + let mut init = Some(init); + self.get_impl(&mut || init.take().map_or(false, |mut f| f())) + } + + fn get_impl(&self, init: &mut dyn FnMut() -> bool) -> bool { + match self.0.load(Ordering::Relaxed) { + 0 => false, + 1 => true, + _ => { + let res = init(); + self.0.store(if res { 1 } else { 0 }, Ordering::Relaxed); + res + } + } + } +} + #[cfg(test)] mod tests { use super::*; -- cgit v1.2.3