1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
#![warn(rust_2018_idioms, unreachable_pub)]

use std::{error::Error, fmt};

use derive_more::Deref;

pub use self::rate_limiter::RateLimiter;

mod rate_limiter;

#[derive(Debug, Clone, Copy, Default, Hash, PartialEq, Eq, Deref)]
// Spatial prefetcher is now pulling two lines at a time, so we use `align(128)`.
#[cfg_attr(any(target_arch = "x86_64", target_arch = "aarch64"), repr(align(128)))]
#[cfg_attr(
    not(any(target_arch = "x86_64", target_arch = "aarch64")),
    repr(align(64))
)]
pub struct CachePadded<T>(pub T);

/// Returns the contents of a `Option<T>`'s `Some(T)`, otherwise it returns
/// early from the function. Can alternatively have an `else` branch, or an
/// alternative "early return" statement, like `break` or `continue` for loops.
#[macro_export]
macro_rules! ward {
    ($o:expr) => {
        // Do not reuse `ward!` here, because it confuses rust-analyzer for now.
        match $o {
            Some(x) => x,
            None => return,
        }
    };
    ($o:expr, else $body:block) => {
        match $o {
            Some(x) => x,
            None => $body,
        }
    };
    ($o:expr, $early:stmt) => {
        // Do not reuse `ward!` here, because it confuses rust-analyzer for now.
        match $o {
            Some(x) => x,
            None => ({ $early }),
        }
    };
}

#[macro_export]
macro_rules! cooldown {
    ($period:expr, $body:expr) => {{
        use std::{
            sync::atomic::{AtomicU64, Ordering},
            time::UNIX_EPOCH,
        };

        static LOGGED_TIME: AtomicU64 = AtomicU64::new(0);

        let period = $period.as_nanos() as u64;
        let res = LOGGED_TIME.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |logged_time| {
            let now = UNIX_EPOCH.elapsed().unwrap_or_default().as_nanos() as u64;
            if logged_time + period <= now {
                Some(now)
            } else {
                None
            }
        });

        if res.is_ok() {
            $body
        }
    }};
}

pub struct ErrorChain<'a>(pub &'a dyn Error);

impl fmt::Display for ErrorChain<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)?;

        let mut cursor = self.0;
        while let Some(err) = cursor.source() {
            write!(f, ": {}", err)?;
            cursor = err;
        }

        Ok(())
    }
}

#[test]
fn trivial_error_chain() {
    let error = anyhow::anyhow!("oops");
    assert_eq!(format!("{}", ErrorChain(&*error)), "oops");
}

#[test]
fn error_chain() {
    let innermost = anyhow::anyhow!("innermost");
    let inner = innermost.context("inner");
    let outer = inner.context("outer");
    assert_eq!(
        format!("{}", ErrorChain(&*outer)),
        "outer: inner: innermost"
    );
}