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