util.rs

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