util.rs

   1pub mod arc_cow;
   2pub mod archive;
   3pub mod command;
   4pub mod fs;
   5pub mod markdown;
   6pub mod paths;
   7pub mod redact;
   8pub mod serde;
   9pub mod shell_env;
  10pub mod size;
  11#[cfg(any(test, feature = "test-support"))]
  12pub mod test;
  13pub mod time;
  14
  15use anyhow::Result;
  16use futures::Future;
  17use itertools::Either;
  18use regex::Regex;
  19use std::sync::{LazyLock, OnceLock};
  20use std::{
  21    borrow::Cow,
  22    cmp::{self, Ordering},
  23    env,
  24    ops::{AddAssign, Range, RangeInclusive},
  25    panic::Location,
  26    pin::Pin,
  27    task::{Context, Poll},
  28    time::Instant,
  29};
  30use unicase::UniCase;
  31
  32pub use take_until::*;
  33#[cfg(any(test, feature = "test-support"))]
  34pub use util_macros::{line_endings, path, uri};
  35
  36#[macro_export]
  37macro_rules! debug_panic {
  38    ( $($fmt_arg:tt)* ) => {
  39        if cfg!(debug_assertions) {
  40            panic!( $($fmt_arg)* );
  41        } else {
  42            let backtrace = std::backtrace::Backtrace::capture();
  43            log::error!("{}\n{:?}", format_args!($($fmt_arg)*), backtrace);
  44        }
  45    };
  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) {
 131            if s.as_bytes()[i] == b'\n' {
 132                // Since the i-th character is \n, valid to slice at i + 1.
 133                return &s[..i + 1];
 134            }
 135        }
 136    }
 137
 138    truncate_to_byte_limit(s, max_bytes)
 139}
 140
 141#[test]
 142fn test_truncate_lines_to_byte_limit() {
 143    let text = "Line 1\nLine 2\nLine 3\nLine 4";
 144
 145    // Limit that includes all lines
 146    assert_eq!(truncate_lines_to_byte_limit(text, 100), text);
 147
 148    // Exactly the first line
 149    assert_eq!(truncate_lines_to_byte_limit(text, 7), "Line 1\n");
 150
 151    // Limit between lines
 152    assert_eq!(truncate_lines_to_byte_limit(text, 13), "Line 1\n");
 153    assert_eq!(truncate_lines_to_byte_limit(text, 20), "Line 1\nLine 2\n");
 154
 155    // Limit before first newline
 156    assert_eq!(truncate_lines_to_byte_limit(text, 6), "Line ");
 157
 158    // Test with non-ASCII characters
 159    let text_utf8 = "Line 1\nLΓ­ne 2\nLine 3";
 160    assert_eq!(
 161        truncate_lines_to_byte_limit(text_utf8, 15),
 162        "Line 1\nLΓ­ne 2\n"
 163    );
 164}
 165
 166pub fn post_inc<T: From<u8> + AddAssign<T> + Copy>(value: &mut T) -> T {
 167    let prev = *value;
 168    *value += T::from(1);
 169    prev
 170}
 171
 172/// Extend a sorted vector with a sorted sequence of items, maintaining the vector's sort order and
 173/// enforcing a maximum length. This also de-duplicates items. Sort the items according to the given callback. Before calling this,
 174/// both `vec` and `new_items` should already be sorted according to the `cmp` comparator.
 175pub fn extend_sorted<T, I, F>(vec: &mut Vec<T>, new_items: I, limit: usize, mut cmp: F)
 176where
 177    I: IntoIterator<Item = T>,
 178    F: FnMut(&T, &T) -> Ordering,
 179{
 180    let mut start_index = 0;
 181    for new_item in new_items {
 182        if let Err(i) = vec[start_index..].binary_search_by(|m| cmp(m, &new_item)) {
 183            let index = start_index + i;
 184            if vec.len() < limit {
 185                vec.insert(index, new_item);
 186            } else if index < vec.len() {
 187                vec.pop();
 188                vec.insert(index, new_item);
 189            }
 190            start_index = index;
 191        }
 192    }
 193}
 194
 195pub fn truncate_to_bottom_n_sorted_by<T, F>(items: &mut Vec<T>, limit: usize, compare: &F)
 196where
 197    F: Fn(&T, &T) -> Ordering,
 198{
 199    if limit == 0 {
 200        items.truncate(0);
 201    }
 202    if items.len() <= limit {
 203        items.sort_by(compare);
 204        return;
 205    }
 206    // When limit is near to items.len() it may be more efficient to sort the whole list and
 207    // truncate, rather than always doing selection first as is done below. It's hard to analyze
 208    // where the threshold for this should be since the quickselect style algorithm used by
 209    // `select_nth_unstable_by` makes the prefix partially sorted, and so its work is not wasted -
 210    // the expected number of comparisons needed by `sort_by` is less than it is for some arbitrary
 211    // unsorted input.
 212    items.select_nth_unstable_by(limit, compare);
 213    items.truncate(limit);
 214    items.sort_by(compare);
 215}
 216
 217/// Prevents execution of the application with root privileges on Unix systems.
 218///
 219/// This function checks if the current process is running with root privileges
 220/// and terminates the program with an error message unless explicitly allowed via the
 221/// `ZED_ALLOW_ROOT` environment variable.
 222#[cfg(unix)]
 223pub fn prevent_root_execution() {
 224    let is_root = nix::unistd::geteuid().is_root();
 225    let allow_root = std::env::var("ZED_ALLOW_ROOT").is_ok_and(|val| val == "true");
 226
 227    if is_root && !allow_root {
 228        eprintln!(
 229            "\
 230Error: Running Zed as root or via sudo is unsupported.
 231       Doing so (even once) may subtly break things for all subsequent non-root usage of Zed.
 232       It is untested and not recommended, don't complain when things break.
 233       If you wish to proceed anyways, set `ZED_ALLOW_ROOT=true` in your environment."
 234        );
 235        std::process::exit(1);
 236    }
 237}
 238
 239#[cfg(unix)]
 240fn load_shell_from_passwd() -> Result<()> {
 241    let buflen = match unsafe { libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) } {
 242        n if n < 0 => 1024,
 243        n => n as usize,
 244    };
 245    let mut buffer = Vec::with_capacity(buflen);
 246
 247    let mut pwd: std::mem::MaybeUninit<libc::passwd> = std::mem::MaybeUninit::uninit();
 248    let mut result: *mut libc::passwd = std::ptr::null_mut();
 249
 250    let uid = unsafe { libc::getuid() };
 251    let status = unsafe {
 252        libc::getpwuid_r(
 253            uid,
 254            pwd.as_mut_ptr(),
 255            buffer.as_mut_ptr() as *mut libc::c_char,
 256            buflen,
 257            &mut result,
 258        )
 259    };
 260    let entry = unsafe { pwd.assume_init() };
 261
 262    anyhow::ensure!(
 263        status == 0,
 264        "call to getpwuid_r failed. uid: {}, status: {}",
 265        uid,
 266        status
 267    );
 268    anyhow::ensure!(!result.is_null(), "passwd entry for uid {} not found", uid);
 269    anyhow::ensure!(
 270        entry.pw_uid == uid,
 271        "passwd entry has different uid ({}) than getuid ({}) returned",
 272        entry.pw_uid,
 273        uid,
 274    );
 275
 276    let shell = unsafe { std::ffi::CStr::from_ptr(entry.pw_shell).to_str().unwrap() };
 277    if env::var("SHELL").map_or(true, |shell_env| shell_env != shell) {
 278        log::info!(
 279            "updating SHELL environment variable to value from passwd entry: {:?}",
 280            shell,
 281        );
 282        unsafe { env::set_var("SHELL", shell) };
 283    }
 284
 285    Ok(())
 286}
 287
 288#[cfg(unix)]
 289/// Returns a shell escaped path for the current zed executable
 290pub fn get_shell_safe_zed_path() -> anyhow::Result<String> {
 291    use anyhow::Context;
 292
 293    let zed_path = std::env::current_exe()
 294        .context("Failed to determine current zed executable path.")?
 295        .to_string_lossy()
 296        .trim_end_matches(" (deleted)") // see https://github.com/rust-lang/rust/issues/69343
 297        .to_string();
 298
 299    // As of writing, this can only be fail if the path contains a null byte, which shouldn't be possible
 300    // but shlex has annotated the error as #[non_exhaustive] so we can't make it a compile error if other
 301    // errors are introduced in the future :(
 302    let zed_path_escaped =
 303        shlex::try_quote(&zed_path).context("Failed to shell-escape Zed executable path.")?;
 304
 305    return Ok(zed_path_escaped.to_string());
 306}
 307
 308#[cfg(unix)]
 309pub fn load_login_shell_environment() -> Result<()> {
 310    load_shell_from_passwd().log_err();
 311
 312    // If possible, we want to `cd` in the user's `$HOME` to trigger programs
 313    // such as direnv, asdf, mise, ... to adjust the PATH. These tools often hook
 314    // into shell's `cd` command (and hooks) to manipulate env.
 315    // We do this so that we get the env a user would have when spawning a shell
 316    // in home directory.
 317    for (name, value) in shell_env::capture(paths::home_dir())? {
 318        unsafe { env::set_var(&name, &value) };
 319    }
 320
 321    log::info!(
 322        "set environment variables from shell:{}, path:{}",
 323        std::env::var("SHELL").unwrap_or_default(),
 324        std::env::var("PATH").unwrap_or_default(),
 325    );
 326
 327    Ok(())
 328}
 329
 330/// Configures the process to start a new session, to prevent interactive shells from taking control
 331/// of the terminal.
 332///
 333/// For more details: https://registerspill.thorstenball.com/p/how-to-lose-control-of-your-shell
 334pub fn set_pre_exec_to_start_new_session(
 335    command: &mut std::process::Command,
 336) -> &mut std::process::Command {
 337    // safety: code in pre_exec should be signal safe.
 338    // https://man7.org/linux/man-pages/man7/signal-safety.7.html
 339    #[cfg(not(target_os = "windows"))]
 340    unsafe {
 341        use std::os::unix::process::CommandExt;
 342        command.pre_exec(|| {
 343            libc::setsid();
 344            Ok(())
 345        });
 346    };
 347    command
 348}
 349
 350pub fn merge_json_lenient_value_into(
 351    source: serde_json_lenient::Value,
 352    target: &mut serde_json_lenient::Value,
 353) {
 354    match (source, target) {
 355        (serde_json_lenient::Value::Object(source), serde_json_lenient::Value::Object(target)) => {
 356            for (key, value) in source {
 357                if let Some(target) = target.get_mut(&key) {
 358                    merge_json_lenient_value_into(value, target);
 359                } else {
 360                    target.insert(key, value);
 361                }
 362            }
 363        }
 364
 365        (serde_json_lenient::Value::Array(source), serde_json_lenient::Value::Array(target)) => {
 366            for value in source {
 367                target.push(value);
 368            }
 369        }
 370
 371        (source, target) => *target = source,
 372    }
 373}
 374
 375pub fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
 376    use serde_json::Value;
 377
 378    match (source, target) {
 379        (Value::Object(source), Value::Object(target)) => {
 380            for (key, value) in source {
 381                if let Some(target) = target.get_mut(&key) {
 382                    merge_json_value_into(value, target);
 383                } else {
 384                    target.insert(key, value);
 385                }
 386            }
 387        }
 388
 389        (Value::Array(source), Value::Array(target)) => {
 390            for value in source {
 391                target.push(value);
 392            }
 393        }
 394
 395        (source, target) => *target = source,
 396    }
 397}
 398
 399pub fn merge_non_null_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
 400    use serde_json::Value;
 401    if let Value::Object(source_object) = source {
 402        let target_object = if let Value::Object(target) = target {
 403            target
 404        } else {
 405            *target = Value::Object(Default::default());
 406            target.as_object_mut().unwrap()
 407        };
 408        for (key, value) in source_object {
 409            if let Some(target) = target_object.get_mut(&key) {
 410                merge_non_null_json_value_into(value, target);
 411            } else if !value.is_null() {
 412                target_object.insert(key, value);
 413            }
 414        }
 415    } else if !source.is_null() {
 416        *target = source
 417    }
 418}
 419
 420pub fn measure<R>(label: &str, f: impl FnOnce() -> R) -> R {
 421    static ZED_MEASUREMENTS: OnceLock<bool> = OnceLock::new();
 422    let zed_measurements = ZED_MEASUREMENTS.get_or_init(|| {
 423        env::var("ZED_MEASUREMENTS")
 424            .map(|measurements| measurements == "1" || measurements == "true")
 425            .unwrap_or(false)
 426    });
 427
 428    if *zed_measurements {
 429        let start = Instant::now();
 430        let result = f();
 431        let elapsed = start.elapsed();
 432        eprintln!("{}: {:?}", label, elapsed);
 433        result
 434    } else {
 435        f()
 436    }
 437}
 438
 439pub fn expanded_and_wrapped_usize_range(
 440    range: Range<usize>,
 441    additional_before: usize,
 442    additional_after: usize,
 443    wrap_length: usize,
 444) -> impl Iterator<Item = usize> {
 445    let start_wraps = range.start < additional_before;
 446    let end_wraps = wrap_length < range.end + additional_after;
 447    if start_wraps && end_wraps {
 448        Either::Left(0..wrap_length)
 449    } else if start_wraps {
 450        let wrapped_start = (range.start + wrap_length).saturating_sub(additional_before);
 451        if wrapped_start <= range.end {
 452            Either::Left(0..wrap_length)
 453        } else {
 454            Either::Right((0..range.end + additional_after).chain(wrapped_start..wrap_length))
 455        }
 456    } else if end_wraps {
 457        let wrapped_end = range.end + additional_after - wrap_length;
 458        if range.start <= wrapped_end {
 459            Either::Left(0..wrap_length)
 460        } else {
 461            Either::Right((0..wrapped_end).chain(range.start - additional_before..wrap_length))
 462        }
 463    } else {
 464        Either::Left((range.start - additional_before)..(range.end + additional_after))
 465    }
 466}
 467
 468/// Yields `[i, i + 1, i - 1, i + 2, ..]`, each modulo `wrap_length` and bounded by
 469/// `additional_before` and `additional_after`. If the wrapping causes overlap, duplicates are not
 470/// emitted. If wrap_length is 0, nothing is yielded.
 471pub fn wrapped_usize_outward_from(
 472    start: usize,
 473    additional_before: usize,
 474    additional_after: usize,
 475    wrap_length: usize,
 476) -> impl Iterator<Item = usize> {
 477    let mut count = 0;
 478    let mut after_offset = 1;
 479    let mut before_offset = 1;
 480
 481    std::iter::from_fn(move || {
 482        count += 1;
 483        if count > wrap_length {
 484            None
 485        } else if count == 1 {
 486            Some(start % wrap_length)
 487        } else if after_offset <= additional_after && after_offset <= before_offset {
 488            let value = (start + after_offset) % wrap_length;
 489            after_offset += 1;
 490            Some(value)
 491        } else if before_offset <= additional_before {
 492            let value = (start + wrap_length - before_offset) % wrap_length;
 493            before_offset += 1;
 494            Some(value)
 495        } else if after_offset <= additional_after {
 496            let value = (start + after_offset) % wrap_length;
 497            after_offset += 1;
 498            Some(value)
 499        } else {
 500            None
 501        }
 502    })
 503}
 504
 505#[cfg(target_os = "windows")]
 506pub fn get_windows_system_shell() -> String {
 507    use std::path::PathBuf;
 508
 509    fn find_pwsh_in_programfiles(find_alternate: bool, find_preview: bool) -> Option<PathBuf> {
 510        #[cfg(target_pointer_width = "64")]
 511        let env_var = if find_alternate {
 512            "ProgramFiles(x86)"
 513        } else {
 514            "ProgramFiles"
 515        };
 516
 517        #[cfg(target_pointer_width = "32")]
 518        let env_var = if find_alternate {
 519            "ProgramW6432"
 520        } else {
 521            "ProgramFiles"
 522        };
 523
 524        let install_base_dir = PathBuf::from(std::env::var_os(env_var)?).join("PowerShell");
 525        install_base_dir
 526            .read_dir()
 527            .ok()?
 528            .filter_map(Result::ok)
 529            .filter(|entry| matches!(entry.file_type(), Ok(ft) if ft.is_dir()))
 530            .filter_map(|entry| {
 531                let dir_name = entry.file_name();
 532                let dir_name = dir_name.to_string_lossy();
 533
 534                let version = if find_preview {
 535                    let dash_index = dir_name.find('-')?;
 536                    if &dir_name[dash_index + 1..] != "preview" {
 537                        return None;
 538                    };
 539                    dir_name[..dash_index].parse::<u32>().ok()?
 540                } else {
 541                    dir_name.parse::<u32>().ok()?
 542                };
 543
 544                let exe_path = entry.path().join("pwsh.exe");
 545                if exe_path.exists() {
 546                    Some((version, exe_path))
 547                } else {
 548                    None
 549                }
 550            })
 551            .max_by_key(|(version, _)| *version)
 552            .map(|(_, path)| path)
 553    }
 554
 555    fn find_pwsh_in_msix(find_preview: bool) -> Option<PathBuf> {
 556        let msix_app_dir =
 557            PathBuf::from(std::env::var_os("LOCALAPPDATA")?).join("Microsoft\\WindowsApps");
 558        if !msix_app_dir.exists() {
 559            return None;
 560        }
 561
 562        let prefix = if find_preview {
 563            "Microsoft.PowerShellPreview_"
 564        } else {
 565            "Microsoft.PowerShell_"
 566        };
 567        msix_app_dir
 568            .read_dir()
 569            .ok()?
 570            .filter_map(|entry| {
 571                let entry = entry.ok()?;
 572                if !matches!(entry.file_type(), Ok(ft) if ft.is_dir()) {
 573                    return None;
 574                }
 575
 576                if !entry.file_name().to_string_lossy().starts_with(prefix) {
 577                    return None;
 578                }
 579
 580                let exe_path = entry.path().join("pwsh.exe");
 581                exe_path.exists().then_some(exe_path)
 582            })
 583            .next()
 584    }
 585
 586    fn find_pwsh_in_scoop() -> Option<PathBuf> {
 587        let pwsh_exe =
 588            PathBuf::from(std::env::var_os("USERPROFILE")?).join("scoop\\shims\\pwsh.exe");
 589        pwsh_exe.exists().then_some(pwsh_exe)
 590    }
 591
 592    static SYSTEM_SHELL: LazyLock<String> = LazyLock::new(|| {
 593        find_pwsh_in_programfiles(false, false)
 594            .or_else(|| find_pwsh_in_programfiles(true, false))
 595            .or_else(|| find_pwsh_in_msix(false))
 596            .or_else(|| find_pwsh_in_programfiles(false, true))
 597            .or_else(|| find_pwsh_in_msix(true))
 598            .or_else(|| find_pwsh_in_programfiles(true, true))
 599            .or_else(find_pwsh_in_scoop)
 600            .map(|p| p.to_string_lossy().to_string())
 601            .unwrap_or("powershell.exe".to_string())
 602    });
 603
 604    (*SYSTEM_SHELL).clone()
 605}
 606
 607pub trait ResultExt<E> {
 608    type Ok;
 609
 610    fn log_err(self) -> Option<Self::Ok>;
 611    /// Assert that this result should never be an error in development or tests.
 612    fn debug_assert_ok(self, reason: &str) -> Self;
 613    fn warn_on_err(self) -> Option<Self::Ok>;
 614    fn log_with_level(self, level: log::Level) -> Option<Self::Ok>;
 615    fn anyhow(self) -> anyhow::Result<Self::Ok>
 616    where
 617        E: Into<anyhow::Error>;
 618}
 619
 620impl<T, E> ResultExt<E> for Result<T, E>
 621where
 622    E: std::fmt::Debug,
 623{
 624    type Ok = T;
 625
 626    #[track_caller]
 627    fn log_err(self) -> Option<T> {
 628        self.log_with_level(log::Level::Error)
 629    }
 630
 631    #[track_caller]
 632    fn debug_assert_ok(self, reason: &str) -> Self {
 633        if let Err(error) = &self {
 634            debug_panic!("{reason} - {error:?}");
 635        }
 636        self
 637    }
 638
 639    #[track_caller]
 640    fn warn_on_err(self) -> Option<T> {
 641        self.log_with_level(log::Level::Warn)
 642    }
 643
 644    #[track_caller]
 645    fn log_with_level(self, level: log::Level) -> Option<T> {
 646        match self {
 647            Ok(value) => Some(value),
 648            Err(error) => {
 649                log_error_with_caller(*Location::caller(), error, level);
 650                None
 651            }
 652        }
 653    }
 654
 655    fn anyhow(self) -> anyhow::Result<T>
 656    where
 657        E: Into<anyhow::Error>,
 658    {
 659        self.map_err(Into::into)
 660    }
 661}
 662
 663fn log_error_with_caller<E>(caller: core::panic::Location<'_>, error: E, level: log::Level)
 664where
 665    E: std::fmt::Debug,
 666{
 667    #[cfg(not(target_os = "windows"))]
 668    let file = caller.file();
 669    #[cfg(target_os = "windows")]
 670    let file = caller.file().replace('\\', "/");
 671    // In this codebase, the first segment of the file path is
 672    // the 'crates' folder, followed by the crate name.
 673    let target = file.split('/').nth(1);
 674
 675    log::logger().log(
 676        &log::Record::builder()
 677            .target(target.unwrap_or(""))
 678            .module_path(target)
 679            .args(format_args!("{:?}", error))
 680            .file(Some(caller.file()))
 681            .line(Some(caller.line()))
 682            .level(level)
 683            .build(),
 684    );
 685}
 686
 687pub fn log_err<E: std::fmt::Debug>(error: &E) {
 688    log_error_with_caller(*Location::caller(), error, log::Level::Warn);
 689}
 690
 691pub trait TryFutureExt {
 692    fn log_err(self) -> LogErrorFuture<Self>
 693    where
 694        Self: Sized;
 695
 696    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
 697    where
 698        Self: Sized;
 699
 700    fn warn_on_err(self) -> LogErrorFuture<Self>
 701    where
 702        Self: Sized;
 703    fn unwrap(self) -> UnwrapFuture<Self>
 704    where
 705        Self: Sized;
 706}
 707
 708impl<F, T, E> TryFutureExt for F
 709where
 710    F: Future<Output = Result<T, E>>,
 711    E: std::fmt::Debug,
 712{
 713    #[track_caller]
 714    fn log_err(self) -> LogErrorFuture<Self>
 715    where
 716        Self: Sized,
 717    {
 718        let location = Location::caller();
 719        LogErrorFuture(self, log::Level::Error, *location)
 720    }
 721
 722    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
 723    where
 724        Self: Sized,
 725    {
 726        LogErrorFuture(self, log::Level::Error, location)
 727    }
 728
 729    #[track_caller]
 730    fn warn_on_err(self) -> LogErrorFuture<Self>
 731    where
 732        Self: Sized,
 733    {
 734        let location = Location::caller();
 735        LogErrorFuture(self, log::Level::Warn, *location)
 736    }
 737
 738    fn unwrap(self) -> UnwrapFuture<Self>
 739    where
 740        Self: Sized,
 741    {
 742        UnwrapFuture(self)
 743    }
 744}
 745
 746#[must_use]
 747pub struct LogErrorFuture<F>(F, log::Level, core::panic::Location<'static>);
 748
 749impl<F, T, E> Future for LogErrorFuture<F>
 750where
 751    F: Future<Output = Result<T, E>>,
 752    E: std::fmt::Debug,
 753{
 754    type Output = Option<T>;
 755
 756    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
 757        let level = self.1;
 758        let location = self.2;
 759        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
 760        match inner.poll(cx) {
 761            Poll::Ready(output) => Poll::Ready(match output {
 762                Ok(output) => Some(output),
 763                Err(error) => {
 764                    log_error_with_caller(location, error, level);
 765                    None
 766                }
 767            }),
 768            Poll::Pending => Poll::Pending,
 769        }
 770    }
 771}
 772
 773pub struct UnwrapFuture<F>(F);
 774
 775impl<F, T, E> Future for UnwrapFuture<F>
 776where
 777    F: Future<Output = Result<T, E>>,
 778    E: std::fmt::Debug,
 779{
 780    type Output = T;
 781
 782    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
 783        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
 784        match inner.poll(cx) {
 785            Poll::Ready(result) => Poll::Ready(result.unwrap()),
 786            Poll::Pending => Poll::Pending,
 787        }
 788    }
 789}
 790
 791pub struct Deferred<F: FnOnce()>(Option<F>);
 792
 793impl<F: FnOnce()> Deferred<F> {
 794    /// Drop without running the deferred function.
 795    pub fn abort(mut self) {
 796        self.0.take();
 797    }
 798}
 799
 800impl<F: FnOnce()> Drop for Deferred<F> {
 801    fn drop(&mut self) {
 802        if let Some(f) = self.0.take() {
 803            f()
 804        }
 805    }
 806}
 807
 808/// Run the given function when the returned value is dropped (unless it's cancelled).
 809#[must_use]
 810pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
 811    Deferred(Some(f))
 812}
 813
 814#[cfg(any(test, feature = "test-support"))]
 815mod rng {
 816    use rand::{Rng, seq::SliceRandom};
 817    pub struct RandomCharIter<T: Rng> {
 818        rng: T,
 819        simple_text: bool,
 820    }
 821
 822    impl<T: Rng> RandomCharIter<T> {
 823        pub fn new(rng: T) -> Self {
 824            Self {
 825                rng,
 826                simple_text: std::env::var("SIMPLE_TEXT").map_or(false, |v| !v.is_empty()),
 827            }
 828        }
 829
 830        pub fn with_simple_text(mut self) -> Self {
 831            self.simple_text = true;
 832            self
 833        }
 834    }
 835
 836    impl<T: Rng> Iterator for RandomCharIter<T> {
 837        type Item = char;
 838
 839        fn next(&mut self) -> Option<Self::Item> {
 840            if self.simple_text {
 841                return if self.rng.gen_range(0..100) < 5 {
 842                    Some('\n')
 843                } else {
 844                    Some(self.rng.gen_range(b'a'..b'z' + 1).into())
 845                };
 846            }
 847
 848            match self.rng.gen_range(0..100) {
 849                // whitespace
 850                0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
 851                // two-byte greek letters
 852                20..=32 => char::from_u32(self.rng.gen_range(('Ξ±' as u32)..('Ο‰' as u32 + 1))),
 853                // // three-byte characters
 854                33..=45 => ['βœ‹', 'βœ…', '❌', '❎', '⭐']
 855                    .choose(&mut self.rng)
 856                    .copied(),
 857                // // four-byte characters
 858                46..=58 => ['🍐', 'πŸ€', 'πŸ—', 'πŸŽ‰'].choose(&mut self.rng).copied(),
 859                // ascii letters
 860                _ => Some(self.rng.gen_range(b'a'..b'z' + 1).into()),
 861            }
 862        }
 863    }
 864}
 865#[cfg(any(test, feature = "test-support"))]
 866pub use rng::RandomCharIter;
 867
 868/// Get an embedded file as a string.
 869pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
 870    match A::get(path).expect(path).data {
 871        Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
 872        Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
 873    }
 874}
 875
 876/// Expands to an immediately-invoked function expression. Good for using the ? operator
 877/// in functions which do not return an Option or Result.
 878///
 879/// Accepts a normal block, an async block, or an async move block.
 880#[macro_export]
 881macro_rules! maybe {
 882    ($block:block) => {
 883        (|| $block)()
 884    };
 885    (async $block:block) => {
 886        (|| async $block)()
 887    };
 888    (async move $block:block) => {
 889        (|| async move $block)()
 890    };
 891}
 892
 893pub trait RangeExt<T> {
 894    fn sorted(&self) -> Self;
 895    fn to_inclusive(&self) -> RangeInclusive<T>;
 896    fn overlaps(&self, other: &Range<T>) -> bool;
 897    fn contains_inclusive(&self, other: &Range<T>) -> bool;
 898}
 899
 900impl<T: Ord + Clone> RangeExt<T> for Range<T> {
 901    fn sorted(&self) -> Self {
 902        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
 903    }
 904
 905    fn to_inclusive(&self) -> RangeInclusive<T> {
 906        self.start.clone()..=self.end.clone()
 907    }
 908
 909    fn overlaps(&self, other: &Range<T>) -> bool {
 910        self.start < other.end && other.start < self.end
 911    }
 912
 913    fn contains_inclusive(&self, other: &Range<T>) -> bool {
 914        self.start <= other.start && other.end <= self.end
 915    }
 916}
 917
 918impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
 919    fn sorted(&self) -> Self {
 920        cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
 921    }
 922
 923    fn to_inclusive(&self) -> RangeInclusive<T> {
 924        self.clone()
 925    }
 926
 927    fn overlaps(&self, other: &Range<T>) -> bool {
 928        self.start() < &other.end && &other.start <= self.end()
 929    }
 930
 931    fn contains_inclusive(&self, other: &Range<T>) -> bool {
 932        self.start() <= &other.start && &other.end <= self.end()
 933    }
 934}
 935
 936/// A way to sort strings with starting numbers numerically first, falling back to alphanumeric one,
 937/// case-insensitive.
 938///
 939/// This is useful for turning regular alphanumerically sorted sequences as `1-abc, 10, 11-def, .., 2, 21-abc`
 940/// into `1-abc, 2, 10, 11-def, .., 21-abc`
 941#[derive(Debug, PartialEq, Eq)]
 942pub struct NumericPrefixWithSuffix<'a>(Option<u64>, &'a str);
 943
 944impl<'a> NumericPrefixWithSuffix<'a> {
 945    pub fn from_numeric_prefixed_str(str: &'a str) -> Self {
 946        let i = str.chars().take_while(|c| c.is_ascii_digit()).count();
 947        let (prefix, remainder) = str.split_at(i);
 948
 949        let prefix = prefix.parse().ok();
 950        Self(prefix, remainder)
 951    }
 952}
 953
 954/// When dealing with equality, we need to consider the case of the strings to achieve strict equality
 955/// to handle cases like "a" < "A" instead of "a" == "A".
 956impl Ord for NumericPrefixWithSuffix<'_> {
 957    fn cmp(&self, other: &Self) -> Ordering {
 958        match (self.0, other.0) {
 959            (None, None) => UniCase::new(self.1)
 960                .cmp(&UniCase::new(other.1))
 961                .then_with(|| self.1.cmp(other.1).reverse()),
 962            (None, Some(_)) => Ordering::Greater,
 963            (Some(_), None) => Ordering::Less,
 964            (Some(a), Some(b)) => a.cmp(&b).then_with(|| {
 965                UniCase::new(self.1)
 966                    .cmp(&UniCase::new(other.1))
 967                    .then_with(|| self.1.cmp(other.1).reverse())
 968            }),
 969        }
 970    }
 971}
 972
 973impl PartialOrd for NumericPrefixWithSuffix<'_> {
 974    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
 975        Some(self.cmp(other))
 976    }
 977}
 978
 979/// Capitalizes the first character of a string.
 980///
 981/// This function takes a string slice as input and returns a new `String` with the first character
 982/// capitalized.
 983///
 984/// # Examples
 985///
 986/// ```
 987/// use util::capitalize;
 988///
 989/// assert_eq!(capitalize("hello"), "Hello");
 990/// assert_eq!(capitalize("WORLD"), "WORLD");
 991/// assert_eq!(capitalize(""), "");
 992/// ```
 993pub fn capitalize(str: &str) -> String {
 994    let mut chars = str.chars();
 995    match chars.next() {
 996        None => String::new(),
 997        Some(first_char) => first_char.to_uppercase().collect::<String>() + chars.as_str(),
 998    }
 999}
