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 rel_path;
   9pub mod schemars;
  10pub mod serde;
  11pub mod shell_env;
  12pub mod size;
  13#[cfg(any(test, feature = "test-support"))]
  14pub mod test;
  15pub mod time;
  16
  17use anyhow::{Context as _, Result};
  18use futures::Future;
  19use itertools::Either;
  20use regex::Regex;
  21use std::sync::{LazyLock, OnceLock};
  22use std::{
  23    borrow::Cow,
  24    cmp::{self, Ordering},
  25    env,
  26    ops::{AddAssign, Range, RangeInclusive},
  27    panic::Location,
  28    pin::Pin,
  29    task::{Context, Poll},
  30    time::Instant,
  31};
  32use unicase::UniCase;
  33
  34pub use take_until::*;
  35#[cfg(any(test, feature = "test-support"))]
  36pub use util_macros::{line_endings, path, uri};
  37
  38#[macro_export]
  39macro_rules! debug_panic {
  40    ( $($fmt_arg:tt)* ) => {
  41        if cfg!(debug_assertions) {
  42            panic!( $($fmt_arg)* );
  43        } else {
  44            let backtrace = std::backtrace::Backtrace::capture();
  45            log::error!("{}\n{:?}", format_args!($($fmt_arg)*), backtrace);
  46        }
  47    };
  48}
  49
  50pub fn truncate(s: &str, max_chars: usize) -> &str {
  51    match s.char_indices().nth(max_chars) {
  52        None => s,
  53        Some((idx, _)) => &s[..idx],
  54    }
  55}
  56
  57/// Removes characters from the end of the string if its length is greater than `max_chars` and
  58/// appends "..." to the string. Returns string unchanged if its length is smaller than max_chars.
  59pub fn truncate_and_trailoff(s: &str, max_chars: usize) -> String {
  60    debug_assert!(max_chars >= 5);
  61
  62    // If the string's byte length is <= max_chars, walking the string can be skipped since the
  63    // number of chars is <= the number of bytes.
  64    if s.len() <= max_chars {
  65        return s.to_string();
  66    }
  67    let truncation_ix = s.char_indices().map(|(i, _)| i).nth(max_chars);
  68    match truncation_ix {
  69        Some(index) => s[..index].to_string() + "…",
  70        _ => s.to_string(),
  71    }
  72}
  73
  74/// Removes characters from the front of the string if its length is greater than `max_chars` and
  75/// prepends the string with "...". Returns string unchanged if its length is smaller than max_chars.
  76pub fn truncate_and_remove_front(s: &str, max_chars: usize) -> String {
  77    debug_assert!(max_chars >= 5);
  78
  79    // If the string's byte length is <= max_chars, walking the string can be skipped since the
  80    // number of chars is <= the number of bytes.
  81    if s.len() <= max_chars {
  82        return s.to_string();
  83    }
  84    let suffix_char_length = max_chars.saturating_sub(1);
  85    let truncation_ix = s
  86        .char_indices()
  87        .map(|(i, _)| i)
  88        .nth_back(suffix_char_length);
  89    match truncation_ix {
  90        Some(index) if index > 0 => "…".to_string() + &s[index..],
  91        _ => s.to_string(),
  92    }
  93}
  94
  95/// Takes only `max_lines` from the string and, if there were more than `max_lines-1`, appends a
  96/// a newline and "..." to the string, so that `max_lines` are returned.
  97/// Returns string unchanged if its length is smaller than max_lines.
  98pub fn truncate_lines_and_trailoff(s: &str, max_lines: usize) -> String {
  99    let mut lines = s.lines().take(max_lines).collect::<Vec<_>>();
 100    if lines.len() > max_lines - 1 {
 101        lines.pop();
 102        lines.join("\n") + "\n…"
 103    } else {
 104        lines.join("\n")
 105    }
 106}
 107
 108/// Truncates the string at a character boundary, such that the result is less than `max_bytes` in
 109/// length.
 110pub fn truncate_to_byte_limit(s: &str, max_bytes: usize) -> &str {
 111    if s.len() < max_bytes {
 112        return s;
 113    }
 114
 115    for i in (0..max_bytes).rev() {
 116        if s.is_char_boundary(i) {
 117            return &s[..i];
 118        }
 119    }
 120
 121    ""
 122}
 123
 124/// Takes a prefix of complete lines which fit within the byte limit. If the first line is longer
 125/// than the limit, truncates at a character boundary.
 126pub fn truncate_lines_to_byte_limit(s: &str, max_bytes: usize) -> &str {
 127    if s.len() < max_bytes {
 128        return s;
 129    }
 130
 131    for i in (0..max_bytes).rev() {
 132        if s.is_char_boundary(i) && s.as_bytes()[i] == b'\n' {
 133            // Since the i-th character is \n, valid to slice at i + 1.
 134            return &s[..i + 1];
 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    anyhow::ensure!(!result.is_null(), "passwd entry for uid {} not found", uid);
 261
 262    // SAFETY: If `getpwuid_r` doesn't error, we have the entry here.
 263    let entry = unsafe { pwd.assume_init() };
 264
 265    anyhow::ensure!(
 266        status == 0,
 267        "call to getpwuid_r failed. uid: {}, status: {}",
 268        uid,
 269        status
 270    );
 271    anyhow::ensure!(
 272        entry.pw_uid == uid,
 273        "passwd entry has different uid ({}) than getuid ({}) returned",
 274        entry.pw_uid,
 275        uid,
 276    );
 277
 278    let shell = unsafe { std::ffi::CStr::from_ptr(entry.pw_shell).to_str().unwrap() };
 279    if env::var("SHELL").map_or(true, |shell_env| shell_env != shell) {
 280        log::info!(
 281            "updating SHELL environment variable to value from passwd entry: {:?}",
 282            shell,
 283        );
 284        unsafe { env::set_var("SHELL", shell) };
 285    }
 286
 287    Ok(())
 288}
 289
 290#[cfg(unix)]
 291/// Returns a shell escaped path for the current zed executable
 292pub fn get_shell_safe_zed_path() -> anyhow::Result<String> {
 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    Ok(zed_path_escaped.to_string())
 306}
 307
 308/// Returns a shell escaped path for the zed cli executable, this function
 309/// should be called from the zed executable, not zed-cli.
 310pub fn get_shell_safe_zed_cli_path() -> Result<String> {
 311    let zed_path =
 312        std::env::current_exe().context("Failed to determine current zed executable path.")?;
 313    let parent = zed_path
 314        .parent()
 315        .context("Failed to determine parent directory of zed executable path.")?;
 316
 317    let possible_locations: &[&str] = if cfg!(target_os = "macos") {
 318        // On macOS, the zed executable and zed-cli are inside the app bundle,
 319        // so here ./cli is for both installed and development builds.
 320        &["./cli"]
 321    } else if cfg!(target_os = "windows") {
 322        // bin/zed.exe is for installed builds, ./cli.exe is for development builds.
 323        &["bin/zed.exe", "./cli.exe"]
 324    } else if cfg!(target_os = "linux") || cfg!(target_os = "freebsd") {
 325        // bin is the standard, ./cli is for the target directory in development builds.
 326        &["../bin/zed", "./cli"]
 327    } else {
 328        anyhow::bail!("unsupported platform for determining zed-cli path");
 329    };
 330
 331    let zed_cli_path = possible_locations
 332        .iter()
 333        .find_map(|p| {
 334            parent
 335                .join(p)
 336                .canonicalize()
 337                .ok()
 338                .filter(|p| p != &zed_path)
 339        })
 340        .with_context(|| {
 341            format!(
 342                "could not find zed-cli from any of: {}",
 343                possible_locations.join(", ")
 344            )
 345        })?
 346        .to_string_lossy()
 347        .to_string();
 348
 349    #[cfg(target_os = "windows")]
 350    {
 351        Ok(zed_cli_path)
 352    }
 353    #[cfg(not(target_os = "windows"))]
 354    {
 355        Ok(shlex::try_quote(&zed_cli_path)
 356            .context("Failed to shell-escape Zed executable path.")?
 357            .to_string())
 358    }
 359}
 360
 361#[cfg(unix)]
 362pub async fn load_login_shell_environment() -> Result<()> {
 363    load_shell_from_passwd().log_err();
 364
 365    // If possible, we want to `cd` in the user's `$HOME` to trigger programs
 366    // such as direnv, asdf, mise, ... to adjust the PATH. These tools often hook
 367    // into shell's `cd` command (and hooks) to manipulate env.
 368    // We do this so that we get the env a user would have when spawning a shell
 369    // in home directory.
 370    for (name, value) in shell_env::capture(paths::home_dir()).await? {
 371        unsafe { env::set_var(&name, &value) };
 372    }
 373
 374    log::info!(
 375        "set environment variables from shell:{}, path:{}",
 376        std::env::var("SHELL").unwrap_or_default(),
 377        std::env::var("PATH").unwrap_or_default(),
 378    );
 379
 380    Ok(())
 381}
 382
 383/// Configures the process to start a new session, to prevent interactive shells from taking control
 384/// of the terminal.
 385///
 386/// For more details: <https://registerspill.thorstenball.com/p/how-to-lose-control-of-your-shell>
 387pub fn set_pre_exec_to_start_new_session(
 388    command: &mut std::process::Command,
 389) -> &mut std::process::Command {
 390    // safety: code in pre_exec should be signal safe.
 391    // https://man7.org/linux/man-pages/man7/signal-safety.7.html
 392    #[cfg(not(target_os = "windows"))]
 393    unsafe {
 394        use std::os::unix::process::CommandExt;
 395        command.pre_exec(|| {
 396            libc::setsid();
 397            Ok(())
 398        });
 399    };
 400    command
 401}
 402
 403pub fn merge_json_lenient_value_into(
 404    source: serde_json_lenient::Value,
 405    target: &mut serde_json_lenient::Value,
 406) {
 407    match (source, target) {
 408        (serde_json_lenient::Value::Object(source), serde_json_lenient::Value::Object(target)) => {
 409            for (key, value) in source {
 410                if let Some(target) = target.get_mut(&key) {
 411                    merge_json_lenient_value_into(value, target);
 412                } else {
 413                    target.insert(key, value);
 414                }
 415            }
 416        }
 417
 418        (serde_json_lenient::Value::Array(source), serde_json_lenient::Value::Array(target)) => {
 419            for value in source {
 420                target.push(value);
 421            }
 422        }
 423
 424        (source, target) => *target = source,
 425    }
 426}
 427
 428pub fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
 429    use serde_json::Value;
 430
 431    match (source, target) {
 432        (Value::Object(source), Value::Object(target)) => {
 433            for (key, value) in source {
 434                if let Some(target) = target.get_mut(&key) {
 435                    merge_json_value_into(value, target);
 436                } else {
 437                    target.insert(key, value);
 438                }
 439            }
 440        }
 441
 442        (Value::Array(source), Value::Array(target)) => {
 443            for value in source {
 444                target.push(value);
 445            }
 446        }
 447
 448        (source, target) => *target = source,
 449    }
 450}
 451
 452pub fn merge_non_null_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
 453    use serde_json::Value;
 454    if let Value::Object(source_object) = source {
 455        let target_object = if let Value::Object(target) = target {
 456            target
 457        } else {
 458            *target = Value::Object(Default::default());
 459            target.as_object_mut().unwrap()
 460        };
 461        for (key, value) in source_object {
 462            if let Some(target) = target_object.get_mut(&key) {
 463                merge_non_null_json_value_into(value, target);
 464            } else if !value.is_null() {
 465                target_object.insert(key, value);
 466            }
 467        }
 468    } else if !source.is_null() {
 469        *target = source
 470    }
 471}
 472
 473pub fn measure<R>(label: &str, f: impl FnOnce() -> R) -> R {
 474    static ZED_MEASUREMENTS: OnceLock<bool> = OnceLock::new();
 475    let zed_measurements = ZED_MEASUREMENTS.get_or_init(|| {
 476        env::var("ZED_MEASUREMENTS")
 477            .map(|measurements| measurements == "1" || measurements == "true")
 478            .unwrap_or(false)
 479    });
 480
 481    if *zed_measurements {
 482        let start = Instant::now();
 483        let result = f();
 484        let elapsed = start.elapsed();
 485        eprintln!("{}: {:?}", label, elapsed);
 486        result
 487    } else {
 488        f()
 489    }
 490}
 491
 492pub fn expanded_and_wrapped_usize_range(
 493    range: Range<usize>,
 494    additional_before: usize,
 495    additional_after: usize,
 496    wrap_length: usize,
 497) -> impl Iterator<Item = usize> {
 498    let start_wraps = range.start < additional_before;
 499    let end_wraps = wrap_length < range.end + additional_after;
 500    if start_wraps && end_wraps {
 501        Either::Left(0..wrap_length)
 502    } else if start_wraps {
 503        let wrapped_start = (range.start + wrap_length).saturating_sub(additional_before);
 504        if wrapped_start <= range.end {
 505            Either::Left(0..wrap_length)
 506        } else {
 507            Either::Right((0..range.end + additional_after).chain(wrapped_start..wrap_length))
 508        }
 509    } else if end_wraps {
 510        let wrapped_end = range.end + additional_after - wrap_length;
 511        if range.start <= wrapped_end {
 512            Either::Left(0..wrap_length)
 513        } else {
 514            Either::Right((0..wrapped_end).chain(range.start - additional_before..wrap_length))
 515        }
 516    } else {
 517        Either::Left((range.start - additional_before)..(range.end + additional_after))
 518    }
 519}
 520
 521/// Yields `[i, i + 1, i - 1, i + 2, ..]`, each modulo `wrap_length` and bounded by
 522/// `additional_before` and `additional_after`. If the wrapping causes overlap, duplicates are not
 523/// emitted. If wrap_length is 0, nothing is yielded.
 524pub fn wrapped_usize_outward_from(
 525    start: usize,
 526    additional_before: usize,
 527    additional_after: usize,
 528    wrap_length: usize,
 529) -> impl Iterator<Item = usize> {
 530    let mut count = 0;
 531    let mut after_offset = 1;
 532    let mut before_offset = 1;
 533
 534    std::iter::from_fn(move || {
 535        count += 1;
 536        if count > wrap_length {
 537            None
 538        } else if count == 1 {
 539            Some(start % wrap_length)
 540        } else if after_offset <= additional_after && after_offset <= before_offset {
 541            let value = (start + after_offset) % wrap_length;
 542            after_offset += 1;
 543            Some(value)
 544        } else if before_offset <= additional_before {
 545            let value = (start + wrap_length - before_offset) % wrap_length;
 546            before_offset += 1;
 547            Some(value)
 548        } else if after_offset <= additional_after {
 549            let value = (start + after_offset) % wrap_length;
 550            after_offset += 1;
 551            Some(value)
 552        } else {
 553            None
 554        }
 555    })
 556}
 557
 558#[cfg(target_os = "windows")]
 559pub fn get_windows_system_shell() -> String {
 560    use std::path::PathBuf;
 561
 562    fn find_pwsh_in_programfiles(find_alternate: bool, find_preview: bool) -> Option<PathBuf> {
 563        #[cfg(target_pointer_width = "64")]
 564        let env_var = if find_alternate {
 565            "ProgramFiles(x86)"
 566        } else {
 567            "ProgramFiles"
 568        };
 569
 570        #[cfg(target_pointer_width = "32")]
 571        let env_var = if find_alternate {
 572            "ProgramW6432"
 573        } else {
 574            "ProgramFiles"
 575        };
 576
 577        let install_base_dir = PathBuf::from(std::env::var_os(env_var)?).join("PowerShell");
 578        install_base_dir
 579            .read_dir()
 580            .ok()?
 581            .filter_map(Result::ok)
 582            .filter(|entry| matches!(entry.file_type(), Ok(ft) if ft.is_dir()))
 583            .filter_map(|entry| {
 584                let dir_name = entry.file_name();
 585                let dir_name = dir_name.to_string_lossy();
 586
 587                let version = if find_preview {
 588                    let dash_index = dir_name.find('-')?;
 589                    if &dir_name[dash_index + 1..] != "preview" {
 590                        return None;
 591                    };
 592                    dir_name[..dash_index].parse::<u32>().ok()?
 593                } else {
 594                    dir_name.parse::<u32>().ok()?
 595                };
 596
 597                let exe_path = entry.path().join("pwsh.exe");
 598                if exe_path.exists() {
 599                    Some((version, exe_path))
 600                } else {
 601                    None
 602                }
 603            })
 604            .max_by_key(|(version, _)| *version)
 605            .map(|(_, path)| path)
 606    }
 607
 608    fn find_pwsh_in_msix(find_preview: bool) -> Option<PathBuf> {
 609        let msix_app_dir =
 610            PathBuf::from(std::env::var_os("LOCALAPPDATA")?).join("Microsoft\\WindowsApps");
 611        if !msix_app_dir.exists() {
 612            return None;
 613        }
 614
 615        let prefix = if find_preview {
 616            "Microsoft.PowerShellPreview_"
 617        } else {
 618            "Microsoft.PowerShell_"
 619        };
 620        msix_app_dir
 621            .read_dir()
 622            .ok()?
 623            .filter_map(|entry| {
 624                let entry = entry.ok()?;
 625                if !matches!(entry.file_type(), Ok(ft) if ft.is_dir()) {
 626                    return None;
 627                }
 628
 629                if !entry.file_name().to_string_lossy().starts_with(prefix) {
 630                    return None;
 631                }
 632
 633                let exe_path = entry.path().join("pwsh.exe");
 634                exe_path.exists().then_some(exe_path)
 635            })
 636            .next()
 637    }
 638
 639    fn find_pwsh_in_scoop() -> Option<PathBuf> {
 640        let pwsh_exe =
 641            PathBuf::from(std::env::var_os("USERPROFILE")?).join("scoop\\shims\\pwsh.exe");
 642        pwsh_exe.exists().then_some(pwsh_exe)
 643    }
 644
 645    static SYSTEM_SHELL: LazyLock<String> = LazyLock::new(|| {
 646        find_pwsh_in_programfiles(false, false)
 647            .or_else(|| find_pwsh_in_programfiles(true, false))
 648            .or_else(|| find_pwsh_in_msix(false))
 649            .or_else(|| find_pwsh_in_programfiles(false, true))
 650            .or_else(|| find_pwsh_in_msix(true))
 651            .or_else(|| find_pwsh_in_programfiles(true, true))
 652            .or_else(find_pwsh_in_scoop)
 653            .map(|p| p.to_string_lossy().into_owned())
 654            .unwrap_or("powershell.exe".to_string())
 655    });
 656
 657    (*SYSTEM_SHELL).clone()
 658}
 659
 660pub trait ResultExt<E> {
 661    type Ok;
 662
 663    fn log_err(self) -> Option<Self::Ok>;
 664    /// Assert that this result should never be an error in development or tests.
 665    fn debug_assert_ok(self, reason: &str) -> Self;
 666    fn warn_on_err(self) -> Option<Self::Ok>;
 667    fn log_with_level(self, level: log::Level) -> Option<Self::Ok>;
 668    fn anyhow(self) -> anyhow::Result<Self::Ok>
 669    where
 670        E: Into<anyhow::Error>;
 671}
 672
 673impl<T, E> ResultExt<E> for Result<T, E>
 674where
 675    E: std::fmt::Debug,
 676{
 677    type Ok = T;
 678
 679    #[track_caller]
 680    fn log_err(self) -> Option<T> {
 681        self.log_with_level(log::Level::Error)
 682    }
 683
 684    #[track_caller]
 685    fn debug_assert_ok(self, reason: &str) -> Self {
 686        if let Err(error) = &self {
 687            debug_panic!("{reason} - {error:?}");
 688        }
 689        self
 690    }
 691
 692    #[track_caller]
 693    fn warn_on_err(self) -> Option<T> {
 694        self.log_with_level(log::Level::Warn)
 695    }
 696
 697    #[track_caller]
 698    fn log_with_level(self, level: log::Level) -> Option<T> {
 699        match self {
 700            Ok(value) => Some(value),
 701            Err(error) => {
 702                log_error_with_caller(*Location::caller(), error, level);
 703                None
 704            }
 705        }
 706    }
 707
 708    fn anyhow(self) -> anyhow::Result<T>
 709    where
 710        E: Into<anyhow::Error>,
 711    {
 712        self.map_err(Into::into)
 713    }
 714}
 715
 716fn log_error_with_caller<E>(caller: core::panic::Location<'_>, error: E, level: log::Level)
 717where
 718    E: std::fmt::Debug,
 719{
 720    #[cfg(not(target_os = "windows"))]
 721    let file = caller.file();
 722    #[cfg(target_os = "windows")]
 723    let file = caller.file().replace('\\', "/");
 724    // In this codebase all crates reside in a `crates` directory,
 725    // so discard the prefix up to that segment to find the crate name
 726    let target = file
 727        .split_once("crates/")
 728        .and_then(|(_, s)| s.split_once('/'))
 729        .map(|(p, _)| p);
 730
 731    log::logger().log(
 732        &log::Record::builder()
 733            .target(target.unwrap_or(""))
 734            .module_path(target)
 735            .args(format_args!("{:?}", error))
 736            .file(Some(caller.file()))
 737            .line(Some(caller.line()))
 738            .level(level)
 739            .build(),
 740    );
 741}
 742
 743pub fn log_err<E: std::fmt::Debug>(error: &E) {
 744    log_error_with_caller(*Location::caller(), error, log::Level::Warn);
 745}
 746
 747pub trait TryFutureExt {
 748    fn log_err(self) -> LogErrorFuture<Self>
 749    where
 750        Self: Sized;
 751
 752    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
 753    where
 754        Self: Sized;
 755
 756    fn warn_on_err(self) -> LogErrorFuture<Self>
 757    where
 758        Self: Sized;
 759    fn unwrap(self) -> UnwrapFuture<Self>
 760    where
 761        Self: Sized;
 762}
 763
 764impl<F, T, E> TryFutureExt for F
 765where
 766    F: Future<Output = Result<T, E>>,
 767    E: std::fmt::Debug,
 768{
 769    #[track_caller]
 770    fn log_err(self) -> LogErrorFuture<Self>
 771    where
 772        Self: Sized,
 773    {
 774        let location = Location::caller();
 775        LogErrorFuture(self, log::Level::Error, *location)
 776    }
 777
 778    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
 779    where
 780        Self: Sized,
 781    {
 782        LogErrorFuture(self, log::Level::Error, location)
 783    }
 784
 785    #[track_caller]
 786    fn warn_on_err(self) -> LogErrorFuture<Self>
 787    where
 788        Self: Sized,
 789    {
 790        let location = Location::caller();
 791        LogErrorFuture(self, log::Level::Warn, *location)
 792    }
 793
 794    fn unwrap(self) -> UnwrapFuture<Self>
 795    where
 796        Self: Sized,
 797    {
 798        UnwrapFuture(self)
 799    }
 800}
 801
 802#[must_use]
 803pub struct LogErrorFuture<F>(F, log::Level, core::panic::Location<'static>);
 804
 805impl<F, T, E> Future for LogErrorFuture<F>
 806where
 807    F: Future<Output = Result<T, E>>,
 808    E: std::fmt::Debug,
 809{
 810    type Output = Option<T>;
 811
 812    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
 813        let level = self.1;
 814        let location = self.2;
 815        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
 816        match inner.poll(cx) {
 817            Poll::Ready(output) => Poll::Ready(match output {
 818                Ok(output) => Some(output),
 819                Err(error) => {
 820                    log_error_with_caller(location, error, level);
 821                    None
 822                }
 823            }),
 824            Poll::Pending => Poll::Pending,
 825        }
 826    }
 827}
 828
 829pub struct UnwrapFuture<F>(F);
 830
 831impl<F, T, E> Future for UnwrapFuture<F>
 832where
 833    F: Future<Output = Result<T, E>>,
 834    E: std::fmt::Debug,
 835{
 836    type Output = T;
 837
 838    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
 839        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
 840        match inner.poll(cx) {
 841            Poll::Ready(result) => Poll::Ready(result.unwrap()),
 842            Poll::Pending => Poll::Pending,
 843        }
 844    }
 845}
 846
 847pub struct Deferred<F: FnOnce()>(Option<F>);
 848
 849impl<F: FnOnce()> Deferred<F> {
 850    /// Drop without running the deferred function.
 851    pub fn abort(mut self) {
 852        self.0.take();
 853    }
 854}
 855
 856impl<F: FnOnce()> Drop for Deferred<F> {
 857    fn drop(&mut self) {
 858        if let Some(f) = self.0.take() {
 859            f()
 860        }
 861    }
 862}
 863
 864/// Run the given function when the returned value is dropped (unless it's cancelled).
 865#[must_use]
 866pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
 867    Deferred(Some(f))
 868}
 869
 870#[cfg(any(test, feature = "test-support"))]
 871mod rng {
 872    use rand::prelude::*;
 873
 874    pub struct RandomCharIter<T: Rng> {
 875        rng: T,
 876        simple_text: bool,
 877    }
 878
 879    impl<T: Rng> RandomCharIter<T> {
 880        pub fn new(rng: T) -> Self {
 881            Self {
 882                rng,
 883                simple_text: std::env::var("SIMPLE_TEXT").is_ok_and(|v| !v.is_empty()),
 884            }
 885        }
 886
 887        pub fn with_simple_text(mut self) -> Self {
 888            self.simple_text = true;
 889            self
 890        }
 891    }
 892
 893    impl<T: Rng> Iterator for RandomCharIter<T> {
 894        type Item = char;
 895
 896        fn next(&mut self) -> Option<Self::Item> {
 897            if self.simple_text {
 898                return if self.rng.random_range(0..100) < 5 {
 899                    Some('\n')
 900                } else {
 901                    Some(self.rng.random_range(b'a'..b'z' + 1).into())
 902                };
 903            }
 904
 905            match self.rng.random_range(0..100) {
 906                // whitespace
 907                0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
 908                // two-byte greek letters
 909                20..=32 => char::from_u32(self.rng.random_range(('Ξ±' as u32)..('Ο‰' as u32 + 1))),
 910                // // three-byte characters
 911                33..=45 => ['βœ‹', 'βœ…', '❌', '❎', '⭐']
 912                    .choose(&mut self.rng)
 913                    .copied(),
 914                // // four-byte characters
 915                46..=58 => ['🍐', 'πŸ€', 'πŸ—', 'πŸŽ‰'].choose(&mut self.rng).copied(),
 916                // ascii letters
 917                _ => Some(self.rng.random_range(b'a'..b'z' + 1).into()),
 918            }
 919        }
 920    }
 921}
 922#[cfg(any(test, feature = "test-support"))]
 923pub use rng::RandomCharIter;
 924
 925/// Get an embedded file as a string.
 926pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
 927    match A::get(path).expect(path).data {
 928        Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
 929        Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
 930    }
 931}
 932
 933/// Expands to an immediately-invoked function expression. Good for using the ? operator
 934/// in functions which do not return an Option or Result.
 935///
 936/// Accepts a normal block, an async block, or an async move block.
 937#[macro_export]
 938macro_rules! maybe {
 939    ($block:block) => {
 940        (|| $block)()
 941    };
 942    (async $block:block) => {
 943        (async || $block)()
 944    };
 945    (async move $block:block) => {
 946        (async move || $block)()
 947    };
 948}
 949
 950pub trait RangeExt<T> {
 951    fn sorted(&self) -> Self;
 952    fn to_inclusive(&self) -> RangeInclusive<T>;
 953    fn overlaps(&self, other: &Range<T>) -> bool;
 954    fn contains_inclusive(&self, other: &Range<T>) -> bool;
 955}
 956
 957impl<T: Ord + Clone> RangeExt<T> for Range<T> {
 958    fn sorted(&self) -> Self {
 959        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
 960    }
 961
 962    fn to_inclusive(&self) -> RangeInclusive<T> {
 963        self.start.clone()..=self.end.clone()
 964    }
 965
 966    fn overlaps(&self, other: &Range<T>) -> bool {
 967        self.start < other.end && other.start < self.end
 968    }
 969
 970    fn contains_inclusive(&self, other: &Range<T>) -> bool {
 971        self.start <= other.start && other.end <= self.end
 972    }
 973}
 974
 975impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
 976    fn sorted(&self) -> Self {
 977        cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
 978    }
 979
 980    fn to_inclusive(&self) -> RangeInclusive<T> {
 981        self.clone()
 982    }
 983
 984    fn overlaps(&self, other: &Range<T>) -> bool {
 985        self.start() < &other.end && &other.start <= self.end()
 986    }
 987
 988    fn contains_inclusive(&self, other: &Range<T>) -> bool {
 989        self.start() <= &other.start && &other.end <= self.end()
 990    }
 991}
 992
 993/// A way to sort strings with starting numbers numerically first, falling back to alphanumeric one,
 994/// case-insensitive.
 995///
 996/// This is useful for turning regular alphanumerically sorted sequences as `1-abc, 10, 11-def, .., 2, 21-abc`
 997/// into `1-abc, 2, 10, 11-def, .., 21-abc`
 998#[derive(Debug, PartialEq, Eq)]
 999pub struct NumericPrefixWithSuffix<'a>(Option<u64>, &'a str);
