util.rs

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