summaryrefslogtreecommitdiff
path: root/crates/utils/src/lib.rs
blob: 1e8ddfb92493845e89963f4d7e694d2ea239926f (plain)
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
//! Common utilities.
#![no_std]

use core::{
    fmt,
    mem::size_of,
    ops::{Deref, DerefMut},
};

/// Creates an ad-hoc `Debug` instance.
pub fn debug(f: impl Fn(&mut fmt::Formatter) -> fmt::Result) -> impl fmt::Debug {
    struct Debug<F>(F);

    impl<F: Fn(&mut fmt::Formatter) -> fmt::Result> fmt::Debug for Debug<F> {
        fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
            (self.0)(fmt)
        }
    }

    Debug(f)
}

/// A hint that this branch is unlikely to be called.
#[cold]
#[inline(always)]
pub fn cold() {}

/// A hint that `b` is likely to be true. See `core::intrinsics::likely`.
#[inline(always)]
pub fn likely(b: bool) -> bool {
    if !b {
        cold()
    }
    b
}

/// A hint that `b` is likely to be false. See `core::intrinsics::unlikely`.
#[inline(always)]
pub fn unlikely(b: bool) -> bool {
    if b {
        cold()
    }
    b
}

/// A version of `std::dbg` built on top of `log::debug` instead of
/// `std::eprintln`.
///
/// This code is copied from libstd, and inherits its copyright.
#[macro_export]
macro_rules! dbg {
    // NOTE: We cannot use `concat!` to make a static string as a format
    // argument of `log::debug!` because the `$expr` expression could be a
    // block (`{ .. }`), in which case the format string will be malformed.
    () => {
        log::debug!("")
    };
    ($expr:expr $(,)?) => {
        // Use of `match` here is intentional because it affects the lifetimes
        // of temporaries - https://stackoverflow.com/a/48732525/1063961
        match $expr {
            tmp => {
                log::debug!("{} = {:#?}", core::stringify!($expr), &tmp);
                tmp
            }
        }
    };
    ($($expr:expr),+ $(,)?) => {
        ($($crate::dbg!($expr)),+,)
    };
}

/// A wrapper type that promises that its contents are Send.
pub struct BelieveMeSend<T>(pub T);

impl<T> Deref for BelieveMeSend<T> {
    type Target = T;

    fn deref(&self) -> &T {
        &self.0
    }
}

impl<T> DerefMut for BelieveMeSend<T> {
    fn deref_mut(&mut self) -> &mut T {
        &mut self.0
    }
}

unsafe impl<T> Send for BelieveMeSend<T> {}

/// A trait for types that can be converted to from big-endian or little-endian byte slices.
pub trait FromEndianBytes {
    /// Converts from a big-endian byte slice.
    fn from_big_endian_bytes(bytes: &[u8]) -> Self;

    /// Converts from a little-endian byte slice.
    fn from_little_endian_bytes(bytes: &[u8]) -> Self;
}

macro_rules! impl_FromEndianBytes {
    ($($ty:ty),* $(,)?) => {
        $(impl FromEndianBytes for $ty {
            fn from_big_endian_bytes(bytes: &[u8]) -> $ty {
                let chunk = match bytes.last_chunk() {
                    Some(chunk) => *chunk,
                    None => {
                        let mut chunk = [0; size_of::<$ty>()];
                        chunk[size_of::<$ty>() - bytes.len()..]
                            .copy_from_slice(bytes);
                        chunk
                    },
                };
                <$ty>::from_be_bytes(chunk)
            }

            fn from_little_endian_bytes(bytes: &[u8]) -> $ty {
                let chunk = match bytes.first_chunk() {
                    Some(chunk) => *chunk,
                    None => {
                        let mut chunk = [0; size_of::<$ty>()];
                        chunk[.. bytes.len()].copy_from_slice(bytes);
                        chunk
                    },
                };
                <$ty>::from_le_bytes(chunk)
            }
        })*
    };
}

impl_FromEndianBytes!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);

/// Runs the body block the first time it is encountered.
#[macro_export]
macro_rules! first_time {
    ($($stmt:stmt)*) => {{
        use spin::lazy::Lazy;
        static LAZY: Lazy<()> = Lazy::new(|| {
            $($stmt)*
        });
        *Lazy::force(&LAZY)
    }};
}