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