util.rs

   1pub mod archive;
   2pub mod command;
   3pub mod fs;
   4pub mod markdown;
   5pub mod path_list;
   6pub mod paths;
   7pub mod process;
   8pub mod redact;
   9pub mod rel_path;
  10pub mod schemars;
  11pub mod serde;
  12pub mod shell;
  13pub mod shell_builder;
  14pub mod shell_env;
  15pub mod size;
  16#[cfg(any(test, feature = "test-support"))]
  17pub mod test;
  18pub mod time;
  19
  20use anyhow::Result;
  21use itertools::Either;
  22use regex::Regex;
  23use std::path::{Path, PathBuf};
  24use std::sync::LazyLock;
  25use std::{
  26    borrow::Cow,
  27    cmp::{self, Ordering},
  28    ops::{Range, RangeInclusive},
  29};
  30use unicase::UniCase;
  31
  32pub use gpui_util::*;
  33
  34pub use take_until::*;
  35#[cfg(any(test, feature = "test-support"))]
  36pub use util_macros::{line_endings, path, uri};
  37
  38pub use self::shell::{
  39    get_default_system_shell, get_default_system_shell_preferring_bash, get_system_shell,
  40};
  41
  42#[inline]
  43pub const fn is_utf8_char_boundary(u8: u8) -> bool {
  44    // This is bit magic equivalent to: b < 128 || b >= 192
  45    (u8 as i8) >= -0x40
  46}
  47
  48pub fn truncate(s: &str, max_chars: usize) -> &str {
  49    match s.char_indices().nth(max_chars) {
  50        None => s,
  51        Some((idx, _)) => &s[..idx],
  52    }
  53}
  54
  55/// Removes characters from the end of the string if its length is greater than `max_chars` and
  56/// appends "..." to the string. Returns string unchanged if its length is smaller than max_chars.
  57pub fn truncate_and_trailoff(s: &str, max_chars: usize) -> String {
  58    debug_assert!(max_chars >= 5);
  59
  60    // If the string's byte length is <= max_chars, walking the string can be skipped since the
  61    // number of chars is <= the number of bytes.
  62    if s.len() <= max_chars {
  63        return s.to_string();
  64    }
  65    let truncation_ix = s.char_indices().map(|(i, _)| i).nth(max_chars);
  66    match truncation_ix {
  67        Some(index) => s[..index].to_string() + "…",
  68        _ => s.to_string(),
  69    }
  70}
  71
  72/// Removes characters from the front of the string if its length is greater than `max_chars` and
  73/// prepends the string with "...". Returns string unchanged if its length is smaller than max_chars.
  74pub fn truncate_and_remove_front(s: &str, max_chars: usize) -> String {
  75    debug_assert!(max_chars >= 5);
  76
  77    // If the string's byte length is <= max_chars, walking the string can be skipped since the
  78    // number of chars is <= the number of bytes.
  79    if s.len() <= max_chars {
  80        return s.to_string();
  81    }
  82    let suffix_char_length = max_chars.saturating_sub(1);
  83    let truncation_ix = s
  84        .char_indices()
  85        .map(|(i, _)| i)
  86        .nth_back(suffix_char_length);
  87    match truncation_ix {
  88        Some(index) if index > 0 => "…".to_string() + &s[index..],
  89        _ => s.to_string(),
  90    }
  91}
  92
  93/// Takes only `max_lines` from the string and, if there were more than `max_lines-1`, appends a
  94/// a newline and "..." to the string, so that `max_lines` are returned.
  95/// Returns string unchanged if its length is smaller than max_lines.
  96pub fn truncate_lines_and_trailoff(s: &str, max_lines: usize) -> String {
  97    let mut lines = s.lines().take(max_lines).collect::<Vec<_>>();
  98    if lines.len() > max_lines - 1 {
  99        lines.pop();
 100        lines.join("\n") + "\n…"
 101    } else {
 102        lines.join("\n")
 103    }
 104}
 105
 106/// Truncates the string at a character boundary, such that the result is less than `max_bytes` in
 107/// length.
 108pub fn truncate_to_byte_limit(s: &str, max_bytes: usize) -> &str {
 109    if s.len() < max_bytes {
 110        return s;
 111    }
 112
 113    for i in (0..max_bytes).rev() {
 114        if s.is_char_boundary(i) {
 115            return &s[..i];
 116        }
 117    }
 118
 119    ""
 120}
 121
 122/// Takes a prefix of complete lines which fit within the byte limit. If the first line is longer
 123/// than the limit, truncates at a character boundary.
 124pub fn truncate_lines_to_byte_limit(s: &str, max_bytes: usize) -> &str {
 125    if s.len() < max_bytes {
 126        return s;
 127    }
 128
 129    for i in (0..max_bytes).rev() {
 130        if s.is_char_boundary(i) && s.as_bytes()[i] == b'\n' {
 131            // Since the i-th character is \n, valid to slice at i + 1.
 132            return &s[..i + 1];
 133        }
 134    }
 135
 136    truncate_to_byte_limit(s, max_bytes)
 137}
 138
 139#[test]
 140fn test_truncate_lines_to_byte_limit() {
 141    let text = "Line 1\nLine 2\nLine 3\nLine 4";
 142
 143    // Limit that includes all lines
 144    assert_eq!(truncate_lines_to_byte_limit(text, 100), text);
 145
 146    // Exactly the first line
 147    assert_eq!(truncate_lines_to_byte_limit(text, 7), "Line 1\n");
 148
 149    // Limit between lines
 150    assert_eq!(truncate_lines_to_byte_limit(text, 13), "Line 1\n");
 151    assert_eq!(truncate_lines_to_byte_limit(text, 20), "Line 1\nLine 2\n");
 152
 153    // Limit before first newline
 154    assert_eq!(truncate_lines_to_byte_limit(text, 6), "Line ");
 155
 156    // Test with non-ASCII characters
 157    let text_utf8 = "Line 1\nLΓ­ne 2\nLine 3";
 158    assert_eq!(
 159        truncate_lines_to_byte_limit(text_utf8, 15),
 160        "Line 1\nLΓ­ne 2\n"
 161    );
 162}
 163
 164/// Extend a sorted vector with a sorted sequence of items, maintaining the vector's sort order and
 165/// enforcing a maximum length. This also de-duplicates items. Sort the items according to the given callback. Before calling this,
 166/// both `vec` and `new_items` should already be sorted according to the `cmp` comparator.
 167pub fn extend_sorted<T, I, F>(vec: &mut Vec<T>, new_items: I, limit: usize, mut cmp: F)
 168where
 169    I: IntoIterator<Item = T>,
 170    F: FnMut(&T, &T) -> Ordering,
 171{
 172    let mut start_index = 0;
 173    for new_item in new_items {
 174        if let Err(i) = vec[start_index..].binary_search_by(|m| cmp(m, &new_item)) {
 175            let index = start_index + i;
 176            if vec.len() < limit {
 177                vec.insert(index, new_item);
 178            } else if index < vec.len() {
 179                vec.pop();
 180                vec.insert(index, new_item);
 181            }
 182            start_index = index;
 183        }
 184    }
 185}
 186
 187pub fn truncate_to_bottom_n_sorted_by<T, F>(items: &mut Vec<T>, limit: usize, compare: &F)
 188where
 189    F: Fn(&T, &T) -> Ordering,
 190{
 191    if limit == 0 {
 192        items.truncate(0);
 193    }
 194    if items.len() <= limit {
 195        items.sort_by(compare);
 196        return;
 197    }
 198    // When limit is near to items.len() it may be more efficient to sort the whole list and
 199    // truncate, rather than always doing selection first as is done below. It's hard to analyze
 200    // where the threshold for this should be since the quickselect style algorithm used by
 201    // `select_nth_unstable_by` makes the prefix partially sorted, and so its work is not wasted -
 202    // the expected number of comparisons needed by `sort_by` is less than it is for some arbitrary
 203    // unsorted input.
 204    items.select_nth_unstable_by(limit, compare);
 205    items.truncate(limit);
 206    items.sort_by(compare);
 207}
 208
 209/// Prevents execution of the application with root privileges on Unix systems.
 210///
 211/// This function checks if the current process is running with root privileges
 212/// and terminates the program with an error message unless explicitly allowed via the
 213/// `ZED_ALLOW_ROOT` environment variable.
 214#[cfg(unix)]
 215pub fn prevent_root_execution() {
 216    let is_root = nix::unistd::geteuid().is_root();
 217    let allow_root = std::env::var("ZED_ALLOW_ROOT").is_ok_and(|val| val == "true");
 218
 219    if is_root && !allow_root {
 220        eprintln!(
 221            "\
 222Error: Running Zed as root or via sudo is unsupported.
 223       Doing so (even once) may subtly break things for all subsequent non-root usage of Zed.
 224       It is untested and not recommended, don't complain when things break.
 225       If you wish to proceed anyways, set `ZED_ALLOW_ROOT=true` in your environment."
 226        );
 227        std::process::exit(1);
 228    }
 229}
 230
 231#[cfg(unix)]
 232fn load_shell_from_passwd() -> Result<()> {
 233    let buflen = match unsafe { libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) } {
 234        n if n < 0 => 1024,
 235        n => n as usize,
 236    };
 237    let mut buffer = Vec::with_capacity(buflen);
 238
 239    let mut pwd: std::mem::MaybeUninit<libc::passwd> = std::mem::MaybeUninit::uninit();
 240    let mut result: *mut libc::passwd = std::ptr::null_mut();
 241
 242    let uid = unsafe { libc::getuid() };
 243    let status = unsafe {
 244        libc::getpwuid_r(
 245            uid,
 246            pwd.as_mut_ptr(),
 247            buffer.as_mut_ptr() as *mut libc::c_char,
 248            buflen,
 249            &mut result,
 250        )
 251    };
 252    anyhow::ensure!(!result.is_null(), "passwd entry for uid {} not found", uid);
 253
 254    // SAFETY: If `getpwuid_r` doesn't error, we have the entry here.
 255    let entry = unsafe { pwd.assume_init() };
 256
 257    anyhow::ensure!(
 258        status == 0,
 259        "call to getpwuid_r failed. uid: {}, status: {}",
 260        uid,
 261        status
 262    );
 263    anyhow::ensure!(
 264        entry.pw_uid == uid,
 265        "passwd entry has different uid ({}) than getuid ({}) returned",
 266        entry.pw_uid,
 267        uid,
 268    );
 269
 270    let shell = unsafe { std::ffi::CStr::from_ptr(entry.pw_shell).to_str().unwrap() };
 271    let should_set_shell = std::env::var("SHELL").map_or(true, |shell_env| {
 272        shell_env != shell && !std::path::Path::new(&shell_env).exists()
 273    });
 274
 275    if should_set_shell {
 276        log::info!(
 277            "updating SHELL environment variable to value from passwd entry: {:?}",
 278            shell,
 279        );
 280        unsafe { std::env::set_var("SHELL", shell) };
 281    }
 282
 283    Ok(())
 284}
 285
 286/// Returns a shell escaped path for the current zed executable
 287pub fn get_shell_safe_zed_path(shell_kind: shell::ShellKind) -> anyhow::Result<String> {
 288    use anyhow::Context as _;
 289    use paths::PathExt;
 290    let mut zed_path =
 291        std::env::current_exe().context("Failed to determine current zed executable path.")?;
 292    if cfg!(target_os = "linux")
 293        && !zed_path.is_file()
 294        && let Some(truncated) = zed_path
 295            .clone()
 296            .file_name()
 297            .and_then(|s| s.to_str())
 298            .and_then(|n| n.strip_suffix(" (deleted)"))
 299    {
 300        // Might have been deleted during update; let's use the new binary if there is one.
 301        zed_path.set_file_name(truncated);
 302    }
 303
 304    zed_path
 305        .try_shell_safe(shell_kind)
 306        .context("Failed to shell-escape Zed executable path.")
 307}
 308
 309/// Returns a path for the zed cli executable, this function
 310/// should be called from the zed executable, not zed-cli.
 311pub fn get_zed_cli_path() -> Result<PathBuf> {
 312    use anyhow::Context as _;
 313    let zed_path =
 314        std::env::current_exe().context("Failed to determine current zed executable path.")?;
 315    let parent = zed_path
 316        .parent()
 317        .context("Failed to determine parent directory of zed executable path.")?;
 318
 319    let possible_locations: &[&str] = if cfg!(target_os = "macos") {
 320        // On macOS, the zed executable and zed-cli are inside the app bundle,
 321        // so here ./cli is for both installed and development builds.
 322        &["./cli"]
 323    } else if cfg!(target_os = "windows") {
 324        // bin/zed.exe is for installed builds, ./cli.exe is for development builds.
 325        &["bin/zed.exe", "./cli.exe"]
 326    } else if cfg!(target_os = "linux") || cfg!(target_os = "freebsd") {
 327        // bin is the standard, ./cli is for the target directory in development builds.
 328        &["../bin/zed", "./cli"]
 329    } else {
 330        anyhow::bail!("unsupported platform for determining zed-cli path");
 331    };
 332
 333    possible_locations
 334        .iter()
 335        .find_map(|p| {
 336            parent
 337                .join(p)
 338                .canonicalize()
 339                .ok()
 340                .filter(|p| p != &zed_path)
 341        })
 342        .with_context(|| {
 343            format!(
 344                "could not find zed-cli from any of: {}",
 345                possible_locations.join(", ")
 346            )
 347        })
 348}
 349
 350#[cfg(unix)]
 351pub async fn load_login_shell_environment() -> Result<()> {
 352    use anyhow::Context as _;
 353
 354    load_shell_from_passwd().log_err();
 355
 356    // If possible, we want to `cd` in the user's `$HOME` to trigger programs
 357    // such as direnv, asdf, mise, ... to adjust the PATH. These tools often hook
 358    // into shell's `cd` command (and hooks) to manipulate env.
 359    // We do this so that we get the env a user would have when spawning a shell
 360    // in home directory.
 361    for (name, value) in shell_env::capture(get_system_shell(), &[], paths::home_dir())
 362        .await
 363        .with_context(|| format!("capturing environment with {:?}", get_system_shell()))?
 364    {
 365        // Skip SHLVL to prevent it from polluting Zed's process environment.
 366        // The login shell used for env capture increments SHLVL, and if we propagate it,
 367        // terminals spawned by Zed will inherit it and increment again, causing SHLVL
 368        // to start at 2 instead of 1 (and increase by 2 on each reload).
 369        if name == "SHLVL" {
 370            continue;
 371        }
 372        unsafe { std::env::set_var(&name, &value) };
 373    }
 374
 375    log::info!(
 376        "set environment variables from shell:{}, path:{}",
 377        std::env::var("SHELL").unwrap_or_default(),
 378        std::env::var("PATH").unwrap_or_default(),
 379    );
 380
 381    Ok(())
 382}
 383
 384/// Configures the process to start a new session, to prevent interactive shells from taking control
 385/// of the terminal.
 386///
 387/// For more details: <https://registerspill.thorstenball.com/p/how-to-lose-control-of-your-shell>
 388pub fn set_pre_exec_to_start_new_session(
 389    command: &mut std::process::Command,
 390) -> &mut std::process::Command {
 391    // safety: code in pre_exec should be signal safe.
 392    // https://man7.org/linux/man-pages/man7/signal-safety.7.html
 393    #[cfg(unix)]
 394    unsafe {
 395        use std::os::unix::process::CommandExt;
 396        command.pre_exec(|| {
 397            libc::setsid();
 398            Ok(())
 399        });
 400    };
 401    command
 402}
 403
 404pub fn merge_json_lenient_value_into(
 405    source: serde_json_lenient::Value,
 406    target: &mut serde_json_lenient::Value,
 407) {
 408    match (source, target) {
 409        (serde_json_lenient::Value::Object(source), serde_json_lenient::Value::Object(target)) => {
 410            for (key, value) in source {
 411                if let Some(target) = target.get_mut(&key) {
 412                    merge_json_lenient_value_into(value, target);
 413                } else {
 414                    target.insert(key, value);
 415                }
 416            }
 417        }
 418
 419        (serde_json_lenient::Value::Array(source), serde_json_lenient::Value::Array(target)) => {
 420            for value in source {
 421                target.push(value);
 422            }
 423        }
 424
 425        (source, target) => *target = source,
 426    }
 427}
 428
 429pub fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
 430    use serde_json::Value;
 431
 432    match (source, target) {
 433        (Value::Object(source), Value::Object(target)) => {
 434            for (key, value) in source {
 435                if let Some(target) = target.get_mut(&key) {
 436                    merge_json_value_into(value, target);
 437                } else {
 438                    target.insert(key, value);
 439                }
 440            }
 441        }
 442
 443        (Value::Array(source), Value::Array(target)) => {
 444            for value in source {
 445                target.push(value);
 446            }
 447        }
 448
 449        (source, target) => *target = source,
 450    }
 451}
 452
 453pub fn merge_non_null_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
 454    use serde_json::Value;
 455    if let Value::Object(source_object) = source {
 456        let target_object = if let Value::Object(target) = target {
 457            target
 458        } else {
 459            *target = Value::Object(Default::default());
 460            target.as_object_mut().unwrap()
 461        };
 462        for (key, value) in source_object {
 463            if let Some(target) = target_object.get_mut(&key) {
 464                merge_non_null_json_value_into(value, target);
 465            } else if !value.is_null() {
 466                target_object.insert(key, value);
 467            }
 468        }
 469    } else if !source.is_null() {
 470        *target = source
 471    }
 472}
 473
 474pub fn expanded_and_wrapped_usize_range(
 475    range: Range<usize>,
 476    additional_before: usize,
 477    additional_after: usize,
 478    wrap_length: usize,
 479) -> impl Iterator<Item = usize> {
 480    let start_wraps = range.start < additional_before;
 481    let end_wraps = wrap_length < range.end + additional_after;
 482    if start_wraps && end_wraps {
 483        Either::Left(0..wrap_length)
 484    } else if start_wraps {
 485        let wrapped_start = (range.start + wrap_length).saturating_sub(additional_before);
 486        if wrapped_start <= range.end {
 487            Either::Left(0..wrap_length)
 488        } else {
 489            Either::Right((0..range.end + additional_after).chain(wrapped_start..wrap_length))
 490        }
 491    } else if end_wraps {
 492        let wrapped_end = range.end + additional_after - wrap_length;
 493        if range.start <= wrapped_end {
 494            Either::Left(0..wrap_length)
 495        } else {
 496            Either::Right((0..wrapped_end).chain(range.start - additional_before..wrap_length))
 497        }
 498    } else {
 499        Either::Left((range.start - additional_before)..(range.end + additional_after))
 500    }
 501}
 502
 503/// Yields `[i, i + 1, i - 1, i + 2, ..]`, each modulo `wrap_length` and bounded by
 504/// `additional_before` and `additional_after`. If the wrapping causes overlap, duplicates are not
 505/// emitted. If wrap_length is 0, nothing is yielded.
 506pub fn wrapped_usize_outward_from(
 507    start: usize,
 508    additional_before: usize,
 509    additional_after: usize,
 510    wrap_length: usize,
 511) -> impl Iterator<Item = usize> {
 512    let mut count = 0;
 513    let mut after_offset = 1;
 514    let mut before_offset = 1;
 515
 516    std::iter::from_fn(move || {
 517        count += 1;
 518        if count > wrap_length {
 519            None
 520        } else if count == 1 {
 521            Some(start % wrap_length)
 522        } else if after_offset <= additional_after && after_offset <= before_offset {
 523            let value = (start + after_offset) % wrap_length;
 524            after_offset += 1;
 525            Some(value)
 526        } else if before_offset <= additional_before {
 527            let value = (start + wrap_length - before_offset) % wrap_length;
 528            before_offset += 1;
 529            Some(value)
 530        } else if after_offset <= additional_after {
 531            let value = (start + after_offset) % wrap_length;
 532            after_offset += 1;
 533            Some(value)
 534        } else {
 535            None
 536        }
 537    })
 538}
 539
 540#[cfg(any(test, feature = "test-support"))]
 541mod rng {
 542    use rand::prelude::*;
 543
 544    pub struct RandomCharIter<T: Rng> {
 545        rng: T,
 546        simple_text: bool,
 547    }
 548
 549    impl<T: Rng> RandomCharIter<T> {
 550        pub fn new(rng: T) -> Self {
 551            Self {
 552                rng,
 553                simple_text: std::env::var("SIMPLE_TEXT").is_ok_and(|v| !v.is_empty()),
 554            }
 555        }
 556
 557        pub fn with_simple_text(mut self) -> Self {
 558            self.simple_text = true;
 559            self
 560        }
 561    }
 562
 563    impl<T: Rng> Iterator for RandomCharIter<T> {
 564        type Item = char;
 565
 566        fn next(&mut self) -> Option<Self::Item> {
 567            if self.simple_text {
 568                return if self.rng.random_range(0..100) < 5 {
 569                    Some('\n')
 570                } else {
 571                    Some(self.rng.random_range(b'a'..b'z' + 1).into())
 572                };
 573            }
 574
 575            match self.rng.random_range(0..100) {
 576                // whitespace
 577                0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
 578                // two-byte greek letters
 579                20..=32 => char::from_u32(self.rng.random_range(('Ξ±' as u32)..('Ο‰' as u32 + 1))),
 580                // // three-byte characters
 581                33..=45 => ['βœ‹', 'βœ…', '❌', '❎', '⭐']
 582                    .choose(&mut self.rng)
 583                    .copied(),
 584                // // four-byte characters
 585                46..=58 => ['🍐', 'πŸ€', 'πŸ—', 'πŸŽ‰'].choose(&mut self.rng).copied(),
 586                // ascii letters
 587                _ => Some(self.rng.random_range(b'a'..b'z' + 1).into()),
 588            }
 589        }
 590    }
 591}
 592#[cfg(any(test, feature = "test-support"))]
 593pub use rng::RandomCharIter;
 594
 595/// Get an embedded file as a string.
 596pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
 597    match A::get(path).expect(path).data {
 598        Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
 599        Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
 600    }
 601}
 602
 603pub trait RangeExt<T> {
 604    fn sorted(&self) -> Self;
 605    fn to_inclusive(&self) -> RangeInclusive<T>;
 606    fn overlaps(&self, other: &Range<T>) -> bool;
 607    fn contains_inclusive(&self, other: &Range<T>) -> bool;
 608}
 609
 610impl<T: Ord + Clone> RangeExt<T> for Range<T> {
 611    fn sorted(&self) -> Self {
 612        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
 613    }
 614
 615    fn to_inclusive(&self) -> RangeInclusive<T> {
 616        self.start.clone()..=self.end.clone()
 617    }
 618
 619    fn overlaps(&self, other: &Range<T>) -> bool {
 620        self.start < other.end && other.start < self.end
 621    }
 622
 623    fn contains_inclusive(&self, other: &Range<T>) -> bool {
 624        self.start <= other.start && other.end <= self.end
 625    }
 626}
 627
 628impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
 629    fn sorted(&self) -> Self {
 630        cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
 631    }
 632
 633    fn to_inclusive(&self) -> RangeInclusive<T> {
 634        self.clone()
 635    }
 636
 637    fn overlaps(&self, other: &Range<T>) -> bool {
 638        self.start() < &other.end && &other.start <= self.end()
 639    }
 640
 641    fn contains_inclusive(&self, other: &Range<T>) -> bool {
 642        self.start() <= &other.start && &other.end <= self.end()
 643    }
 644}
 645
 646/// A way to sort strings with starting numbers numerically first, falling back to alphanumeric one,
 647/// case-insensitive.
 648///
 649/// This is useful for turning regular alphanumerically sorted sequences as `1-abc, 10, 11-def, .., 2, 21-abc`
 650/// into `1-abc, 2, 10, 11-def, .., 21-abc`
 651#[derive(Debug, PartialEq, Eq)]
 652pub struct NumericPrefixWithSuffix<'a>(Option<u64>, &'a str);
 653
 654impl<'a> NumericPrefixWithSuffix<'a> {
 655    pub fn from_numeric_prefixed_str(str: &'a str) -> Self {
 656        let i = str.chars().take_while(|c| c.is_ascii_digit()).count();
 657        let (prefix, remainder) = str.split_at(i);
 658
 659        let prefix = prefix.parse().ok();
 660        Self(prefix, remainder)
 661    }
 662}
 663
 664/// When dealing with equality, we need to consider the case of the strings to achieve strict equality
 665/// to handle cases like "a" < "A" instead of "a" == "A".
 666impl Ord for NumericPrefixWithSuffix<'_> {
 667    fn cmp(&self, other: &Self) -> Ordering {
 668        match (self.0, other.0) {
 669            (None, None) => UniCase::new(self.1)
 670                .cmp(&UniCase::new(other.1))
 671                .then_with(|| self.1.cmp(other.1).reverse()),
 672            (None, Some(_)) => Ordering::Greater,
 673            (Some(_), None) => Ordering::Less,
 674            (Some(a), Some(b)) => a.cmp(&b).then_with(|| {
 675                UniCase::new(self.1)
 676                    .cmp(&UniCase::new(other.1))
 677                    .then_with(|| self.1.cmp(other.1).reverse())
 678            }),
 679        }
 680    }
 681}
 682
 683impl PartialOrd for NumericPrefixWithSuffix<'_> {
 684    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
 685        Some(self.cmp(other))
 686    }
 687}
 688
 689fn emoji_regex() -> &'static Regex {
 690    static EMOJI_REGEX: LazyLock<Regex> =
 691        LazyLock::new(|| Regex::new("(\\p{Emoji}|\u{200D})").unwrap());
 692    &EMOJI_REGEX
 693}
 694
 695/// Returns true if the given string consists of emojis only.
 696/// E.g. "πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘§πŸ‘‹" will return true, but "πŸ‘‹!" will return false.
 697pub fn word_consists_of_emojis(s: &str) -> bool {
 698    let mut prev_end = 0;
 699    for capture in emoji_regex().find_iter(s) {
 700        if capture.start() != prev_end {
 701            return false;
 702        }
 703        prev_end = capture.end();
 704    }
 705    prev_end == s.len()
 706}
 707
 708/// Similar to `str::split`, but also provides byte-offset ranges of the results. Unlike
 709/// `str::split`, this is not generic on pattern types and does not return an `Iterator`.
 710pub fn split_str_with_ranges<'s>(
 711    s: &'s str,
 712    pat: &dyn Fn(char) -> bool,
 713) -> Vec<(Range<usize>, &'s str)> {
 714    let mut result = Vec::new();
 715    let mut start = 0;
 716
 717    for (i, ch) in s.char_indices() {
 718        if pat(ch) {
 719            if i > start {
 720                result.push((start..i, &s[start..i]));
 721            }
 722            start = i + ch.len_utf8();
 723        }
 724    }
 725
 726    if s.len() > start {
 727        result.push((start..s.len(), &s[start..s.len()]));
 728    }
 729
 730    result
 731}
 732
 733pub fn default<D: Default>() -> D {
 734    Default::default()
 735}
 736
 737#[derive(Debug)]
 738pub enum ConnectionResult<O> {
 739    Timeout,
 740    ConnectionReset,
 741    Result(anyhow::Result<O>),
 742}
 743
 744impl<O> ConnectionResult<O> {
 745    pub fn into_response(self) -> anyhow::Result<O> {
 746        match self {
 747            ConnectionResult::Timeout => anyhow::bail!("Request timed out"),
 748            ConnectionResult::ConnectionReset => anyhow::bail!("Server reset the connection"),
 749            ConnectionResult::Result(r) => r,
 750        }
 751    }
 752}
 753
 754impl<O> From<anyhow::Result<O>> for ConnectionResult<O> {
 755    fn from(result: anyhow::Result<O>) -> Self {
 756        ConnectionResult::Result(result)
 757    }
 758}
 759
 760/// Normalizes a path by resolving `.` and `..` components without
 761/// requiring the path to exist on disk (unlike `canonicalize`).
 762pub fn normalize_path(path: &Path) -> PathBuf {
 763    use std::path::Component;
 764    let mut components = path.components().peekable();
 765    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
 766        components.next();
 767        PathBuf::from(c.as_os_str())
 768    } else {
 769        PathBuf::new()
 770    };
 771
 772    for component in components {
 773        match component {
 774            Component::Prefix(..) => unreachable!(),
 775            Component::RootDir => {
 776                ret.push(component.as_os_str());
 777            }
 778            Component::CurDir => {}
 779            Component::ParentDir => {
 780                ret.pop();
 781            }
 782            Component::Normal(c) => {
 783                ret.push(c);
 784            }
 785        }
 786    }
 787    ret
 788}
 789
 790#[cfg(test)]
 791mod tests {
 792    use super::*;
 793
 794    #[test]
 795    fn test_extend_sorted() {
 796        let mut vec = vec![];
 797
 798        extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
 799        assert_eq!(vec, &[21, 17, 13, 8, 1]);
 800
 801        extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
 802        assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
 803
 804        extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
 805        assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
 806    }
 807
 808    #[test]
 809    fn test_truncate_to_bottom_n_sorted_by() {
 810        let mut vec: Vec<u32> = vec![5, 2, 3, 4, 1];
 811        truncate_to_bottom_n_sorted_by(&mut vec, 10, &u32::cmp);
 812        assert_eq!(vec, &[1, 2, 3, 4, 5]);
 813
 814        vec = vec![5, 2, 3, 4, 1];
 815        truncate_to_bottom_n_sorted_by(&mut vec, 5, &u32::cmp);
 816        assert_eq!(vec, &[1, 2, 3, 4, 5]);
 817
 818        vec = vec![5, 2, 3, 4, 1];
 819        truncate_to_bottom_n_sorted_by(&mut vec, 4, &u32::cmp);
 820        assert_eq!(vec, &[1, 2, 3, 4]);
 821
 822        vec = vec![5, 2, 3, 4, 1];
 823        truncate_to_bottom_n_sorted_by(&mut vec, 1, &u32::cmp);
 824        assert_eq!(vec, &[1]);
 825
 826        vec = vec![5, 2, 3, 4, 1];
 827        truncate_to_bottom_n_sorted_by(&mut vec, 0, &u32::cmp);
 828        assert!(vec.is_empty());
 829    }
 830
 831    #[test]
 832    fn test_iife() {
 833        fn option_returning_function() -> Option<()> {
 834            None
 835        }
 836
 837        let foo = maybe!({
 838            option_returning_function()?;
 839            Some(())
 840        });
 841
 842        assert_eq!(foo, None);
 843    }
 844
 845    #[test]
 846    fn test_truncate_and_trailoff() {
 847        assert_eq!(truncate_and_trailoff("", 5), "");
 848        assert_eq!(truncate_and_trailoff("aaaaaa", 7), "aaaaaa");
 849        assert_eq!(truncate_and_trailoff("aaaaaa", 6), "aaaaaa");
 850        assert_eq!(truncate_and_trailoff("aaaaaa", 5), "aaaaa…");
 851        assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
 852        assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
 853        assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
 854    }
 855
 856    #[test]
 857    fn test_truncate_and_remove_front() {
 858        assert_eq!(truncate_and_remove_front("", 5), "");
 859        assert_eq!(truncate_and_remove_front("aaaaaa", 7), "aaaaaa");
 860        assert_eq!(truncate_and_remove_front("aaaaaa", 6), "aaaaaa");
 861        assert_eq!(truncate_and_remove_front("aaaaaa", 5), "…aaaaa");
 862        assert_eq!(truncate_and_remove_front("èèèèèè", 7), "èèèèèè");
 863        assert_eq!(truncate_and_remove_front("èèèèèè", 6), "èèèèèè");
 864        assert_eq!(truncate_and_remove_front("èèèèèè", 5), "…èèèèè");
 865    }
 866
 867    #[test]
 868    fn test_numeric_prefix_str_method() {
 869        let target = "1a";
 870        assert_eq!(
 871            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
 872            NumericPrefixWithSuffix(Some(1), "a")
 873        );
 874
 875        let target = "12ab";
 876        assert_eq!(
 877            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
 878            NumericPrefixWithSuffix(Some(12), "ab")
 879        );
 880
 881        let target = "12_ab";
 882        assert_eq!(
 883            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
 884            NumericPrefixWithSuffix(Some(12), "_ab")
 885        );
 886
 887        let target = "1_2ab";
 888        assert_eq!(
 889            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
 890            NumericPrefixWithSuffix(Some(1), "_2ab")
 891        );
 892
 893        let target = "1.2";
 894        assert_eq!(
 895            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
 896            NumericPrefixWithSuffix(Some(1), ".2")
 897        );
 898
 899        let target = "1.2_a";
 900        assert_eq!(
 901            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
 902            NumericPrefixWithSuffix(Some(1), ".2_a")
 903        );
 904
 905        let target = "12.2_a";
 906        assert_eq!(
 907            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
 908            NumericPrefixWithSuffix(Some(12), ".2_a")
 909        );
 910
 911        let target = "12a.2_a";
 912        assert_eq!(
 913            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
 914            NumericPrefixWithSuffix(Some(12), "a.2_a")
 915        );
 916    }
 917
 918    #[test]
 919    fn test_numeric_prefix_with_suffix() {
 920        let mut sorted = vec!["1-abc", "10", "11def", "2", "21-abc"];
 921        sorted.sort_by_key(|s| NumericPrefixWithSuffix::from_numeric_prefixed_str(s));
 922        assert_eq!(sorted, ["1-abc", "2", "10", "11def", "21-abc"]);
 923
 924        for numeric_prefix_less in ["numeric_prefix_less", "aaa", "~β„’Β£"] {
 925            assert_eq!(
 926                NumericPrefixWithSuffix::from_numeric_prefixed_str(numeric_prefix_less),
 927                NumericPrefixWithSuffix(None, numeric_prefix_less),
 928                "String without numeric prefix `{numeric_prefix_less}` should not be converted into NumericPrefixWithSuffix"
 929            )
 930        }
 931    }
 932
 933    #[test]
 934    fn test_word_consists_of_emojis() {
 935        let words_to_test = vec![
 936            ("πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘§πŸ‘‹πŸ₯’", true),
 937            ("πŸ‘‹", true),
 938            ("!πŸ‘‹", false),
 939            ("πŸ‘‹!", false),
 940            ("πŸ‘‹ ", false),
 941            (" πŸ‘‹", false),
 942            ("Test", false),
 943        ];
 944
 945        for (text, expected_result) in words_to_test {
 946            assert_eq!(word_consists_of_emojis(text), expected_result);
 947        }
 948    }
 949
 950    #[test]
 951    fn test_truncate_lines_and_trailoff() {
 952        let text = r#"Line 1
 953Line 2
 954Line 3"#;
 955
 956        assert_eq!(
 957            truncate_lines_and_trailoff(text, 2),
 958            r#"Line 1
 959…"#
 960        );
 961
 962        assert_eq!(
 963            truncate_lines_and_trailoff(text, 3),
 964            r#"Line 1
 965Line 2
 966…"#
 967        );
 968
 969        assert_eq!(
 970            truncate_lines_and_trailoff(text, 4),
 971            r#"Line 1
 972Line 2
 973Line 3"#
 974        );
 975    }
 976
 977    #[test]
 978    fn test_expanded_and_wrapped_usize_range() {
 979        // Neither wrap
 980        assert_eq!(
 981            expanded_and_wrapped_usize_range(2..4, 1, 1, 8).collect::<Vec<usize>>(),
 982            (1..5).collect::<Vec<usize>>()
 983        );
 984        // Start wraps
 985        assert_eq!(
 986            expanded_and_wrapped_usize_range(2..4, 3, 1, 8).collect::<Vec<usize>>(),
 987            ((0..5).chain(7..8)).collect::<Vec<usize>>()
 988        );
 989        // Start wraps all the way around
 990        assert_eq!(
 991            expanded_and_wrapped_usize_range(2..4, 5, 1, 8).collect::<Vec<usize>>(),
 992            (0..8).collect::<Vec<usize>>()
 993        );
 994        // Start wraps all the way around and past 0
 995        assert_eq!(
 996            expanded_and_wrapped_usize_range(2..4, 10, 1, 8).collect::<Vec<usize>>(),
 997            (0..8).collect::<Vec<usize>>()
 998        );
 999        // End wraps
1000        assert_eq!(
1001            expanded_and_wrapped_usize_range(3..5, 1, 4, 8).collect::<Vec<usize>>(),
1002            (0..1).chain(2..8).collect::<Vec<usize>>()
1003        );
1004        // End wraps all the way around
1005        assert_eq!(
1006            expanded_and_wrapped_usize_range(3..5, 1, 5, 8).collect::<Vec<usize>>(),
1007            (0..8).collect::<Vec<usize>>()
1008        );
1009        // End wraps all the way around and past the end
1010        assert_eq!(
1011            expanded_and_wrapped_usize_range(3..5, 1, 10, 8).collect::<Vec<usize>>(),
1012            (0..8).collect::<Vec<usize>>()
1013        );
1014        // Both start and end wrap
1015        assert_eq!(
1016            expanded_and_wrapped_usize_range(3..5, 4, 4, 8).collect::<Vec<usize>>(),
1017            (0..8).collect::<Vec<usize>>()
1018        );
1019    }
1020
1021    #[test]
1022    fn test_wrapped_usize_outward_from() {
1023        // No wrapping
1024        assert_eq!(
1025            wrapped_usize_outward_from(4, 2, 2, 10).collect::<Vec<usize>>(),
1026            vec![4, 5, 3, 6, 2]
1027        );
1028        // Wrapping at end
1029        assert_eq!(
1030            wrapped_usize_outward_from(8, 2, 3, 10).collect::<Vec<usize>>(),
1031            vec![8, 9, 7, 0, 6, 1]
1032        );
1033        // Wrapping at start
1034        assert_eq!(
1035            wrapped_usize_outward_from(1, 3, 2, 10).collect::<Vec<usize>>(),
1036            vec![1, 2, 0, 3, 9, 8]
1037        );
1038        // All values wrap around
1039        assert_eq!(
1040            wrapped_usize_outward_from(5, 10, 10, 8).collect::<Vec<usize>>(),
1041            vec![5, 6, 4, 7, 3, 0, 2, 1]
1042        );
1043        // None before / after
1044        assert_eq!(
1045            wrapped_usize_outward_from(3, 0, 0, 8).collect::<Vec<usize>>(),
1046            vec![3]
1047        );
1048        // Starting point already wrapped
1049        assert_eq!(
1050            wrapped_usize_outward_from(15, 2, 2, 10).collect::<Vec<usize>>(),
1051            vec![5, 6, 4, 7, 3]
1052        );
1053        // wrap_length of 0
1054        assert_eq!(
1055            wrapped_usize_outward_from(4, 2, 2, 0).collect::<Vec<usize>>(),
1056            Vec::<usize>::new()
1057        );
1058    }
1059
1060    #[test]
1061    fn test_split_with_ranges() {
1062        let input = "hi";
1063        let result = split_str_with_ranges(input, &|c| c == ' ');
1064
1065        assert_eq!(result.len(), 1);
1066        assert_eq!(result[0], (0..2, "hi"));
1067
1068        let input = "hΓ©lloπŸ¦€world";
1069        let result = split_str_with_ranges(input, &|c| c == 'πŸ¦€');
1070
1071        assert_eq!(result.len(), 2);
1072        assert_eq!(result[0], (0..6, "hΓ©llo")); // 'Γ©' is 2 bytes
1073        assert_eq!(result[1], (10..15, "world")); // 'πŸ¦€' is 4 bytes
1074    }
1075}