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