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