util.rs

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