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