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