lib.rs

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