util.rs

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