util.rs

  1pub mod arc_cow;
  2pub mod fs;
  3pub mod github;
  4pub mod http;
  5pub mod paths;
  6mod semantic_version;
  7#[cfg(any(test, feature = "test-support"))]
  8pub mod test;
  9
 10use futures::Future;
 11use lazy_static::lazy_static;
 12use rand::{seq::SliceRandom, Rng};
 13pub use semantic_version::SemanticVersion;
 14use std::{
 15    borrow::Cow,
 16    cmp::{self, Ordering},
 17    env,
 18    ops::{AddAssign, Range, RangeInclusive},
 19    panic::Location,
 20    pin::Pin,
 21    task::{Context, Poll},
 22    time::Instant,
 23};
 24use unicase::UniCase;
 25
 26pub use take_until::*;
 27
 28#[macro_export]
 29macro_rules! debug_panic {
 30    ( $($fmt_arg:tt)* ) => {
 31        if cfg!(debug_assertions) {
 32            panic!( $($fmt_arg)* );
 33        } else {
 34            let backtrace = std::backtrace::Backtrace::capture();
 35            log::error!("{}\n{:?}", format_args!($($fmt_arg)*), backtrace);
 36        }
 37    };
 38}
 39
 40pub fn truncate(s: &str, max_chars: usize) -> &str {
 41    match s.char_indices().nth(max_chars) {
 42        None => s,
 43        Some((idx, _)) => &s[..idx],
 44    }
 45}
 46
 47pub fn http_proxy_from_env() -> Option<isahc::http::Uri> {
 48    macro_rules! try_env {
 49        ($($env:literal),+) => {
 50            $(
 51                if let Ok(env) = std::env::var($env) {
 52                    return env.parse::<isahc::http::Uri>().ok();
 53                }
 54            )+
 55        };
 56    }
 57
 58    try_env!(
 59        "ALL_PROXY",
 60        "all_proxy",
 61        "HTTPS_PROXY",
 62        "https_proxy",
 63        "HTTP_PROXY",
 64        "http_proxy"
 65    );
 66    None
 67}
 68
 69/// Removes characters from the end of the string if its length is greater than `max_chars` and
 70/// appends "..." to the string. Returns string unchanged if its length is smaller than max_chars.
 71pub fn truncate_and_trailoff(s: &str, max_chars: usize) -> String {
 72    debug_assert!(max_chars >= 5);
 73
 74    let truncation_ix = s.char_indices().map(|(i, _)| i).nth(max_chars);
 75    match truncation_ix {
 76        Some(length) => s[..length].to_string() + "",
 77        None => s.to_string(),
 78    }
 79}
 80
 81/// Removes characters from the front of the string if its length is greater than `max_chars` and
 82/// prepends the string with "...". Returns string unchanged if its length is smaller than max_chars.
 83pub fn truncate_and_remove_front(s: &str, max_chars: usize) -> String {
 84    debug_assert!(max_chars >= 5);
 85
 86    let truncation_ix = s.char_indices().map(|(i, _)| i).nth_back(max_chars);
 87    match truncation_ix {
 88        Some(length) => "".to_string() + &s[length..],
 89        None => s.to_string(),
 90    }
 91}
 92
 93pub fn post_inc<T: From<u8> + AddAssign<T> + Copy>(value: &mut T) -> T {
 94    let prev = *value;
 95    *value += T::from(1);
 96    prev
 97}
 98
 99/// Extend a sorted vector with a sorted sequence of items, maintaining the vector's sort order and
