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}
128
129impl<F, T> TryFutureExt for F
130where
131    F: Future<Output = anyhow::Result<T>>,
132{
133    fn log_err(self) -> LogErrorFuture<Self>
134    where
135        Self: Sized,
136    {
137        LogErrorFuture(self, log::Level::Error)
138    }
139
140    fn warn_on_err(self) -> LogErrorFuture<Self>
141    where
142        Self: Sized,
143    {
144        LogErrorFuture(self, log::Level::Warn)
145    }
146}
147
148pub struct LogErrorFuture<F>(F, log::Level);
149
150impl<F, T> Future for LogErrorFuture<F>
151where
152    F: Future<Output = anyhow::Result<T>>,
153{
154    type Output = Option<T>;
155
156    fn poll(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
157        let level = self.1;
158        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
159        match inner.poll(cx) {
160            Poll::Ready(output) => Poll::Ready(match output {
161                Ok(output) => Some(output),
162                Err(error) => {
163                    log::log!(level, "{:?}", error);
164                    None
165                }
166            }),
167            Poll::Pending => Poll::Pending,
168        }
169    }
170}
171
172struct Defer<F: FnOnce()>(Option<F>);
173
174impl<F: FnOnce()> Drop for Defer<F> {
175    fn drop(&mut self) {
176        if let Some(f) = self.0.take() {
177            f()
178        }
179    }
180}
181
182pub fn defer<F: FnOnce()>(f: F) -> impl Drop {
183    Defer(Some(f))
184}
185
186pub struct RandomCharIter<T: Rng>(T);
187
188impl<T: Rng> RandomCharIter<T> {
189    pub fn new(rng: T) -> Self {
190        Self(rng)
191    }
192}
193
194impl<T: Rng> Iterator for RandomCharIter<T> {
195    type Item = char;
196
197    fn next(&mut self) -> Option<Self::Item> {
198        if std::env::var("SIMPLE_TEXT").map_or(false, |v| !v.is_empty()) {
199            return if self.0.gen_range(0..100) < 5 {
200                Some('\n')
201            } else {
202                Some(self.0.gen_range(b'a'..b'z' + 1).into())
203            };
204        }
205
206        match self.0.gen_range(0..100) {
207            // whitespace
208            0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.0).copied(),
209            // two-byte greek letters
210            20..=32 => char::from_u32(self.0.gen_range(('α' as u32)..('ω' as u32 + 1))),
211            // // three-byte characters
212            33..=45 => ['✋', '✅', '❌', '❎', '⭐'].choose(&mut self.0).copied(),
213            // // four-byte characters
214            46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.0).copied(),
215            // ascii letters
216            _ => Some(self.0.gen_range(b'a'..b'z' + 1).into()),
217        }
218    }
219}
220
221// copy unstable standard feature option unzip
222// https://github.com/rust-lang/rust/issues/87800
223// Remove when this ship in Rust 1.66 or 1.67
224pub fn unzip_option<T, U>(option: Option<(T, U)>) -> (Option<T>, Option<U>) {
225    match option {
226        Some((a, b)) => (Some(a), Some(b)),
227        None => (None, None),
228    }
229}
230
231/// Immediately invoked function expression. Good for using the ? operator
232/// in functions which do not return an Option or Result
233#[macro_export]
234macro_rules! iife {
235    ($block:block) => {
236        (|| $block)()
237    };
238}
239
240/// Async Immediately invoked function expression. Good for using the ? operator
241/// in functions which do not return an Option or Result. Async version of above
242#[macro_export]
243macro_rules! async_iife {
244    ($block:block) => {
245        (|| async move { $block })()
246    };
247}
248
249pub trait RangeExt<T> {
250    fn sorted(&self) -> Self;
251    fn to_inclusive(&self) -> RangeInclusive<T>;
252    fn overlaps(&self, other: &Range<T>) -> bool;
253}
254
255impl<T: Ord + Clone> RangeExt<T> for Range<T> {
256    fn sorted(&self) -> Self {
257        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
258    }
259
260    fn to_inclusive(&self) -> RangeInclusive<T> {
261        self.start.clone()..=self.end.clone()
262    }
263
264    fn overlaps(&self, other: &Range<T>) -> bool {
265        self.start < other.end && other.start < self.end
266    }
267}
268
269impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
270    fn sorted(&self) -> Self {
271        cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
272    }
273
274    fn to_inclusive(&self) -> RangeInclusive<T> {
275        self.clone()
276    }
277
278    fn overlaps(&self, other: &Range<T>) -> bool {
279        self.start() < &other.end && &other.start <= self.end()
280    }
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286
287    #[test]
288    fn test_extend_sorted() {
289        let mut vec = vec![];
290
291        extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
292        assert_eq!(vec, &[21, 17, 13, 8, 1]);
293
294        extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
295        assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
296
297        extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
298        assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
299    }
300
301    #[test]
302    fn test_iife() {
303        fn option_returning_function() -> Option<()> {
304            None
305        }
306
307        let foo = iife!({
308            option_returning_function()?;
309            Some(())
310        });
311
312        assert_eq!(foo, None);
313    }
314
315    #[test]
316    fn test_trancate_and_trailoff() {
317        assert_eq!(truncate_and_trailoff("", 5), "");
318        assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
319        assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
320        assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
321    }
322}