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