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