100/// enforcing a maximum length. This also de-duplicates items. Sort the items according to the given callback. Before calling this,
101/// both `vec` and `new_items` should already be sorted according to the `cmp` comparator.
102pub fn extend_sorted<T, I, F>(vec: &mut Vec<T>, new_items: I, limit: usize, mut cmp: F)
103where
104    I: IntoIterator<Item = T>,
105    F: FnMut(&T, &T) -> Ordering,
106{
107    let mut start_index = 0;
108    for new_item in new_items {
109        if let Err(i) = vec[start_index..].binary_search_by(|m| cmp(m, &new_item)) {
110            let index = start_index + i;
111            if vec.len() < limit {
112                vec.insert(index, new_item);
113            } else if index < vec.len() {
114                vec.pop();
115                vec.insert(index, new_item);
116            }
117            start_index = index;
118        }
119    }
120}
121
122pub fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
123    use serde_json::Value;
124
125    match (source, target) {
126        (Value::Object(source), Value::Object(target)) => {
127            for (key, value) in source {
128                if let Some(target) = target.get_mut(&key) {
129                    merge_json_value_into(value, target);
130                } else {
131                    target.insert(key.clone(), value);
132                }
133            }
134        }
135
136        (source, target) => *target = source,
137    }
138}
139
140pub fn merge_non_null_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
141    use serde_json::Value;
142    if let Value::Object(source_object) = source {
143        let target_object = if let Value::Object(target) = target {
144            target
145        } else {
146            *target = Value::Object(Default::default());
147            target.as_object_mut().unwrap()
148        };
149        for (key, value) in source_object {
150            if let Some(target) = target_object.get_mut(&key) {
151                merge_non_null_json_value_into(value, target);
152            } else if !value.is_null() {
153                target_object.insert(key.clone(), value);
154            }
155        }
156    } else if !source.is_null() {
157        *target = source
158    }
159}
160
161pub fn measure<R>(label: &str, f: impl FnOnce() -> R) -> R {
162    lazy_static! {
163        pub static ref ZED_MEASUREMENTS: bool = env::var("ZED_MEASUREMENTS")
164            .map(|measurements| measurements == "1" || measurements == "true")
165            .unwrap_or(false);
166    }
167
168    if *ZED_MEASUREMENTS {
169        let start = Instant::now();
170        let result = f();
171        let elapsed = start.elapsed();
172        eprintln!("{}: {:?}", label, elapsed);
173        result
174    } else {
175        f()
176    }
177}
178
179pub trait ResultExt<E> {
180    type Ok;
181
182    fn log_err(self) -> Option<Self::Ok>;
183    /// Assert that this result should never be an error in development or tests.
184    fn debug_assert_ok(self, reason: &str) -> Self;
185    fn warn_on_err(self) -> Option<Self::Ok>;
186    fn inspect_error(self, func: impl FnOnce(&E)) -> Self;
187}
188
189impl<T, E> ResultExt<E> for Result<T, E>
190where
191    E: std::fmt::Debug,
192{
193    type Ok = T;
194
195    #[track_caller]
196    fn log_err(self) -> Option<T> {
197        match self {
198            Ok(value) => Some(value),
199            Err(error) => {
200                let caller = Location::caller();
201                log::error!("{}:{}: {:?}", caller.file(), caller.line(), error);
202                None
203            }
204        }
205    }
206
207    #[track_caller]
208    fn debug_assert_ok(self, reason: &str) -> Self {
209        if let Err(error) = &self {
210            debug_panic!("{reason} - {error:?}");
211        }
212        self
213    }
214
215    fn warn_on_err(self) -> Option<T> {
216        match self {
217            Ok(value) => Some(value),
218            Err(error) => {
219                log::warn!("{:?}", error);
220                None
221            }
222        }
223    }
224
225    /// https://doc.rust-lang.org/std/result/enum.Result.html#method.inspect_err
226    fn inspect_error(self, func: impl FnOnce(&E)) -> Self {
227        if let Err(err) = &self {
228            func(err);
229        }
230
231        self
232    }
233}
234
235pub trait TryFutureExt {
236    fn log_err(self) -> LogErrorFuture<Self>
237    where
238        Self: Sized;
239
240    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
241    where
242        Self: Sized;
243
244    fn warn_on_err(self) -> LogErrorFuture<Self>
245    where
246        Self: Sized;
247    fn unwrap(self) -> UnwrapFuture<Self>
248    where
249        Self: Sized;
250}
251
252impl<F, T, E> TryFutureExt for F
253where
254    F: Future<Output = Result<T, E>>,
255    E: std::fmt::Debug,
256{
257    #[track_caller]
258    fn log_err(self) -> LogErrorFuture<Self>
259    where
260        Self: Sized,
261    {
262        let location = Location::caller();
263        LogErrorFuture(self, log::Level::Error, *location)
264    }
265
266    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
267    where
268        Self: Sized,
269    {
270        LogErrorFuture(self, log::Level::Error, location)
271    }
272
273    #[track_caller]
274    fn warn_on_err(self) -> LogErrorFuture<Self>
275    where
276        Self: Sized,
277    {
278        let location = Location::caller();
279        LogErrorFuture(self, log::Level::Warn, *location)
280    }
281
282    fn unwrap(self) -> UnwrapFuture<Self>
283    where
284        Self: Sized,
285    {
286        UnwrapFuture(self)
287    }
288}
289
290#[must_use]
291pub struct LogErrorFuture<F>(F, log::Level, core::panic::Location<'static>);
292
293impl<F, T, E> Future for LogErrorFuture<F>
294where
295    F: Future<Output = Result<T, E>>,
296    E: std::fmt::Debug,
297{
298    type Output = Option<T>;
299
300    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
301        let level = self.1;
302        let location = self.2;
303        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
304        match inner.poll(cx) {
305            Poll::Ready(output) => Poll::Ready(match output {
306                Ok(output) => Some(output),
307                Err(error) => {
308                    log::log!(
309                        level,
310                        "{}:{}: {:?}",
311                        location.file(),
312                        location.line(),
313                        error
314                    );
315                    None
316                }
317            }),
318            Poll::Pending => Poll::Pending,
319        }
320    }
321}
322
323pub struct UnwrapFuture<F>(F);
324
325impl<F, T, E> Future for UnwrapFuture<F>
326where
327    F: Future<Output = Result<T, E>>,
328    E: std::fmt::Debug,
329{
330    type Output = T;
331
332    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
333        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
334        match inner.poll(cx) {
335            Poll::Ready(result) => Poll::Ready(result.unwrap()),
336            Poll::Pending => Poll::Pending,
337        }
338    }
339}
340
341pub struct Deferred<F: FnOnce()>(Option<F>);
342
343impl<F: FnOnce()> Deferred<F> {
344    /// Drop without running the deferred function.
345    pub fn abort(mut self) {
346        self.0.take();
347    }
348}
349
350impl<F: FnOnce()> Drop for Deferred<F> {
351    fn drop(&mut self) {
352        if let Some(f) = self.0.take() {
353            f()
354        }
355    }
356}
357
358/// Run the given function when the returned value is dropped (unless it's cancelled).
359pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
360    Deferred(Some(f))
361}
362
363pub struct RandomCharIter<T: Rng> {
364    rng: T,
365    simple_text: bool,
366}
367
368impl<T: Rng> RandomCharIter<T> {
369    pub fn new(rng: T) -> Self {
370        Self {
371            rng,
372            simple_text: std::env::var("SIMPLE_TEXT").map_or(false, |v| !v.is_empty()),
373        }
374    }
375
376    pub fn with_simple_text(mut self) -> Self {
377        self.simple_text = true;
378        self
379    }
380}
381
382impl<T: Rng> Iterator for RandomCharIter<T> {
383    type Item = char;
384
385    fn next(&mut self) -> Option<Self::Item> {
386        if self.simple_text {
387            return if self.rng.gen_range(0..100) < 5 {
388                Some('\n')
389            } else {
390                Some(self.rng.gen_range(b'a'..b'z' + 1).into())
391            };
392        }
393
394        match self.rng.gen_range(0..100) {
395            // whitespace
396            0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
397            // two-byte greek letters
398            20..=32 => char::from_u32(self.rng.gen_range(('α' as u32)..('ω' as u32 + 1))),
399            // // three-byte characters
400            33..=45 => ['✋', '✅', '❌', '❎', '⭐']
401                .choose(&mut self.rng)
402                .copied(),
403            // // four-byte characters
404            46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.rng).copied(),
405            // ascii letters
406            _ => Some(self.rng.gen_range(b'a'..b'z' + 1).into()),
407        }
408    }
409}
410
411/// Get an embedded file as a string.
412pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
413    match A::get(path).unwrap().data {
414        Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
415        Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
416    }
417}
418
419// copy unstable standard feature option unzip
420// https://github.com/rust-lang/rust/issues/87800
421// Remove when this ship in Rust 1.66 or 1.67
422pub fn unzip_option<T, U>(option: Option<(T, U)>) -> (Option<T>, Option<U>) {
423    match option {
424        Some((a, b)) => (Some(a), Some(b)),
425        None => (None, None),
426    }
427}
428
429/// Evaluates to an immediately invoked function expression. Good for using the ? operator
430/// in functions which do not return an Option or Result
431#[macro_export]
432macro_rules! maybe {
433    ($block:block) => {
434        (|| $block)()
435    };
436}
437
438/// Evaluates to an immediately invoked function expression. Good for using the ? operator
439/// in functions which do not return an Option or Result, but async.
440#[macro_export]
441macro_rules! async_maybe {
442    ($block:block) => {
443        (|| async move { $block })()
444    };
445}
446
447pub trait RangeExt<T> {
448    fn sorted(&self) -> Self;
449    fn to_inclusive(&self) -> RangeInclusive<T>;
450    fn overlaps(&self, other: &Range<T>) -> bool;
451    fn contains_inclusive(&self, other: &Range<T>) -> bool;
452}
453
454impl<T: Ord + Clone> RangeExt<T> for Range<T> {
455    fn sorted(&self) -> Self {
456        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
457    }
458
459    fn to_inclusive(&self) -> RangeInclusive<T> {
460        self.start.clone()..=self.end.clone()
461    }
462
463    fn overlaps(&self, other: &Range<T>) -> bool {
464        self.start < other.end && other.start < self.end
465    }
466
467    fn contains_inclusive(&self, other: &Range<T>) -> bool {
468        self.start <= other.start && other.end <= self.end
469    }
470}
471
472impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
473    fn sorted(&self) -> Self {
474        cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
475    }
476
477    fn to_inclusive(&self) -> RangeInclusive<T> {
478        self.clone()
479    }
480
481    fn overlaps(&self, other: &Range<T>) -> bool {
482        self.start() < &other.end && &other.start <= self.end()
483    }
484
485    fn contains_inclusive(&self, other: &Range<T>) -> bool {
486        self.start() <= &other.start && &other.end <= self.end()
487    }
488}
489
490/// A way to sort strings with starting numbers numerically first, falling back to alphanumeric one,
491/// case-insensitive.
492///
493/// This is useful for turning regular alphanumerically sorted sequences as `1-abc, 10, 11-def, .., 2, 21-abc`
494/// into `1-abc, 2, 10, 11-def, .., 21-abc`
495#[derive(Debug, PartialEq, Eq)]
496pub struct NumericPrefixWithSuffix<'a>(i32, &'a str);
497
498impl<'a> NumericPrefixWithSuffix<'a> {
499    pub fn from_numeric_prefixed_str(str: &'a str) -> Option<Self> {
500        let mut chars = str.chars();
501        let prefix: String = chars.by_ref().take_while(|c| c.is_ascii_digit()).collect();
502        let remainder = chars.as_str();
503
504        match prefix.parse::<i32>() {
505            Ok(prefix) => Some(NumericPrefixWithSuffix(prefix, remainder)),
506            Err(_) => None,
507        }
508    }
509}
510
511impl Ord for NumericPrefixWithSuffix<'_> {
512    fn cmp(&self, other: &Self) -> Ordering {
513        let NumericPrefixWithSuffix(num_a, remainder_a) = self;
514        let NumericPrefixWithSuffix(num_b, remainder_b) = other;
515        num_a
516            .cmp(num_b)
517            .then_with(|| UniCase::new(remainder_a).cmp(&UniCase::new(remainder_b)))
518    }
519}
520
521impl<'a> PartialOrd for NumericPrefixWithSuffix<'a> {
522    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
523        Some(self.cmp(other))
524    }
525}
526lazy_static! {
527    static ref EMOJI_REGEX: regex::Regex = regex::Regex::new("(\\p{Emoji}|\u{200D})").unwrap();
528}
529
530/// Returns true if the given string consists of emojis only.
531/// E.g. "👨‍👩‍👧‍👧👋" will return true, but "👋!" will return false.
532pub fn word_consists_of_emojis(s: &str) -> bool {
533    let mut prev_end = 0;
534    for capture in EMOJI_REGEX.find_iter(s) {
535        if capture.start() != prev_end {
536            return false;
537        }
538        prev_end = capture.end();
539    }
540    prev_end == s.len()
541}
542
543#[cfg(test)]
544mod tests {
545    use super::*;
546
547    #[test]
548    fn test_extend_sorted() {
549        let mut vec = vec![];
550
551        extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
552        assert_eq!(vec, &[21, 17, 13, 8, 1]);
553
554        extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
555        assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
556
557        extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
558        assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
559    }
560
561    #[test]
562    fn test_iife() {
563        fn option_returning_function() -> Option<()> {
564            None
565        }
566
567        let foo = maybe!({
568            option_returning_function()?;
569            Some(())
570        });
571
572        assert_eq!(foo, None);
573    }
574
575    #[test]
576    fn test_trancate_and_trailoff() {
577        assert_eq!(truncate_and_trailoff("", 5), "");
578        assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
579        assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
580        assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
581    }
582
583    #[test]
584    fn test_numeric_prefix_with_suffix() {
585        let mut sorted = vec!["1-abc", "10", "11def", "2", "21-abc"];
586        sorted.sort_by_key(|s| {
587            NumericPrefixWithSuffix::from_numeric_prefixed_str(s).unwrap_or_else(|| {
588                panic!("Cannot convert string `{s}` into NumericPrefixWithSuffix")
589            })
590        });
591        assert_eq!(sorted, ["1-abc", "2", "10", "11def", "21-abc"]);
592
593        for numeric_prefix_less in ["numeric_prefix_less", "aaa", "~™£"] {
594            assert_eq!(
595                NumericPrefixWithSuffix::from_numeric_prefixed_str(numeric_prefix_less),
596                None,
597                "String without numeric prefix `{numeric_prefix_less}` should not be converted into NumericPrefixWithSuffix"
598            )
599        }
600    }
601
602    #[test]
603    fn test_word_consists_of_emojis() {
604        let words_to_test = vec![
605            ("👨‍👩‍👧‍👧👋🥒", true),
606            ("👋", true),
607            ("!👋", false),
608            ("👋!", false),
609            ("👋 ", false),
610            (" 👋", false),
611            ("Test", false),
612        ];
613
614        for (text, expected_result) in words_to_test {
615            assert_eq!(word_consists_of_emojis(text), expected_result);
616        }
617    }
618}