summaryrefslogtreecommitdiffstats
path: root/third_party/rust/crossbeam-channel/src/utils.rs
diff options
context:
space:
mode:
Diffstat (limited to 'third_party/rust/crossbeam-channel/src/utils.rs')
-rw-r--r--third_party/rust/crossbeam-channel/src/utils.rs66
1 files changed, 66 insertions, 0 deletions
diff --git a/third_party/rust/crossbeam-channel/src/utils.rs b/third_party/rust/crossbeam-channel/src/utils.rs
new file mode 100644
index 0000000000..9f14c8e654
--- /dev/null
+++ b/third_party/rust/crossbeam-channel/src/utils.rs
@@ -0,0 +1,66 @@
+//! Miscellaneous utilities.
+
+use std::cell::Cell;
+use std::num::Wrapping;
+use std::thread;
+use std::time::{Duration, Instant};
+
+/// Randomly shuffles a slice.
+pub(crate) fn shuffle<T>(v: &mut [T]) {
+ let len = v.len();
+ if len <= 1 {
+ return;
+ }
+
+ thread_local! {
+ static RNG: Cell<Wrapping<u32>> = Cell::new(Wrapping(1_406_868_647));
+ }
+
+ let _ = RNG.try_with(|rng| {
+ for i in 1..len {
+ // This is the 32-bit variant of Xorshift.
+ //
+ // Source: https://en.wikipedia.org/wiki/Xorshift
+ let mut x = rng.get();
+ x ^= x << 13;
+ x ^= x >> 17;
+ x ^= x << 5;
+ rng.set(x);
+
+ let x = x.0;
+ let n = i + 1;
+
+ // This is a fast alternative to `let j = x % n`.
+ //
+ // Author: Daniel Lemire
+ // Source: https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
+ let j = ((x as u64).wrapping_mul(n as u64) >> 32) as u32 as usize;
+
+ v.swap(i, j);
+ }
+ });
+}
+
+/// Sleeps until the deadline, or forever if the deadline isn't specified.
+pub(crate) fn sleep_until(deadline: Option<Instant>) {
+ loop {
+ match deadline {
+ None => thread::sleep(Duration::from_secs(1000)),
+ Some(d) => {
+ let now = Instant::now();
+ if now >= d {
+ break;
+ }
+ thread::sleep(d - now);
+ }
+ }
+ }
+}
+
+// https://github.com/crossbeam-rs/crossbeam/issues/795
+pub(crate) fn convert_timeout_to_deadline(timeout: Duration) -> Instant {
+ match Instant::now().checked_add(timeout) {
+ Some(deadline) => deadline,
+ None => Instant::now() + Duration::from_secs(86400 * 365 * 30),
+ }
+}