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