1000
1001fn emoji_regex() -> &'static Regex {
1002    static EMOJI_REGEX: LazyLock<Regex> =
1003        LazyLock::new(|| Regex::new("(\\p{Emoji}|\u{200D})").unwrap());
1004    &EMOJI_REGEX
1005}
1006
1007/// Returns true if the given string consists of emojis only.
1008/// E.g. "πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘§πŸ‘‹" will return true, but "πŸ‘‹!" will return false.
1009pub fn word_consists_of_emojis(s: &str) -> bool {
1010    let mut prev_end = 0;
1011    for capture in emoji_regex().find_iter(s) {
1012        if capture.start() != prev_end {
1013            return false;
1014        }
1015        prev_end = capture.end();
1016    }
1017    prev_end == s.len()
1018}
1019
1020/// Similar to `str::split`, but also provides byte-offset ranges of the results. Unlike
1021/// `str::split`, this is not generic on pattern types and does not return an `Iterator`.
1022pub fn split_str_with_ranges(s: &str, pat: impl Fn(char) -> bool) -> Vec<(Range<usize>, &str)> {
1023    let mut result = Vec::new();
1024    let mut start = 0;
1025
1026    for (i, ch) in s.char_indices() {
1027        if pat(ch) {
1028            if i > start {
1029                result.push((start..i, &s[start..i]));
1030            }
1031            start = i + ch.len_utf8();
1032        }
1033    }
1034
1035    if s.len() > start {
1036        result.push((start..s.len(), &s[start..s.len()]));
1037    }
1038
1039    result
1040}
1041
1042pub fn default<D: Default>() -> D {
1043    Default::default()
1044}
1045
1046pub fn get_system_shell() -> String {
1047    #[cfg(target_os = "windows")]
1048    {
1049        get_windows_system_shell()
1050    }
1051
1052    #[cfg(not(target_os = "windows"))]
1053    {
1054        std::env::var("SHELL").unwrap_or("/bin/sh".to_string())
1055    }
1056}
1057
1058#[derive(Debug)]
1059pub enum ConnectionResult<O> {
1060    Timeout,
1061    ConnectionReset,
1062    Result(anyhow::Result<O>),
1063}
1064
1065impl<O> ConnectionResult<O> {
1066    pub fn into_response(self) -> anyhow::Result<O> {
1067        match self {
1068            ConnectionResult::Timeout => anyhow::bail!("Request timed out"),
1069            ConnectionResult::ConnectionReset => anyhow::bail!("Server reset the connection"),
1070            ConnectionResult::Result(r) => r,
1071        }
1072    }
1073}
1074
1075impl<O> From<anyhow::Result<O>> for ConnectionResult<O> {
1076    fn from(result: anyhow::Result<O>) -> Self {
1077        ConnectionResult::Result(result)
1078    }
1079}
1080
1081#[cfg(test)]
1082mod tests {
1083    use super::*;
1084
1085    #[test]
1086    fn test_extend_sorted() {
1087        let mut vec = vec![];
1088
1089        extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
1090        assert_eq!(vec, &[21, 17, 13, 8, 1]);
1091
1092        extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
1093        assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
1094
1095        extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
1096        assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
1097    }
1098
1099    #[test]
1100    fn test_get_shell_safe_zed_path_with_spaces() {
1101        // Test that shlex::try_quote handles paths with spaces correctly
1102        let path_with_spaces = "/Applications/Zed Nightly.app/Contents/MacOS/zed";
1103        let quoted = shlex::try_quote(path_with_spaces).unwrap();
1104
1105        // The quoted path should be properly escaped for shell use
1106        assert!(quoted.contains(path_with_spaces));
1107
1108        // When used in a shell command, it should not be split at spaces
1109        let command = format!("sh -c '{} --printenv'", quoted);
1110        println!("Command would be: {}", command);
1111
1112        // Test that shlex can parse it back correctly
1113        let parsed = shlex::split(&format!("{} --printenv", quoted)).unwrap();
1114        assert_eq!(parsed.len(), 2);
1115        assert_eq!(parsed[0], path_with_spaces);
1116        assert_eq!(parsed[1], "--printenv");
1117    }
1118
1119    #[test]
1120    fn test_shell_command_construction_with_quoted_path() {
1121        // Test the specific pattern used in shell_env.rs to ensure proper quoting
1122        let path_with_spaces = "/Applications/Zed Nightly.app/Contents/MacOS/zed";
1123        let quoted_path = shlex::try_quote(path_with_spaces).unwrap();
1124
1125        // This should be: '/Applications/Zed Nightly.app/Contents/MacOS/zed'
1126        assert_eq!(
1127            quoted_path,
1128            "'/Applications/Zed Nightly.app/Contents/MacOS/zed'"
1129        );
1130
1131        // Test the command construction pattern from shell_env.rs
1132        // The fixed version should use double quotes around the entire sh -c argument
1133        let env_fd = 0;
1134        let command = format!("sh -c \"{} --printenv >&{}\";", quoted_path, env_fd);
1135
1136        // This should produce: sh -c "'/Applications/Zed Nightly.app/Contents/MacOS/zed' --printenv >&0";
1137        let expected =
1138            "sh -c \"'/Applications/Zed Nightly.app/Contents/MacOS/zed' --printenv >&0\";";
1139        assert_eq!(command, expected);
1140
1141        // The command should not contain the problematic double single-quote pattern
1142        assert!(!command.contains("''"));
1143    }
1144
1145    #[test]
1146    fn test_truncate_to_bottom_n_sorted_by() {
1147        let mut vec: Vec<u32> = vec![5, 2, 3, 4, 1];
1148        truncate_to_bottom_n_sorted_by(&mut vec, 10, &u32::cmp);
1149        assert_eq!(vec, &[1, 2, 3, 4, 5]);
1150
1151        vec = vec![5, 2, 3, 4, 1];
1152        truncate_to_bottom_n_sorted_by(&mut vec, 5, &u32::cmp);
1153        assert_eq!(vec, &[1, 2, 3, 4, 5]);
1154
1155        vec = vec![5, 2, 3, 4, 1];
1156        truncate_to_bottom_n_sorted_by(&mut vec, 4, &u32::cmp);
1157        assert_eq!(vec, &[1, 2, 3, 4]);
1158
1159        vec = vec![5, 2, 3, 4, 1];
1160        truncate_to_bottom_n_sorted_by(&mut vec, 1, &u32::cmp);
1161        assert_eq!(vec, &[1]);
1162
1163        vec = vec![5, 2, 3, 4, 1];
1164        truncate_to_bottom_n_sorted_by(&mut vec, 0, &u32::cmp);
1165        assert!(vec.is_empty());
1166    }
1167
1168    #[test]
1169    fn test_iife() {
1170        fn option_returning_function() -> Option<()> {
1171            None
1172        }
1173
1174        let foo = maybe!({
1175            option_returning_function()?;
1176            Some(())
1177        });
1178
1179        assert_eq!(foo, None);
1180    }
1181
1182    #[test]
1183    fn test_truncate_and_trailoff() {
1184        assert_eq!(truncate_and_trailoff("", 5), "");
1185        assert_eq!(truncate_and_trailoff("aaaaaa", 7), "aaaaaa");
1186        assert_eq!(truncate_and_trailoff("aaaaaa", 6), "aaaaaa");
1187        assert_eq!(truncate_and_trailoff("aaaaaa", 5), "aaaaa…");
1188        assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
1189        assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
1190        assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
1191    }
1192
1193    #[test]
1194    fn test_truncate_and_remove_front() {
1195        assert_eq!(truncate_and_remove_front("", 5), "");
1196        assert_eq!(truncate_and_remove_front("aaaaaa", 7), "aaaaaa");
1197        assert_eq!(truncate_and_remove_front("aaaaaa", 6), "aaaaaa");
1198        assert_eq!(truncate_and_remove_front("aaaaaa", 5), "…aaaaa");
1199        assert_eq!(truncate_and_remove_front("èèèèèè", 7), "èèèèèè");
1200        assert_eq!(truncate_and_remove_front("èèèèèè", 6), "èèèèèè");
1201        assert_eq!(truncate_and_remove_front("èèèèèè", 5), "…èèèèè");
1202    }
1203
1204    #[test]
1205    fn test_numeric_prefix_str_method() {
1206        let target = "1a";
1207        assert_eq!(
1208            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1209            NumericPrefixWithSuffix(Some(1), "a")
1210        );
1211
1212        let target = "12ab";
1213        assert_eq!(
1214            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1215            NumericPrefixWithSuffix(Some(12), "ab")
1216        );
1217
1218        let target = "12_ab";
1219        assert_eq!(
1220            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1221            NumericPrefixWithSuffix(Some(12), "_ab")
1222        );
1223
1224        let target = "1_2ab";
1225        assert_eq!(
1226            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1227            NumericPrefixWithSuffix(Some(1), "_2ab")
1228        );
1229
1230        let target = "1.2";
1231        assert_eq!(
1232            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1233            NumericPrefixWithSuffix(Some(1), ".2")
1234        );
1235
1236        let target = "1.2_a";
1237        assert_eq!(
1238            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1239            NumericPrefixWithSuffix(Some(1), ".2_a")
1240        );
1241
1242        let target = "12.2_a";
1243        assert_eq!(
1244            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1245            NumericPrefixWithSuffix(Some(12), ".2_a")
1246        );
1247
1248        let target = "12a.2_a";
1249        assert_eq!(
1250            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1251            NumericPrefixWithSuffix(Some(12), "a.2_a")
1252        );
1253    }
1254
1255    #[test]
1256    fn test_numeric_prefix_with_suffix() {
1257        let mut sorted = vec!["1-abc", "10", "11def", "2", "21-abc"];
1258        sorted.sort_by_key(|s| NumericPrefixWithSuffix::from_numeric_prefixed_str(s));
1259        assert_eq!(sorted, ["1-abc", "2", "10", "11def", "21-abc"]);
1260
1261        for numeric_prefix_less in ["numeric_prefix_less", "aaa", "~β„’Β£"] {
1262            assert_eq!(
1263                NumericPrefixWithSuffix::from_numeric_prefixed_str(numeric_prefix_less),
1264                NumericPrefixWithSuffix(None, numeric_prefix_less),
1265                "String without numeric prefix `{numeric_prefix_less}` should not be converted into NumericPrefixWithSuffix"
1266            )
1267        }
1268    }
1269
1270    #[test]
1271    fn test_word_consists_of_emojis() {
1272        let words_to_test = vec![
1273            ("πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘§πŸ‘‹πŸ₯’", true),
1274            ("πŸ‘‹", true),
1275            ("!πŸ‘‹", false),
1276            ("πŸ‘‹!", false),
1277            ("πŸ‘‹ ", false),
1278            (" πŸ‘‹", false),
1279            ("Test", false),
1280        ];
1281
1282        for (text, expected_result) in words_to_test {
1283            assert_eq!(word_consists_of_emojis(text), expected_result);
1284        }
1285    }
1286
1287    #[test]
1288    fn test_truncate_lines_and_trailoff() {
1289        let text = r#"Line 1
1290Line 2
1291Line 3"#;
1292
1293        assert_eq!(
1294            truncate_lines_and_trailoff(text, 2),
1295            r#"Line 1
1296…"#
1297        );
1298
1299        assert_eq!(
1300            truncate_lines_and_trailoff(text, 3),
1301            r#"Line 1
1302Line 2
1303…"#
1304        );
1305
1306        assert_eq!(
1307            truncate_lines_and_trailoff(text, 4),
1308            r#"Line 1
1309Line 2
1310Line 3"#
1311        );
1312    }
1313
1314    #[test]
1315    fn test_expanded_and_wrapped_usize_range() {
1316        // Neither wrap
1317        assert_eq!(
1318            expanded_and_wrapped_usize_range(2..4, 1, 1, 8).collect::<Vec<usize>>(),
1319            (1..5).collect::<Vec<usize>>()
1320        );
1321        // Start wraps
1322        assert_eq!(
1323            expanded_and_wrapped_usize_range(2..4, 3, 1, 8).collect::<Vec<usize>>(),
1324            ((0..5).chain(7..8)).collect::<Vec<usize>>()
1325        );
1326        // Start wraps all the way around
1327        assert_eq!(
1328            expanded_and_wrapped_usize_range(2..4, 5, 1, 8).collect::<Vec<usize>>(),
1329            (0..8).collect::<Vec<usize>>()
1330        );
1331        // Start wraps all the way around and past 0
1332        assert_eq!(
1333            expanded_and_wrapped_usize_range(2..4, 10, 1, 8).collect::<Vec<usize>>(),
1334            (0..8).collect::<Vec<usize>>()
1335        );
1336        // End wraps
1337        assert_eq!(
1338            expanded_and_wrapped_usize_range(3..5, 1, 4, 8).collect::<Vec<usize>>(),
1339            (0..1).chain(2..8).collect::<Vec<usize>>()
1340        );
1341        // End wraps all the way around
1342        assert_eq!(
1343            expanded_and_wrapped_usize_range(3..5, 1, 5, 8).collect::<Vec<usize>>(),
1344            (0..8).collect::<Vec<usize>>()
1345        );
1346        // End wraps all the way around and past the end
1347        assert_eq!(
1348            expanded_and_wrapped_usize_range(3..5, 1, 10, 8).collect::<Vec<usize>>(),
1349            (0..8).collect::<Vec<usize>>()
1350        );
1351        // Both start and end wrap
1352        assert_eq!(
1353            expanded_and_wrapped_usize_range(3..5, 4, 4, 8).collect::<Vec<usize>>(),
1354            (0..8).collect::<Vec<usize>>()
1355        );
1356    }
1357
1358    #[test]
1359    fn test_wrapped_usize_outward_from() {
1360        // No wrapping
1361        assert_eq!(
1362            wrapped_usize_outward_from(4, 2, 2, 10).collect::<Vec<usize>>(),
1363            vec![4, 5, 3, 6, 2]
1364        );
1365        // Wrapping at end
1366        assert_eq!(
1367            wrapped_usize_outward_from(8, 2, 3, 10).collect::<Vec<usize>>(),
1368            vec![8, 9, 7, 0, 6, 1]
1369        );
1370        // Wrapping at start
1371        assert_eq!(
1372            wrapped_usize_outward_from(1, 3, 2, 10).collect::<Vec<usize>>(),
1373            vec![1, 2, 0, 3, 9, 8]
1374        );
1375        // All values wrap around
1376        assert_eq!(
1377            wrapped_usize_outward_from(5, 10, 10, 8).collect::<Vec<usize>>(),
1378            vec![5, 6, 4, 7, 3, 0, 2, 1]
1379        );
1380        // None before / after
1381        assert_eq!(
1382            wrapped_usize_outward_from(3, 0, 0, 8).collect::<Vec<usize>>(),
1383            vec![3]
1384        );
1385        // Starting point already wrapped
1386        assert_eq!(
1387            wrapped_usize_outward_from(15, 2, 2, 10).collect::<Vec<usize>>(),
1388            vec![5, 6, 4, 7, 3]
1389        );
1390        // wrap_length of 0
1391        assert_eq!(
1392            wrapped_usize_outward_from(4, 2, 2, 0).collect::<Vec<usize>>(),
1393            Vec::<usize>::new()
1394        );
1395    }
1396
1397    #[test]
1398    fn test_split_with_ranges() {
1399        let input = "hi";
1400        let result = split_str_with_ranges(input, |c| c == ' ');
1401
1402        assert_eq!(result.len(), 1);
1403        assert_eq!(result[0], (0..2, "hi"));
1404
1405        let input = "hΓ©lloπŸ¦€world";
1406        let result = split_str_with_ranges(input, |c| c == 'πŸ¦€');
1407
1408        assert_eq!(result.len(), 2);
1409        assert_eq!(result[0], (0..6, "hΓ©llo")); // 'Γ©' is 2 bytes
1410        assert_eq!(result[1], (10..15, "world")); // 'πŸ¦€' is 4 bytes
1411    }
1412}