lib.rs

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