1000
1001impl<'a> NumericPrefixWithSuffix<'a> {
1002    pub fn from_numeric_prefixed_str(str: &'a str) -> Self {
1003        let i = str.chars().take_while(|c| c.is_ascii_digit()).count();
1004        let (prefix, remainder) = str.split_at(i);
1005
1006        let prefix = prefix.parse().ok();
1007        Self(prefix, remainder)
1008    }
1009}
1010
1011/// When dealing with equality, we need to consider the case of the strings to achieve strict equality
1012/// to handle cases like "a" < "A" instead of "a" == "A".
1013impl Ord for NumericPrefixWithSuffix<'_> {
1014    fn cmp(&self, other: &Self) -> Ordering {
1015        match (self.0, other.0) {
1016            (None, None) => UniCase::new(self.1)
1017                .cmp(&UniCase::new(other.1))
1018                .then_with(|| self.1.cmp(other.1).reverse()),
1019            (None, Some(_)) => Ordering::Greater,
1020            (Some(_), None) => Ordering::Less,
1021            (Some(a), Some(b)) => a.cmp(&b).then_with(|| {
1022                UniCase::new(self.1)
1023                    .cmp(&UniCase::new(other.1))
1024                    .then_with(|| self.1.cmp(other.1).reverse())
1025            }),
1026        }
1027    }
1028}
1029
1030impl PartialOrd for NumericPrefixWithSuffix<'_> {
1031    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1032        Some(self.cmp(other))
1033    }
1034}
1035
1036/// Capitalizes the first character of a string.
1037///
1038/// This function takes a string slice as input and returns a new `String` with the first character
1039/// capitalized.
1040///
1041/// # Examples
1042///
1043/// ```
1044/// use util::capitalize;
1045///
1046/// assert_eq!(capitalize("hello"), "Hello");
1047/// assert_eq!(capitalize("WORLD"), "WORLD");
1048/// assert_eq!(capitalize(""), "");
1049/// ```
1050pub fn capitalize(str: &str) -> String {
1051    let mut chars = str.chars();
1052    match chars.next() {
1053        None => String::new(),
1054        Some(first_char) => first_char.to_uppercase().collect::<String>() + chars.as_str(),
1055    }
1056}
1057
1058fn emoji_regex() -> &'static Regex {
1059    static EMOJI_REGEX: LazyLock<Regex> =
1060        LazyLock::new(|| Regex::new("(\\p{Emoji}|\u{200D})").unwrap());
1061    &EMOJI_REGEX
1062}
1063
1064/// Returns true if the given string consists of emojis only.
1065/// E.g. "πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘§πŸ‘‹" will return true, but "πŸ‘‹!" will return false.
1066pub fn word_consists_of_emojis(s: &str) -> bool {
1067    let mut prev_end = 0;
1068    for capture in emoji_regex().find_iter(s) {
1069        if capture.start() != prev_end {
1070            return false;
1071        }
1072        prev_end = capture.end();
1073    }
1074    prev_end == s.len()
1075}
1076
1077/// Similar to `str::split`, but also provides byte-offset ranges of the results. Unlike
1078/// `str::split`, this is not generic on pattern types and does not return an `Iterator`.
1079pub fn split_str_with_ranges(s: &str, pat: impl Fn(char) -> bool) -> Vec<(Range<usize>, &str)> {
1080    let mut result = Vec::new();
1081    let mut start = 0;
1082
1083    for (i, ch) in s.char_indices() {
1084        if pat(ch) {
1085            if i > start {
1086                result.push((start..i, &s[start..i]));
1087            }
1088            start = i + ch.len_utf8();
1089        }
1090    }
1091
1092    if s.len() > start {
1093        result.push((start..s.len(), &s[start..s.len()]));
1094    }
1095
1096    result
1097}
1098
1099pub fn default<D: Default>() -> D {
1100    Default::default()
1101}
1102
1103pub fn get_system_shell() -> String {
1104    #[cfg(target_os = "windows")]
1105    {
1106        get_windows_system_shell()
1107    }
1108
1109    #[cfg(not(target_os = "windows"))]
1110    {
1111        std::env::var("SHELL").unwrap_or("/bin/sh".to_string())
1112    }
1113}
1114
1115pub fn get_default_system_shell() -> String {
1116    #[cfg(target_os = "windows")]
1117    {
1118        get_windows_system_shell()
1119    }
1120
1121    #[cfg(not(target_os = "windows"))]
1122    {
1123        "/bin/sh".to_string()
1124    }
1125}
1126
1127#[derive(Debug)]
1128pub enum ConnectionResult<O> {
1129    Timeout,
1130    ConnectionReset,
1131    Result(anyhow::Result<O>),
1132}
1133
1134impl<O> ConnectionResult<O> {
1135    pub fn into_response(self) -> anyhow::Result<O> {
1136        match self {
1137            ConnectionResult::Timeout => anyhow::bail!("Request timed out"),
1138            ConnectionResult::ConnectionReset => anyhow::bail!("Server reset the connection"),
1139            ConnectionResult::Result(r) => r,
1140        }
1141    }
1142}
1143
1144impl<O> From<anyhow::Result<O>> for ConnectionResult<O> {
1145    fn from(result: anyhow::Result<O>) -> Self {
1146        ConnectionResult::Result(result)
1147    }
1148}
1149
1150#[track_caller]
1151pub fn some_or_debug_panic<T>(option: Option<T>) -> Option<T> {
1152    #[cfg(debug_assertions)]
1153    if option.is_none() {
1154        panic!("Unexpected None");
1155    }
1156    option
1157}
1158
1159#[cfg(test)]
1160mod tests {
1161    use super::*;
1162
1163    #[test]
1164    fn test_extend_sorted() {
1165        let mut vec = vec![];
1166
1167        extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
1168        assert_eq!(vec, &[21, 17, 13, 8, 1]);
1169
1170        extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
1171        assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
1172
1173        extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
1174        assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
1175    }
1176
1177    #[test]
1178    fn test_truncate_to_bottom_n_sorted_by() {
1179        let mut vec: Vec<u32> = vec![5, 2, 3, 4, 1];
1180        truncate_to_bottom_n_sorted_by(&mut vec, 10, &u32::cmp);
1181        assert_eq!(vec, &[1, 2, 3, 4, 5]);
1182
1183        vec = vec![5, 2, 3, 4, 1];
1184        truncate_to_bottom_n_sorted_by(&mut vec, 5, &u32::cmp);
1185        assert_eq!(vec, &[1, 2, 3, 4, 5]);
1186
1187        vec = vec![5, 2, 3, 4, 1];
1188        truncate_to_bottom_n_sorted_by(&mut vec, 4, &u32::cmp);
1189        assert_eq!(vec, &[1, 2, 3, 4]);
1190
1191        vec = vec![5, 2, 3, 4, 1];
1192        truncate_to_bottom_n_sorted_by(&mut vec, 1, &u32::cmp);
1193        assert_eq!(vec, &[1]);
1194
1195        vec = vec![5, 2, 3, 4, 1];
1196        truncate_to_bottom_n_sorted_by(&mut vec, 0, &u32::cmp);
1197        assert!(vec.is_empty());
1198    }
1199
1200    #[test]
1201    fn test_iife() {
1202        fn option_returning_function() -> Option<()> {
1203            None
1204        }
1205
1206        let foo = maybe!({
1207            option_returning_function()?;
1208            Some(())
1209        });
1210
1211        assert_eq!(foo, None);
1212    }
1213
1214    #[test]
1215    fn test_truncate_and_trailoff() {
1216        assert_eq!(truncate_and_trailoff("", 5), "");
1217        assert_eq!(truncate_and_trailoff("aaaaaa", 7), "aaaaaa");
1218        assert_eq!(truncate_and_trailoff("aaaaaa", 6), "aaaaaa");
1219        assert_eq!(truncate_and_trailoff("aaaaaa", 5), "aaaaa…");
1220        assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
1221        assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
1222        assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
1223    }
1224
1225    #[test]
1226    fn test_truncate_and_remove_front() {
1227        assert_eq!(truncate_and_remove_front("", 5), "");
1228        assert_eq!(truncate_and_remove_front("aaaaaa", 7), "aaaaaa");
1229        assert_eq!(truncate_and_remove_front("aaaaaa", 6), "aaaaaa");
1230        assert_eq!(truncate_and_remove_front("aaaaaa", 5), "…aaaaa");
1231        assert_eq!(truncate_and_remove_front("èèèèèè", 7), "èèèèèè");
1232        assert_eq!(truncate_and_remove_front("èèèèèè", 6), "èèèèèè");
1233        assert_eq!(truncate_and_remove_front("èèèèèè", 5), "…èèèèè");
1234    }
1235
1236    #[test]
1237    fn test_numeric_prefix_str_method() {
1238        let target = "1a";
1239        assert_eq!(
1240            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1241            NumericPrefixWithSuffix(Some(1), "a")
1242        );
1243
1244        let target = "12ab";
1245        assert_eq!(
1246            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1247            NumericPrefixWithSuffix(Some(12), "ab")
1248        );
1249
1250        let target = "12_ab";
1251        assert_eq!(
1252            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1253            NumericPrefixWithSuffix(Some(12), "_ab")
1254        );
1255
1256        let target = "1_2ab";
1257        assert_eq!(
1258            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1259            NumericPrefixWithSuffix(Some(1), "_2ab")
1260        );
1261
1262        let target = "1.2";
1263        assert_eq!(
1264            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1265            NumericPrefixWithSuffix(Some(1), ".2")
1266        );
1267
1268        let target = "1.2_a";
1269        assert_eq!(
1270            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1271            NumericPrefixWithSuffix(Some(1), ".2_a")
1272        );
1273
1274        let target = "12.2_a";
1275        assert_eq!(
1276            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1277            NumericPrefixWithSuffix(Some(12), ".2_a")
1278        );
1279
1280        let target = "12a.2_a";
1281        assert_eq!(
1282            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1283            NumericPrefixWithSuffix(Some(12), "a.2_a")
1284        );
1285    }
1286
1287    #[test]
1288    fn test_numeric_prefix_with_suffix() {
1289        let mut sorted = vec!["1-abc", "10", "11def", "2", "21-abc"];
1290        sorted.sort_by_key(|s| NumericPrefixWithSuffix::from_numeric_prefixed_str(s));
1291        assert_eq!(sorted, ["1-abc", "2", "10", "11def", "21-abc"]);
1292
1293        for numeric_prefix_less in ["numeric_prefix_less", "aaa", "~β„’Β£"] {
1294            assert_eq!(
1295                NumericPrefixWithSuffix::from_numeric_prefixed_str(numeric_prefix_less),
1296                NumericPrefixWithSuffix(None, numeric_prefix_less),
1297                "String without numeric prefix `{numeric_prefix_less}` should not be converted into NumericPrefixWithSuffix"
1298            )
1299        }
1300    }
1301
1302    #[test]
1303    fn test_word_consists_of_emojis() {
1304        let words_to_test = vec![
1305            ("πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘§πŸ‘‹πŸ₯’", true),
1306            ("πŸ‘‹", true),
1307            ("!πŸ‘‹", false),
1308            ("πŸ‘‹!", false),
1309            ("πŸ‘‹ ", false),
1310            (" πŸ‘‹", false),
1311            ("Test", false),
1312        ];
1313
1314        for (text, expected_result) in words_to_test {
1315            assert_eq!(word_consists_of_emojis(text), expected_result);
1316        }
1317    }
1318
1319    #[test]
1320    fn test_truncate_lines_and_trailoff() {
1321        let text = r#"Line 1
1322Line 2
1323Line 3"#;
1324
1325        assert_eq!(
1326            truncate_lines_and_trailoff(text, 2),
1327            r#"Line 1
1328…"#
1329        );
1330
1331        assert_eq!(
1332            truncate_lines_and_trailoff(text, 3),
1333            r#"Line 1
1334Line 2
1335…"#
1336        );
1337
1338        assert_eq!(
1339            truncate_lines_and_trailoff(text, 4),
1340            r#"Line 1
1341Line 2
1342Line 3"#
1343        );
1344    }
1345
1346    #[test]
1347    fn test_expanded_and_wrapped_usize_range() {
1348        // Neither wrap
1349        assert_eq!(
1350            expanded_and_wrapped_usize_range(2..4, 1, 1, 8).collect::<Vec<usize>>(),
1351            (1..5).collect::<Vec<usize>>()
1352        );
1353        // Start wraps
1354        assert_eq!(
1355            expanded_and_wrapped_usize_range(2..4, 3, 1, 8).collect::<Vec<usize>>(),
1356            ((0..5).chain(7..8)).collect::<Vec<usize>>()
1357        );
1358        // Start wraps all the way around
1359        assert_eq!(
1360            expanded_and_wrapped_usize_range(2..4, 5, 1, 8).collect::<Vec<usize>>(),
1361            (0..8).collect::<Vec<usize>>()
1362        );
1363        // Start wraps all the way around and past 0
1364        assert_eq!(
1365            expanded_and_wrapped_usize_range(2..4, 10, 1, 8).collect::<Vec<usize>>(),
1366            (0..8).collect::<Vec<usize>>()
1367        );
1368        // End wraps
1369        assert_eq!(
1370            expanded_and_wrapped_usize_range(3..5, 1, 4, 8).collect::<Vec<usize>>(),
1371            (0..1).chain(2..8).collect::<Vec<usize>>()
1372        );
1373        // End wraps all the way around
1374        assert_eq!(
1375            expanded_and_wrapped_usize_range(3..5, 1, 5, 8).collect::<Vec<usize>>(),
1376            (0..8).collect::<Vec<usize>>()
1377        );
1378        // End wraps all the way around and past the end
1379        assert_eq!(
1380            expanded_and_wrapped_usize_range(3..5, 1, 10, 8).collect::<Vec<usize>>(),
1381            (0..8).collect::<Vec<usize>>()
1382        );
1383        // Both start and end wrap
1384        assert_eq!(
1385            expanded_and_wrapped_usize_range(3..5, 4, 4, 8).collect::<Vec<usize>>(),
1386            (0..8).collect::<Vec<usize>>()
1387        );
1388    }
1389
1390    #[test]
1391    fn test_wrapped_usize_outward_from() {
1392        // No wrapping
1393        assert_eq!(
1394            wrapped_usize_outward_from(4, 2, 2, 10).collect::<Vec<usize>>(),
1395            vec![4, 5, 3, 6, 2]
1396        );
1397        // Wrapping at end
1398        assert_eq!(
1399            wrapped_usize_outward_from(8, 2, 3, 10).collect::<Vec<usize>>(),
1400            vec![8, 9, 7, 0, 6, 1]
1401        );
1402        // Wrapping at start
1403        assert_eq!(
1404            wrapped_usize_outward_from(1, 3, 2, 10).collect::<Vec<usize>>(),
1405            vec![1, 2, 0, 3, 9, 8]
1406        );
1407        // All values wrap around
1408        assert_eq!(
1409            wrapped_usize_outward_from(5, 10, 10, 8).collect::<Vec<usize>>(),
1410            vec![5, 6, 4, 7, 3, 0, 2, 1]
1411        );
1412        // None before / after
1413        assert_eq!(
1414            wrapped_usize_outward_from(3, 0, 0, 8).collect::<Vec<usize>>(),
1415            vec![3]
1416        );
1417        // Starting point already wrapped
1418        assert_eq!(
1419            wrapped_usize_outward_from(15, 2, 2, 10).collect::<Vec<usize>>(),
1420            vec![5, 6, 4, 7, 3]
1421        );
1422        // wrap_length of 0
1423        assert_eq!(
1424            wrapped_usize_outward_from(4, 2, 2, 0).collect::<Vec<usize>>(),
1425            Vec::<usize>::new()
1426        );
1427    }
1428
1429    #[test]
1430    fn test_split_with_ranges() {
1431        let input = "hi";
1432        let result = split_str_with_ranges(input, |c| c == ' ');
1433
1434        assert_eq!(result.len(), 1);
1435        assert_eq!(result[0], (0..2, "hi"));
1436
1437        let input = "hΓ©lloπŸ¦€world";
1438        let result = split_str_with_ranges(input, |c| c == 'πŸ¦€');
1439
1440        assert_eq!(result.len(), 2);
1441        assert_eq!(result[0], (0..6, "hΓ©llo")); // 'Γ©' is 2 bytes
1442        assert_eq!(result[1], (10..15, "world")); // 'πŸ¦€' is 4 bytes
1443    }
1444}