util.rs

  1pub mod arc_cow;
  2pub mod command;
  3pub mod fs;
  4pub mod markdown;
  5pub mod paths;
  6pub mod serde;
  7#[cfg(any(test, feature = "test-support"))]
  8pub mod test;
  9
 10use anyhow::Result;
 11use futures::Future;
 12use itertools::Either;
 13use regex::Regex;
 14use std::sync::{LazyLock, OnceLock};
 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
 27#[cfg(unix)]
 28use anyhow::{anyhow, Context as _};
 29
 30pub use take_until::*;
 31
 32#[macro_export]
 33macro_rules! debug_panic {
 34    ( $($fmt_arg:tt)* ) => {
 35        if cfg!(debug_assertions) {
 36            panic!( $($fmt_arg)* );
 37        } else {
 38            let backtrace = std::backtrace::Backtrace::capture();
 39            log::error!("{}\n{:?}", format_args!($($fmt_arg)*), backtrace);
 40        }
 41    };
 42}
 43
 44pub fn truncate(s: &str, max_chars: usize) -> &str {
 45    match s.char_indices().nth(max_chars) {
 46        None => s,
 47        Some((idx, _)) => &s[..idx],
 48    }
 49}
 50
 51/// Removes characters from the end of the string if its length is greater than `max_chars` and
 52/// appends "..." to the string. Returns string unchanged if its length is smaller than max_chars.
 53pub fn truncate_and_trailoff(s: &str, max_chars: usize) -> String {
 54    debug_assert!(max_chars >= 5);
 55
 56    // If the string's byte length is <= max_chars, walking the string can be skipped since the
 57    // number of chars is <= the number of bytes.
 58    if s.len() <= max_chars {
 59        return s.to_string();
 60    }
 61    let truncation_ix = s.char_indices().map(|(i, _)| i).nth(max_chars);
 62    match truncation_ix {
 63        Some(index) => s[..index].to_string() + "",
 64        _ => s.to_string(),
 65    }
 66}
 67
 68/// Removes characters from the front of the string if its length is greater than `max_chars` and
 69/// prepends the string with "...". Returns string unchanged if its length is smaller than max_chars.
 70pub fn truncate_and_remove_front(s: &str, max_chars: usize) -> String {
 71    debug_assert!(max_chars >= 5);
 72
 73    // If the string's byte length is <= max_chars, walking the string can be skipped since the
 74    // number of chars is <= the number of bytes.
 75    if s.len() <= max_chars {
 76        return s.to_string();
 77    }
 78    let suffix_char_length = max_chars.saturating_sub(1);
 79    let truncation_ix = s
 80        .char_indices()
 81        .map(|(i, _)| i)
 82        .nth_back(suffix_char_length);
 83    match truncation_ix {
 84        Some(index) if index > 0 => "".to_string() + &s[index..],
 85        _ => s.to_string(),
 86    }
 87}
 88
 89/// Takes only `max_lines` from the string and, if there were more than `max_lines-1`, appends a
 90/// a newline and "..." to the string, so that `max_lines` are returned.
 91/// Returns string unchanged if its length is smaller than max_lines.
 92pub fn truncate_lines_and_trailoff(s: &str, max_lines: usize) -> String {
 93    let mut lines = s.lines().take(max_lines).collect::<Vec<_>>();
 94    if lines.len() > max_lines - 1 {
 95        lines.pop();
 96        lines.join("\n") + "\n"
 97    } else {
 98        lines.join("\n")
 99    }
100}
101
102pub fn post_inc<T: From<u8> + AddAssign<T> + Copy>(value: &mut T) -> T {
103    let prev = *value;
104    *value += T::from(1);
105    prev
106}
107
108/// Extend a sorted vector with a sorted sequence of items, maintaining the vector's sort order and
109/// enforcing a maximum length. This also de-duplicates items. Sort the items according to the given callback. Before calling this,
110/// both `vec` and `new_items` should already be sorted according to the `cmp` comparator.
111pub fn extend_sorted<T, I, F>(vec: &mut Vec<T>, new_items: I, limit: usize, mut cmp: F)
112where
113    I: IntoIterator<Item = T>,
114    F: FnMut(&T, &T) -> Ordering,
115{
116    let mut start_index = 0;
117    for new_item in new_items {
118        if let Err(i) = vec[start_index..].binary_search_by(|m| cmp(m, &new_item)) {
119            let index = start_index + i;
120            if vec.len() < limit {
121                vec.insert(index, new_item);
122            } else if index < vec.len() {
123                vec.pop();
124                vec.insert(index, new_item);
125            }
126            start_index = index;
127        }
128    }
129}
130
131pub fn truncate_to_bottom_n_sorted_by<T, F>(items: &mut Vec<T>, limit: usize, compare: &F)
132where
133    F: Fn(&T, &T) -> Ordering,
134{
135    if limit == 0 {
136        items.truncate(0);
137    }
138    if items.len() <= limit {
139        items.sort_by(compare);
140        return;
141    }
142    // When limit is near to items.len() it may be more efficient to sort the whole list and
143    // truncate, rather than always doing selection first as is done below. It's hard to analyze
144    // where the threshold for this should be since the quickselect style algorithm used by
145    // `select_nth_unstable_by` makes the prefix partially sorted, and so its work is not wasted -
146    // the expected number of comparisons needed by `sort_by` is less than it is for some arbitrary
147    // unsorted input.
148    items.select_nth_unstable_by(limit, compare);
149    items.truncate(limit);
150    items.sort_by(compare);
151}
152
153#[cfg(unix)]
154pub fn load_shell_from_passwd() -> Result<()> {
155    let buflen = match unsafe { libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) } {
156        n if n < 0 => 1024,
157        n => n as usize,
158    };
159    let mut buffer = Vec::with_capacity(buflen);
160
161    let mut pwd: std::mem::MaybeUninit<libc::passwd> = std::mem::MaybeUninit::uninit();
162    let mut result: *mut libc::passwd = std::ptr::null_mut();
163
164    let uid = unsafe { libc::getuid() };
165    let status = unsafe {
166        libc::getpwuid_r(
167            uid,
168            pwd.as_mut_ptr(),
169            buffer.as_mut_ptr() as *mut libc::c_char,
170            buflen,
171            &mut result,
172        )
173    };
174    let entry = unsafe { pwd.assume_init() };
175
176    anyhow::ensure!(
177        status == 0,
178        "call to getpwuid_r failed. uid: {}, status: {}",
179        uid,
180        status
181    );
182    anyhow::ensure!(!result.is_null(), "passwd entry for uid {} not found", uid);
183    anyhow::ensure!(
184        entry.pw_uid == uid,
185        "passwd entry has different uid ({}) than getuid ({}) returned",
186        entry.pw_uid,
187        uid,
188    );
189
190    let shell = unsafe { std::ffi::CStr::from_ptr(entry.pw_shell).to_str().unwrap() };
191    if env::var("SHELL").map_or(true, |shell_env| shell_env != shell) {
192        log::info!(
193            "updating SHELL environment variable to value from passwd entry: {:?}",
194            shell,
195        );
196        env::set_var("SHELL", shell);
197    }
198
199    Ok(())
200}
201
202#[cfg(unix)]
203pub fn load_login_shell_environment() -> Result<()> {
204    let marker = "ZED_LOGIN_SHELL_START";
205    let shell = env::var("SHELL").context(
206        "SHELL environment variable is not assigned so we can't source login environment variables",
207    )?;
208
209    // If possible, we want to `cd` in the user's `$HOME` to trigger programs
210    // such as direnv, asdf, mise, ... to adjust the PATH. These tools often hook
211    // into shell's `cd` command (and hooks) to manipulate env.
212    // We do this so that we get the env a user would have when spawning a shell
213    // in home directory.
214    let shell_cmd_prefix = std::env::var_os("HOME")
215        .and_then(|home| home.into_string().ok())
216        .map(|home| format!("cd '{home}';"));
217
218    // The `exit 0` is the result of hours of debugging, trying to find out
219    // why running this command here, without `exit 0`, would mess
220    // up signal process for our process so that `ctrl-c` doesn't work
221    // anymore.
222    // We still don't know why `$SHELL -l -i -c '/usr/bin/env -0'`  would
223    // do that, but it does, and `exit 0` helps.
224    let shell_cmd = format!(
225        "{}printf '%s' {marker}; /usr/bin/env; exit 0;",
226        shell_cmd_prefix.as_deref().unwrap_or("")
227    );
228
229    let output = std::process::Command::new(&shell)
230        .args(["-l", "-i", "-c", &shell_cmd])
231        .output()
232        .context("failed to spawn login shell to source login environment variables")?;
233    if !output.status.success() {
234        Err(anyhow!("login shell exited with error"))?;
235    }
236
237    let stdout = String::from_utf8_lossy(&output.stdout);
238
239    if let Some(env_output_start) = stdout.find(marker) {
240        let env_output = &stdout[env_output_start + marker.len()..];
241
242        parse_env_output(env_output, |key, value| env::set_var(key, value));
243
244        log::info!(
245            "set environment variables from shell:{}, path:{}",
246            shell,
247            env::var("PATH").unwrap_or_default(),
248        );
249    }
250
251    Ok(())
252}
253
254/// Parse the result of calling `usr/bin/env` with no arguments
255pub fn parse_env_output(env: &str, mut f: impl FnMut(String, String)) {
256    let mut current_key: Option<String> = None;
257    let mut current_value: Option<String> = None;
258
259    for line in env.split_terminator('\n') {
260        if let Some(separator_index) = line.find('=') {
261            if !line[..separator_index].is_empty() {
262                if let Some((key, value)) = Option::zip(current_key.take(), current_value.take()) {
263                    f(key, value)
264                }
265                current_key = Some(line[..separator_index].to_string());
266                current_value = Some(line[separator_index + 1..].to_string());
267                continue;
268            };
269        }
270        if let Some(value) = current_value.as_mut() {
271            value.push('\n');
272            value.push_str(line);
273        }
274    }
275    if let Some((key, value)) = Option::zip(current_key.take(), current_value.take()) {
276        f(key, value)
277    }
278}
279
280pub fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
281    use serde_json::Value;
282
283    match (source, target) {
284        (Value::Object(source), Value::Object(target)) => {
285            for (key, value) in source {
286                if let Some(target) = target.get_mut(&key) {
287                    merge_json_value_into(value, target);
288                } else {
289                    target.insert(key.clone(), value);
290                }
291            }
292        }
293
294        (Value::Array(source), Value::Array(target)) => {
295            for value in source {
296                target.push(value);
297            }
298        }
299
300        (source, target) => *target = source,
301    }
302}
303
304pub fn merge_non_null_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
305    use serde_json::Value;
306    if let Value::Object(source_object) = source {
307        let target_object = if let Value::Object(target) = target {
308            target
309        } else {
310            *target = Value::Object(Default::default());
311            target.as_object_mut().unwrap()
312        };
313        for (key, value) in source_object {
314            if let Some(target) = target_object.get_mut(&key) {
315                merge_non_null_json_value_into(value, target);
316            } else if !value.is_null() {
317                target_object.insert(key.clone(), value);
318            }
319        }
320    } else if !source.is_null() {
321        *target = source
322    }
323}
324
325pub fn measure<R>(label: &str, f: impl FnOnce() -> R) -> R {
326    static ZED_MEASUREMENTS: OnceLock<bool> = OnceLock::new();
327    let zed_measurements = ZED_MEASUREMENTS.get_or_init(|| {
328        env::var("ZED_MEASUREMENTS")
329            .map(|measurements| measurements == "1" || measurements == "true")
330            .unwrap_or(false)
331    });
332
333    if *zed_measurements {
334        let start = Instant::now();
335        let result = f();
336        let elapsed = start.elapsed();
337        eprintln!("{}: {:?}", label, elapsed);
338        result
339    } else {
340        f()
341    }
342}
343
344pub fn iterate_expanded_and_wrapped_usize_range(
345    range: Range<usize>,
346    additional_before: usize,
347    additional_after: usize,
348    wrap_length: usize,
349) -> impl Iterator<Item = usize> {
350    let start_wraps = range.start < additional_before;
351    let end_wraps = wrap_length < range.end + additional_after;
352    if start_wraps && end_wraps {
353        Either::Left(0..wrap_length)
354    } else if start_wraps {
355        let wrapped_start = (range.start + wrap_length).saturating_sub(additional_before);
356        if wrapped_start <= range.end {
357            Either::Left(0..wrap_length)
358        } else {
359            Either::Right((0..range.end + additional_after).chain(wrapped_start..wrap_length))
360        }
361    } else if end_wraps {
362        let wrapped_end = range.end + additional_after - wrap_length;
363        if range.start <= wrapped_end {
364            Either::Left(0..wrap_length)
365        } else {
366            Either::Right((0..wrapped_end).chain(range.start - additional_before..wrap_length))
367        }
368    } else {
369        Either::Left((range.start - additional_before)..(range.end + additional_after))
370    }
371}
372
373pub trait ResultExt<E> {
374    type Ok;
375
376    fn log_err(self) -> Option<Self::Ok>;
377    /// Assert that this result should never be an error in development or tests.
378    fn debug_assert_ok(self, reason: &str) -> Self;
379    fn warn_on_err(self) -> Option<Self::Ok>;
380    fn log_with_level(self, level: log::Level) -> Option<Self::Ok>;
381    fn anyhow(self) -> anyhow::Result<Self::Ok>
382    where
383        E: Into<anyhow::Error>;
384}
385
386impl<T, E> ResultExt<E> for Result<T, E>
387where
388    E: std::fmt::Debug,
389{
390    type Ok = T;
391
392    #[track_caller]
393    fn log_err(self) -> Option<T> {
394        self.log_with_level(log::Level::Error)
395    }
396
397    #[track_caller]
398    fn debug_assert_ok(self, reason: &str) -> Self {
399        if let Err(error) = &self {
400            debug_panic!("{reason} - {error:?}");
401        }
402        self
403    }
404
405    #[track_caller]
406    fn warn_on_err(self) -> Option<T> {
407        self.log_with_level(log::Level::Warn)
408    }
409
410    #[track_caller]
411    fn log_with_level(self, level: log::Level) -> Option<T> {
412        match self {
413            Ok(value) => Some(value),
414            Err(error) => {
415                log_error_with_caller(*Location::caller(), error, level);
416                None
417            }
418        }
419    }
420
421    fn anyhow(self) -> anyhow::Result<T>
422    where
423        E: Into<anyhow::Error>,
424    {
425        self.map_err(Into::into)
426    }
427}
428
429fn log_error_with_caller<E>(caller: core::panic::Location<'_>, error: E, level: log::Level)
430where
431    E: std::fmt::Debug,
432{
433    #[cfg(not(target_os = "windows"))]
434    let file = caller.file();
435    #[cfg(target_os = "windows")]
436    let file = caller.file().replace('\\', "/");
437    // In this codebase, the first segment of the file path is
438    // the 'crates' folder, followed by the crate name.
439    let target = file.split('/').nth(1);
440
441    log::logger().log(
442        &log::Record::builder()
443            .target(target.unwrap_or(""))
444            .module_path(target)
445            .args(format_args!("{:?}", error))
446            .file(Some(caller.file()))
447            .line(Some(caller.line()))
448            .level(level)
449            .build(),
450    );
451}
452
453pub fn log_err<E: std::fmt::Debug>(error: &E) {
454    log_error_with_caller(*Location::caller(), error, log::Level::Warn);
455}
456
457pub trait TryFutureExt {
458    fn log_err(self) -> LogErrorFuture<Self>
459    where
460        Self: Sized;
461
462    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
463    where
464        Self: Sized;
465
466    fn warn_on_err(self) -> LogErrorFuture<Self>
467    where
468        Self: Sized;
469    fn unwrap(self) -> UnwrapFuture<Self>
470    where
471        Self: Sized;
472}
473
474impl<F, T, E> TryFutureExt for F
475where
476    F: Future<Output = Result<T, E>>,
477    E: std::fmt::Debug,
478{
479    #[track_caller]
480    fn log_err(self) -> LogErrorFuture<Self>
481    where
482        Self: Sized,
483    {
484        let location = Location::caller();
485        LogErrorFuture(self, log::Level::Error, *location)
486    }
487
488    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
489    where
490        Self: Sized,
491    {
492        LogErrorFuture(self, log::Level::Error, location)
493    }
494
495    #[track_caller]
496    fn warn_on_err(self) -> LogErrorFuture<Self>
497    where
498        Self: Sized,
499    {
500        let location = Location::caller();
501        LogErrorFuture(self, log::Level::Warn, *location)
502    }
503
504    fn unwrap(self) -> UnwrapFuture<Self>
505    where
506        Self: Sized,
507    {
508        UnwrapFuture(self)
509    }
510}
511
512#[must_use]
513pub struct LogErrorFuture<F>(F, log::Level, core::panic::Location<'static>);
514
515impl<F, T, E> Future for LogErrorFuture<F>
516where
517    F: Future<Output = Result<T, E>>,
518    E: std::fmt::Debug,
519{
520    type Output = Option<T>;
521
522    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
523        let level = self.1;
524        let location = self.2;
525        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
526        match inner.poll(cx) {
527            Poll::Ready(output) => Poll::Ready(match output {
528                Ok(output) => Some(output),
529                Err(error) => {
530                    log_error_with_caller(location, error, level);
531                    None
532                }
533            }),
534            Poll::Pending => Poll::Pending,
535        }
536    }
537}
538
539pub struct UnwrapFuture<F>(F);
540
541impl<F, T, E> Future for UnwrapFuture<F>
542where
543    F: Future<Output = Result<T, E>>,
544    E: std::fmt::Debug,
545{
546    type Output = T;
547
548    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
549        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
550        match inner.poll(cx) {
551            Poll::Ready(result) => Poll::Ready(result.unwrap()),
552            Poll::Pending => Poll::Pending,
553        }
554    }
555}
556
557pub struct Deferred<F: FnOnce()>(Option<F>);
558
559impl<F: FnOnce()> Deferred<F> {
560    /// Drop without running the deferred function.
561    pub fn abort(mut self) {
562        self.0.take();
563    }
564}
565
566impl<F: FnOnce()> Drop for Deferred<F> {
567    fn drop(&mut self) {
568        if let Some(f) = self.0.take() {
569            f()
570        }
571    }
572}
573
574/// Run the given function when the returned value is dropped (unless it's cancelled).
575#[must_use]
576pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
577    Deferred(Some(f))
578}
579
580#[cfg(any(test, feature = "test-support"))]
581mod rng {
582    use rand::{seq::SliceRandom, Rng};
583    pub struct RandomCharIter<T: Rng> {
584        rng: T,
585        simple_text: bool,
586    }
587
588    impl<T: Rng> RandomCharIter<T> {
589        pub fn new(rng: T) -> Self {
590            Self {
591                rng,
592                simple_text: std::env::var("SIMPLE_TEXT").map_or(false, |v| !v.is_empty()),
593            }
594        }
595
596        pub fn with_simple_text(mut self) -> Self {
597            self.simple_text = true;
598            self
599        }
600    }
601
602    impl<T: Rng> Iterator for RandomCharIter<T> {
603        type Item = char;
604
605        fn next(&mut self) -> Option<Self::Item> {
606            if self.simple_text {
607                return if self.rng.gen_range(0..100) < 5 {
608                    Some('\n')
609                } else {
610                    Some(self.rng.gen_range(b'a'..b'z' + 1).into())
611                };
612            }
613
614            match self.rng.gen_range(0..100) {
615                // whitespace
616                0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
617                // two-byte greek letters
618                20..=32 => char::from_u32(self.rng.gen_range(('α' as u32)..('ω' as u32 + 1))),
619                // // three-byte characters
620                33..=45 => ['✋', '✅', '❌', '❎', '⭐']
621                    .choose(&mut self.rng)
622                    .copied(),
623                // // four-byte characters
624                46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.rng).copied(),
625                // ascii letters
626                _ => Some(self.rng.gen_range(b'a'..b'z' + 1).into()),
627            }
628        }
629    }
630}
631#[cfg(any(test, feature = "test-support"))]
632pub use rng::RandomCharIter;
633/// Get an embedded file as a string.
634pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
635    match A::get(path).unwrap().data {
636        Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
637        Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
638    }
639}
640
641/// Expands to an immediately-invoked function expression. Good for using the ? operator
642/// in functions which do not return an Option or Result.
643///
644/// Accepts a normal block, an async block, or an async move block.
645#[macro_export]
646macro_rules! maybe {
647    ($block:block) => {
648        (|| $block)()
649    };
650    (async $block:block) => {
651        (|| async $block)()
652    };
653    (async move $block:block) => {
654        (|| async move $block)()
655    };
656}
657
658pub trait RangeExt<T> {
659    fn sorted(&self) -> Self;
660    fn to_inclusive(&self) -> RangeInclusive<T>;
661    fn overlaps(&self, other: &Range<T>) -> bool;
662    fn contains_inclusive(&self, other: &Range<T>) -> bool;
663}
664
665impl<T: Ord + Clone> RangeExt<T> for Range<T> {
666    fn sorted(&self) -> Self {
667        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
668    }
669
670    fn to_inclusive(&self) -> RangeInclusive<T> {
671        self.start.clone()..=self.end.clone()
672    }
673
674    fn overlaps(&self, other: &Range<T>) -> bool {
675        self.start < other.end && other.start < self.end
676    }
677
678    fn contains_inclusive(&self, other: &Range<T>) -> bool {
679        self.start <= other.start && other.end <= self.end
680    }
681}
682
683impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
684    fn sorted(&self) -> Self {
685        cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
686    }
687
688    fn to_inclusive(&self) -> RangeInclusive<T> {
689        self.clone()
690    }
691
692    fn overlaps(&self, other: &Range<T>) -> bool {
693        self.start() < &other.end && &other.start <= self.end()
694    }
695
696    fn contains_inclusive(&self, other: &Range<T>) -> bool {
697        self.start() <= &other.start && &other.end <= self.end()
698    }
699}
700
701/// A way to sort strings with starting numbers numerically first, falling back to alphanumeric one,
702/// case-insensitive.
703///
704/// This is useful for turning regular alphanumerically sorted sequences as `1-abc, 10, 11-def, .., 2, 21-abc`
705/// into `1-abc, 2, 10, 11-def, .., 21-abc`
706#[derive(Debug, PartialEq, Eq)]
707pub struct NumericPrefixWithSuffix<'a>(Option<u64>, &'a str);
708
709impl<'a> NumericPrefixWithSuffix<'a> {
710    pub fn from_numeric_prefixed_str(str: &'a str) -> Self {
711        let i = str.chars().take_while(|c| c.is_ascii_digit()).count();
712        let (prefix, remainder) = str.split_at(i);
713
714        let prefix = prefix.parse().ok();
715        Self(prefix, remainder)
716    }
717}
718
719/// When dealing with equality, we need to consider the case of the strings to achieve strict equality
720/// to handle cases like "a" < "A" instead of "a" == "A".
721impl Ord for NumericPrefixWithSuffix<'_> {
722    fn cmp(&self, other: &Self) -> Ordering {
723        match (self.0, other.0) {
724            (None, None) => UniCase::new(self.1)
725                .cmp(&UniCase::new(other.1))
726                .then_with(|| self.1.cmp(other.1).reverse()),
727            (None, Some(_)) => Ordering::Greater,
728            (Some(_), None) => Ordering::Less,
729            (Some(a), Some(b)) => a.cmp(&b).then_with(|| {
730                UniCase::new(self.1)
731                    .cmp(&UniCase::new(other.1))
732                    .then_with(|| self.1.cmp(other.1).reverse())
733            }),
734        }
735    }
736}
737
738impl<'a> PartialOrd for NumericPrefixWithSuffix<'a> {
739    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
740        Some(self.cmp(other))
741    }
742}
743
744fn emoji_regex() -> &'static Regex {
745    static EMOJI_REGEX: LazyLock<Regex> =
746        LazyLock::new(|| Regex::new("(\\p{Emoji}|\u{200D})").unwrap());
747    &EMOJI_REGEX
748}
749
750/// Returns true if the given string consists of emojis only.
751/// E.g. "👨‍👩‍👧‍👧👋" will return true, but "👋!" will return false.
752pub fn word_consists_of_emojis(s: &str) -> bool {
753    let mut prev_end = 0;
754    for capture in emoji_regex().find_iter(s) {
755        if capture.start() != prev_end {
756            return false;
757        }
758        prev_end = capture.end();
759    }
760    prev_end == s.len()
761}
762
763#[cfg(test)]
764mod tests {
765    use super::*;
766
767    #[test]
768    fn test_extend_sorted() {
769        let mut vec = vec![];
770
771        extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
772        assert_eq!(vec, &[21, 17, 13, 8, 1]);
773
774        extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
775        assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
776
777        extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
778        assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
779    }
780
781    #[test]
782    fn test_truncate_to_bottom_n_sorted_by() {
783        let mut vec: Vec<u32> = vec![5, 2, 3, 4, 1];
784        truncate_to_bottom_n_sorted_by(&mut vec, 10, &u32::cmp);
785        assert_eq!(vec, &[1, 2, 3, 4, 5]);
786
787        vec = vec![5, 2, 3, 4, 1];
788        truncate_to_bottom_n_sorted_by(&mut vec, 5, &u32::cmp);
789        assert_eq!(vec, &[1, 2, 3, 4, 5]);
790
791        vec = vec![5, 2, 3, 4, 1];
792        truncate_to_bottom_n_sorted_by(&mut vec, 4, &u32::cmp);
793        assert_eq!(vec, &[1, 2, 3, 4]);
794
795        vec = vec![5, 2, 3, 4, 1];
796        truncate_to_bottom_n_sorted_by(&mut vec, 1, &u32::cmp);
797        assert_eq!(vec, &[1]);
798
799        vec = vec![5, 2, 3, 4, 1];
800        truncate_to_bottom_n_sorted_by(&mut vec, 0, &u32::cmp);
801        assert!(vec.is_empty());
802    }
803
804    #[test]
805    fn test_iife() {
806        fn option_returning_function() -> Option<()> {
807            None
808        }
809
810        let foo = maybe!({
811            option_returning_function()?;
812            Some(())
813        });
814
815        assert_eq!(foo, None);
816    }
817
818    #[test]
819    fn test_truncate_and_trailoff() {
820        assert_eq!(truncate_and_trailoff("", 5), "");
821        assert_eq!(truncate_and_trailoff("aaaaaa", 7), "aaaaaa");
822        assert_eq!(truncate_and_trailoff("aaaaaa", 6), "aaaaaa");
823        assert_eq!(truncate_and_trailoff("aaaaaa", 5), "aaaaa…");
824        assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
825        assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
826        assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
827    }
828
829    #[test]
830    fn test_truncate_and_remove_front() {
831        assert_eq!(truncate_and_remove_front("", 5), "");
832        assert_eq!(truncate_and_remove_front("aaaaaa", 7), "aaaaaa");
833        assert_eq!(truncate_and_remove_front("aaaaaa", 6), "aaaaaa");
834        assert_eq!(truncate_and_remove_front("aaaaaa", 5), "…aaaaa");
835        assert_eq!(truncate_and_remove_front("èèèèèè", 7), "èèèèèè");
836        assert_eq!(truncate_and_remove_front("èèèèèè", 6), "èèèèèè");
837        assert_eq!(truncate_and_remove_front("èèèèèè", 5), "…èèèèè");
838    }
839
840    #[test]
841    fn test_numeric_prefix_str_method() {
842        let target = "1a";
843        assert_eq!(
844            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
845            NumericPrefixWithSuffix(Some(1), "a")
846        );
847
848        let target = "12ab";
849        assert_eq!(
850            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
851            NumericPrefixWithSuffix(Some(12), "ab")
852        );
853
854        let target = "12_ab";
855        assert_eq!(
856            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
857            NumericPrefixWithSuffix(Some(12), "_ab")
858        );
859
860        let target = "1_2ab";
861        assert_eq!(
862            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
863            NumericPrefixWithSuffix(Some(1), "_2ab")
864        );
865
866        let target = "1.2";
867        assert_eq!(
868            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
869            NumericPrefixWithSuffix(Some(1), ".2")
870        );
871
872        let target = "1.2_a";
873        assert_eq!(
874            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
875            NumericPrefixWithSuffix(Some(1), ".2_a")
876        );
877
878        let target = "12.2_a";
879        assert_eq!(
880            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
881            NumericPrefixWithSuffix(Some(12), ".2_a")
882        );
883
884        let target = "12a.2_a";
885        assert_eq!(
886            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
887            NumericPrefixWithSuffix(Some(12), "a.2_a")
888        );
889    }
890
891    #[test]
892    fn test_numeric_prefix_with_suffix() {
893        let mut sorted = vec!["1-abc", "10", "11def", "2", "21-abc"];
894        sorted.sort_by_key(|s| NumericPrefixWithSuffix::from_numeric_prefixed_str(s));
895        assert_eq!(sorted, ["1-abc", "2", "10", "11def", "21-abc"]);
896
897        for numeric_prefix_less in ["numeric_prefix_less", "aaa", "~™£"] {
898            assert_eq!(
899                NumericPrefixWithSuffix::from_numeric_prefixed_str(numeric_prefix_less),
900                NumericPrefixWithSuffix(None, numeric_prefix_less),
901                "String without numeric prefix `{numeric_prefix_less}` should not be converted into NumericPrefixWithSuffix"
902            )
903        }
904    }
905
906    #[test]
907    fn test_word_consists_of_emojis() {
908        let words_to_test = vec![
909            ("👨‍👩‍👧‍👧👋🥒", true),
910            ("👋", true),
911            ("!👋", false),
912            ("👋!", false),
913            ("👋 ", false),
914            (" 👋", false),
915            ("Test", false),
916        ];
917
918        for (text, expected_result) in words_to_test {
919            assert_eq!(word_consists_of_emojis(text), expected_result);
920        }
921    }
922
923    #[test]
924    fn test_truncate_lines_and_trailoff() {
925        let text = r#"Line 1
926Line 2
927Line 3"#;
928
929        assert_eq!(
930            truncate_lines_and_trailoff(text, 2),
931            r#"Line 1
932…"#
933        );
934
935        assert_eq!(
936            truncate_lines_and_trailoff(text, 3),
937            r#"Line 1
938Line 2
939…"#
940        );
941
942        assert_eq!(
943            truncate_lines_and_trailoff(text, 4),
944            r#"Line 1
945Line 2
946Line 3"#
947        );
948    }
949
950    #[test]
951    fn test_iterate_expanded_and_wrapped_usize_range() {
952        // Neither wrap
953        assert_eq!(
954            iterate_expanded_and_wrapped_usize_range(2..4, 1, 1, 8).collect::<Vec<usize>>(),
955            (1..5).collect::<Vec<usize>>()
956        );
957        // Start wraps
958        assert_eq!(
959            iterate_expanded_and_wrapped_usize_range(2..4, 3, 1, 8).collect::<Vec<usize>>(),
960            ((0..5).chain(7..8)).collect::<Vec<usize>>()
961        );
962        // Start wraps all the way around
963        assert_eq!(
964            iterate_expanded_and_wrapped_usize_range(2..4, 5, 1, 8).collect::<Vec<usize>>(),
965            (0..8).collect::<Vec<usize>>()
966        );
967        // Start wraps all the way around and past 0
968        assert_eq!(
969            iterate_expanded_and_wrapped_usize_range(2..4, 10, 1, 8).collect::<Vec<usize>>(),
970            (0..8).collect::<Vec<usize>>()
971        );
972        // End wraps
973        assert_eq!(
974            iterate_expanded_and_wrapped_usize_range(3..5, 1, 4, 8).collect::<Vec<usize>>(),
975            (0..1).chain(2..8).collect::<Vec<usize>>()
976        );
977        // End wraps all the way around
978        assert_eq!(
979            iterate_expanded_and_wrapped_usize_range(3..5, 1, 5, 8).collect::<Vec<usize>>(),
980            (0..8).collect::<Vec<usize>>()
981        );
982        // End wraps all the way around and past the end
983        assert_eq!(
984            iterate_expanded_and_wrapped_usize_range(3..5, 1, 10, 8).collect::<Vec<usize>>(),
985            (0..8).collect::<Vec<usize>>()
986        );
987        // Both start and end wrap
988        assert_eq!(
989            iterate_expanded_and_wrapped_usize_range(3..5, 4, 4, 8).collect::<Vec<usize>>(),
990            (0..8).collect::<Vec<usize>>()
991        );
992    }
993}