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