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