util.rs

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