lib.rs

  1#[cfg(any(test, feature = "test-support"))]
  2pub mod test;
  3
  4pub use backtrace::Backtrace;
  5use futures::Future;
  6use rand::{seq::SliceRandom, Rng};
  7use std::{
  8    cmp::Ordering,
  9    ops::AddAssign,
 10    pin::Pin,
 11    task::{Context, Poll},
 12};
 13
 14#[macro_export]
 15macro_rules! debug_panic {
 16    ( $($fmt_arg:tt)* ) => {
 17        if cfg!(debug_assertions) {
 18            panic!( $($fmt_arg)* );
 19        } else {
 20            let backtrace = $crate::Backtrace::new();
 21            log::error!("{}\n{:?}", format_args!($($fmt_arg)*), backtrace);
 22        }
 23    };
 24}
 25
 26pub fn truncate(s: &str, max_chars: usize) -> &str {
 27    match s.char_indices().nth(max_chars) {
 28        None => s,
 29        Some((idx, _)) => &s[..idx],
 30    }
 31}
 32
 33pub fn truncate_and_trailoff(s: &str, max_chars: usize) -> String {
 34    debug_assert!(max_chars >= 5);
 35
 36    if s.len() > max_chars {
 37        format!("{}", truncate(&s, max_chars.saturating_sub(3)))
 38    } else {
 39        s.to_string()
 40    }
 41}
 42
 43pub fn post_inc<T: From<u8> + AddAssign<T> + Copy>(value: &mut T) -> T {
 44    let prev = *value;
 45    *value += T::from(1);
 46    prev
 47}
 48
 49/// Extend a sorted vector with a sorted sequence of items, maintaining the vector's sort order and
 50/// enforcing a maximum length. Sort the items according to the given callback. Before calling this,
 51/// both `vec` and `new_items` should already be sorted according to the `cmp` comparator.
 52pub fn extend_sorted<T, I, F>(vec: &mut Vec<T>, new_items: I, limit: usize, mut cmp: F)
 53where
 54    I: IntoIterator<Item = T>,
 55    F: FnMut(&T, &T) -> Ordering,
 56{
 57    let mut start_index = 0;
 58    for new_item in new_items {
 59        if let Err(i) = vec[start_index..].binary_search_by(|m| cmp(m, &new_item)) {
 60            let index = start_index + i;
 61            if vec.len() < limit {
 62                vec.insert(index, new_item);
 63            } else if index < vec.len() {
 64                vec.pop();
 65                vec.insert(index, new_item);
 66            }
 67            start_index = index;
 68        }
 69    }
 70}
 71
 72pub trait ResultExt {
 73    type Ok;
 74
 75    fn log_err(self) -> Option<Self::Ok>;
 76    fn warn_on_err(self) -> Option<Self::Ok>;
 77}
 78
 79impl<T, E> ResultExt for Result<T, E>
 80where
 81    E: std::fmt::Debug,
 82{
 83    type Ok = T;
 84
 85    fn log_err(self) -> Option<T> {
 86        match self {
 87            Ok(value) => Some(value),
 88            Err(error) => {
 89                log::error!("{:?}", error);
 90                None
 91            }
 92        }
 93    }
 94
 95    fn warn_on_err(self) -> Option<T> {
 96        match self {
 97            Ok(value) => Some(value),
 98            Err(error) => {
 99                log::warn!("{:?}", error);
100                None
101            }
102        }
103    }
104}
105
106pub trait TryFutureExt {
107    fn log_err(self) -> LogErrorFuture<Self>
108    where
109        Self: Sized;
110    fn warn_on_err(self) -> LogErrorFuture<Self>
111    where
112        Self: Sized;
113}
114
115impl<F, T> TryFutureExt for F
116where
117    F: Future<Output = anyhow::Result<T>>,
118{
119    fn log_err(self) -> LogErrorFuture<Self>
120    where
121        Self: Sized,
122    {
123        LogErrorFuture(self, log::Level::Error)
124    }
125
126    fn warn_on_err(self) -> LogErrorFuture<Self>
127    where
128        Self: Sized,
129    {
130        LogErrorFuture(self, log::Level::Warn)
131    }
132}
133
134pub struct LogErrorFuture<F>(F, log::Level);
135
136impl<F, T> Future for LogErrorFuture<F>
137where
138    F: Future<Output = anyhow::Result<T>>,
139{
140    type Output = Option<T>;
141
142    fn poll(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
143        let level = self.1;
144        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
145        match inner.poll(cx) {
146            Poll::Ready(output) => Poll::Ready(match output {
147                Ok(output) => Some(output),
148                Err(error) => {
149                    log::log!(level, "{:?}", error);
150                    None
151                }
152            }),
153            Poll::Pending => Poll::Pending,
154        }
155    }
156}
157
158struct Defer<F: FnOnce()>(Option<F>);
159
160impl<F: FnOnce()> Drop for Defer<F> {
161    fn drop(&mut self) {
162        if let Some(f) = self.0.take() {
163            f()
164        }
165    }
166}
167
168pub fn defer<F: FnOnce()>(f: F) -> impl Drop {
169    Defer(Some(f))
170}
171
172pub struct RandomCharIter<T: Rng>(T);
173
174impl<T: Rng> RandomCharIter<T> {
175    pub fn new(rng: T) -> Self {
176        Self(rng)
177    }
178}
179
180impl<T: Rng> Iterator for RandomCharIter<T> {
181    type Item = char;
182
183    fn next(&mut self) -> Option<Self::Item> {
184        if std::env::var("SIMPLE_TEXT").map_or(false, |v| !v.is_empty()) {
185            return if self.0.gen_range(0..100) < 5 {
186                Some('\n')
187            } else {
188                Some(self.0.gen_range(b'a'..b'z' + 1).into())
189            };
190        }
191
192        match self.0.gen_range(0..100) {
193            // whitespace
194            0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.0).copied(),
195            // two-byte greek letters
196            20..=32 => char::from_u32(self.0.gen_range(('α' as u32)..('ω' as u32 + 1))),
197            // // three-byte characters
198            33..=45 => ['✋', '✅', '❌', '❎', '⭐'].choose(&mut self.0).copied(),
199            // // four-byte characters
200            46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.0).copied(),
201            // ascii letters
202            _ => Some(self.0.gen_range(b'a'..b'z' + 1).into()),
203        }
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210
211    #[test]
212    fn test_extend_sorted() {
213        let mut vec = vec![];
214
215        extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
216        assert_eq!(vec, &[21, 17, 13, 8, 1]);
217
218        extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
219        assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
220
221        extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
222        assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
223    }
224}