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, the first segment of the file path is
 673    // the 'crates' folder, followed by the crate name.
 674    let target = file.split('/').nth(1);
 675
 676    log::logger().log(
 677        &log::Record::builder()
 678            .target(target.unwrap_or(""))
 679            .module_path(target)
 680            .args(format_args!("{:?}", error))
 681            .file(Some(caller.file()))
 682            .line(Some(caller.line()))
 683            .level(level)
 684            .build(),
 685    );
 686}
 687
 688pub fn log_err<E: std::fmt::Debug>(error: &E) {
 689    log_error_with_caller(*Location::caller(), error, log::Level::Warn);
 690}
 691
 692pub trait TryFutureExt {
 693    fn log_err(self) -> LogErrorFuture<Self>
 694    where
 695        Self: Sized;
 696
 697    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
 698    where
 699        Self: Sized;
 700
 701    fn warn_on_err(self) -> LogErrorFuture<Self>
 702    where
 703        Self: Sized;
 704    fn unwrap(self) -> UnwrapFuture<Self>
 705    where
 706        Self: Sized;
 707}
 708
 709impl<F, T, E> TryFutureExt for F
 710where
 711    F: Future<Output = Result<T, E>>,
 712    E: std::fmt::Debug,
 713{
 714    #[track_caller]
 715    fn log_err(self) -> LogErrorFuture<Self>
 716    where
 717        Self: Sized,
 718    {
 719        let location = Location::caller();
 720        LogErrorFuture(self, log::Level::Error, *location)
 721    }
 722
 723    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
 724    where
 725        Self: Sized,
 726    {
 727        LogErrorFuture(self, log::Level::Error, location)
 728    }
 729
 730    #[track_caller]
 731    fn warn_on_err(self) -> LogErrorFuture<Self>
 732    where
 733        Self: Sized,
 734    {
 735        let location = Location::caller();
 736        LogErrorFuture(self, log::Level::Warn, *location)
 737    }
 738
 739    fn unwrap(self) -> UnwrapFuture<Self>
 740    where
 741        Self: Sized,
 742    {
 743        UnwrapFuture(self)
 744    }
 745}
 746
 747#[must_use]
 748pub struct LogErrorFuture<F>(F, log::Level, core::panic::Location<'static>);
 749
 750impl<F, T, E> Future for LogErrorFuture<F>
 751where
 752    F: Future<Output = Result<T, E>>,
 753    E: std::fmt::Debug,
 754{
 755    type Output = Option<T>;
 756
 757    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
 758        let level = self.1;
 759        let location = self.2;
 760        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
 761        match inner.poll(cx) {
 762            Poll::Ready(output) => Poll::Ready(match output {
 763                Ok(output) => Some(output),
 764                Err(error) => {
 765                    log_error_with_caller(location, error, level);
 766                    None
 767                }
 768            }),
 769            Poll::Pending => Poll::Pending,
 770        }
 771    }
 772}
 773
 774pub struct UnwrapFuture<F>(F);
 775
 776impl<F, T, E> Future for UnwrapFuture<F>
 777where
 778    F: Future<Output = Result<T, E>>,
 779    E: std::fmt::Debug,
 780{
 781    type Output = T;
 782
 783    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
 784        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
 785        match inner.poll(cx) {
 786            Poll::Ready(result) => Poll::Ready(result.unwrap()),
 787            Poll::Pending => Poll::Pending,
 788        }
 789    }
 790}
 791
 792pub struct Deferred<F: FnOnce()>(Option<F>);
 793
 794impl<F: FnOnce()> Deferred<F> {
 795    /// Drop without running the deferred function.
 796    pub fn abort(mut self) {
 797        self.0.take();
 798    }
 799}
 800
 801impl<F: FnOnce()> Drop for Deferred<F> {
 802    fn drop(&mut self) {
 803        if let Some(f) = self.0.take() {
 804            f()
 805        }
 806    }
 807}
 808
 809/// Run the given function when the returned value is dropped (unless it's cancelled).
 810#[must_use]
 811pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
 812    Deferred(Some(f))
 813}
 814
 815#[cfg(any(test, feature = "test-support"))]
 816mod rng {
 817    use rand::{Rng, seq::SliceRandom};
 818    pub struct RandomCharIter<T: Rng> {
 819        rng: T,
 820        simple_text: bool,
 821    }
 822
 823    impl<T: Rng> RandomCharIter<T> {
 824        pub fn new(rng: T) -> Self {
 825            Self {
 826                rng,
 827                simple_text: std::env::var("SIMPLE_TEXT").map_or(false, |v| !v.is_empty()),
 828            }
 829        }
 830
 831        pub fn with_simple_text(mut self) -> Self {
 832            self.simple_text = true;
 833            self
 834        }
 835    }
 836
 837    impl<T: Rng> Iterator for RandomCharIter<T> {
 838        type Item = char;
 839
 840        fn next(&mut self) -> Option<Self::Item> {
 841            if self.simple_text {
 842                return if self.rng.gen_range(0..100) < 5 {
 843                    Some('\n')
 844                } else {
 845                    Some(self.rng.gen_range(b'a'..b'z' + 1).into())
 846                };
 847            }
 848
 849            match self.rng.gen_range(0..100) {
 850                // whitespace
 851                0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
 852                // two-byte greek letters
 853                20..=32 => char::from_u32(self.rng.gen_range(('Ξ±' as u32)..('Ο‰' as u32 + 1))),
 854                // // three-byte characters
 855                33..=45 => ['βœ‹', 'βœ…', '❌', '❎', '⭐']
 856                    .choose(&mut self.rng)
 857                    .copied(),
 858                // // four-byte characters
 859                46..=58 => ['🍐', 'πŸ€', 'πŸ—', 'πŸŽ‰'].choose(&mut self.rng).copied(),
 860                // ascii letters
 861                _ => Some(self.rng.gen_range(b'a'..b'z' + 1).into()),
 862            }
 863        }
 864    }
 865}
 866#[cfg(any(test, feature = "test-support"))]
 867pub use rng::RandomCharIter;
 868
 869/// Get an embedded file as a string.
 870pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
 871    match A::get(path).expect(path).data {
 872        Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
 873        Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
 874    }
 875}
 876
 877/// Expands to an immediately-invoked function expression. Good for using the ? operator
 878/// in functions which do not return an Option or Result.
 879///
 880/// Accepts a normal block, an async block, or an async move block.
 881#[macro_export]
 882macro_rules! maybe {
 883    ($block:block) => {
 884        (|| $block)()
 885    };
 886    (async $block:block) => {
 887        (|| async $block)()
 888    };
 889    (async move $block:block) => {
 890        (|| async move $block)()
 891    };
 892}
 893
 894pub trait RangeExt<T> {
 895    fn sorted(&self) -> Self;
 896    fn to_inclusive(&self) -> RangeInclusive<T>;
 897    fn overlaps(&self, other: &Range<T>) -> bool;
 898    fn contains_inclusive(&self, other: &Range<T>) -> bool;
 899}
 900
 901impl<T: Ord + Clone> RangeExt<T> for Range<T> {
 902    fn sorted(&self) -> Self {
 903        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
 904    }
 905
 906    fn to_inclusive(&self) -> RangeInclusive<T> {
 907        self.start.clone()..=self.end.clone()
 908    }
 909
 910    fn overlaps(&self, other: &Range<T>) -> bool {
 911        self.start < other.end && other.start < self.end
 912    }
 913
 914    fn contains_inclusive(&self, other: &Range<T>) -> bool {
 915        self.start <= other.start && other.end <= self.end
 916    }
 917}
 918
 919impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
 920    fn sorted(&self) -> Self {
 921        cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
 922    }
 923
 924    fn to_inclusive(&self) -> RangeInclusive<T> {
 925        self.clone()
 926    }
 927
 928    fn overlaps(&self, other: &Range<T>) -> bool {
 929        self.start() < &other.end && &other.start <= self.end()
 930    }
 931
 932    fn contains_inclusive(&self, other: &Range<T>) -> bool {
 933        self.start() <= &other.start && &other.end <= self.end()
 934    }
 935}
 936
 937/// A way to sort strings with starting numbers numerically first, falling back to alphanumeric one,
 938/// case-insensitive.
 939///
 940/// This is useful for turning regular alphanumerically sorted sequences as `1-abc, 10, 11-def, .., 2, 21-abc`
 941/// into `1-abc, 2, 10, 11-def, .., 21-abc`
 942#[derive(Debug, PartialEq, Eq)]
 943pub struct NumericPrefixWithSuffix<'a>(Option<u64>, &'a str);
 944
 945impl<'a> NumericPrefixWithSuffix<'a> {
 946    pub fn from_numeric_prefixed_str(str: &'a str) -> Self {
 947        let i = str.chars().take_while(|c| c.is_ascii_digit()).count();
 948        let (prefix, remainder) = str.split_at(i);
 949
 950        let prefix = prefix.parse().ok();
 951        Self(prefix, remainder)
 952    }
 953}
 954
 955/// When dealing with equality, we need to consider the case of the strings to achieve strict equality
 956/// to handle cases like "a" < "A" instead of "a" == "A".
 957impl Ord for NumericPrefixWithSuffix<'_> {
 958    fn cmp(&self, other: &Self) -> Ordering {
 959        match (self.0, other.0) {
 960            (None, None) => UniCase::new(self.1)
 961                .cmp(&UniCase::new(other.1))
 962                .then_with(|| self.1.cmp(other.1).reverse()),
 963            (None, Some(_)) => Ordering::Greater,
 964            (Some(_), None) => Ordering::Less,
 965            (Some(a), Some(b)) => a.cmp(&b).then_with(|| {
 966                UniCase::new(self.1)
 967                    .cmp(&UniCase::new(other.1))
 968                    .then_with(|| self.1.cmp(other.1).reverse())
 969            }),
 970        }
 971    }
 972}
 973
 974impl PartialOrd for NumericPrefixWithSuffix<'_> {
 975    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
 976        Some(self.cmp(other))
 977    }
 978}
 979
 980/// Capitalizes the first character of a string.
 981///
 982/// This function takes a string slice as input and returns a new `String` with the first character
 983/// capitalized.
 984///
 985/// # Examples
 986///
 987/// ```
 988/// use util::capitalize;
 989///
 990/// assert_eq!(capitalize("hello"), "Hello");
 991/// assert_eq!(capitalize("WORLD"), "WORLD");
 992/// assert_eq!(capitalize(""), "");
 993/// ```
 994pub fn capitalize(str: &str) -> String {
 995    let mut chars = str.chars();
 996    match chars.next() {
 997        None => String::new(),
 998        Some(first_char) => first_char.to_uppercase().collect::<String>() + chars.as_str(),
 999    }
1000}
1001
1002fn emoji_regex() -> &'static Regex {
1003    static EMOJI_REGEX: LazyLock<Regex> =
1004        LazyLock::new(|| Regex::new("(\\p{Emoji}|\u{200D})").unwrap());
1005    &EMOJI_REGEX
1006}
1007
1008/// Returns true if the given string consists of emojis only.
1009/// E.g. "πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘§πŸ‘‹" will return true, but "πŸ‘‹!" will return false.
1010pub fn word_consists_of_emojis(s: &str) -> bool {
1011    let mut prev_end = 0;
1012    for capture in emoji_regex().find_iter(s) {
1013        if capture.start() != prev_end {
1014            return false;
1015        }
1016        prev_end = capture.end();
1017    }
1018    prev_end == s.len()
1019}
1020
1021/// Similar to `str::split`, but also provides byte-offset ranges of the results. Unlike
1022/// `str::split`, this is not generic on pattern types and does not return an `Iterator`.
1023pub fn split_str_with_ranges(s: &str, pat: impl Fn(char) -> bool) -> Vec<(Range<usize>, &str)> {
1024    let mut result = Vec::new();
1025    let mut start = 0;
1026
1027    for (i, ch) in s.char_indices() {
1028        if pat(ch) {
1029            if i > start {
1030                result.push((start..i, &s[start..i]));
1031            }
1032            start = i + ch.len_utf8();
1033        }
1034    }
1035
1036    if s.len() > start {
1037        result.push((start..s.len(), &s[start..s.len()]));
1038    }
1039
1040    result
1041}
1042
1043pub fn default<D: Default>() -> D {
1044    Default::default()
1045}
1046
1047pub fn get_system_shell() -> String {
1048    #[cfg(target_os = "windows")]
1049    {
1050        get_windows_system_shell()
1051    }
1052
1053    #[cfg(not(target_os = "windows"))]
1054    {
1055        std::env::var("SHELL").unwrap_or("/bin/sh".to_string())
1056    }
1057}
1058
1059#[derive(Debug)]
1060pub enum ConnectionResult<O> {
1061    Timeout,
1062    ConnectionReset,
1063    Result(anyhow::Result<O>),
1064}
1065
1066impl<O> ConnectionResult<O> {
1067    pub fn into_response(self) -> anyhow::Result<O> {
1068        match self {
1069            ConnectionResult::Timeout => anyhow::bail!("Request timed out"),
1070            ConnectionResult::ConnectionReset => anyhow::bail!("Server reset the connection"),
1071            ConnectionResult::Result(r) => r,
1072        }
1073    }
1074}
1075
1076impl<O> From<anyhow::Result<O>> for ConnectionResult<O> {
1077    fn from(result: anyhow::Result<O>) -> Self {
1078        ConnectionResult::Result(result)
1079    }
1080}
1081
1082#[cfg(test)]
1083mod tests {
1084    use super::*;
1085
1086    #[test]
1087    fn test_extend_sorted() {
1088        let mut vec = vec![];
1089
1090        extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
1091        assert_eq!(vec, &[21, 17, 13, 8, 1]);
1092
1093        extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
1094        assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
1095
1096        extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
1097        assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
1098    }
1099
1100    #[test]
1101    fn test_truncate_to_bottom_n_sorted_by() {
1102        let mut vec: Vec<u32> = vec![5, 2, 3, 4, 1];
1103        truncate_to_bottom_n_sorted_by(&mut vec, 10, &u32::cmp);
1104        assert_eq!(vec, &[1, 2, 3, 4, 5]);
1105
1106        vec = vec![5, 2, 3, 4, 1];
1107        truncate_to_bottom_n_sorted_by(&mut vec, 5, &u32::cmp);
1108        assert_eq!(vec, &[1, 2, 3, 4, 5]);
1109
1110        vec = vec![5, 2, 3, 4, 1];
1111        truncate_to_bottom_n_sorted_by(&mut vec, 4, &u32::cmp);
1112        assert_eq!(vec, &[1, 2, 3, 4]);
1113
1114        vec = vec![5, 2, 3, 4, 1];
1115        truncate_to_bottom_n_sorted_by(&mut vec, 1, &u32::cmp);
1116        assert_eq!(vec, &[1]);
1117
1118        vec = vec![5, 2, 3, 4, 1];
1119        truncate_to_bottom_n_sorted_by(&mut vec, 0, &u32::cmp);
1120        assert!(vec.is_empty());
1121    }
1122
1123    #[test]
1124    fn test_iife() {
1125        fn option_returning_function() -> Option<()> {
1126            None
1127        }
1128
1129        let foo = maybe!({
1130            option_returning_function()?;
1131            Some(())
1132        });
1133
1134        assert_eq!(foo, None);
1135    }
1136
1137    #[test]
1138    fn test_truncate_and_trailoff() {
1139        assert_eq!(truncate_and_trailoff("", 5), "");
1140        assert_eq!(truncate_and_trailoff("aaaaaa", 7), "aaaaaa");
1141        assert_eq!(truncate_and_trailoff("aaaaaa", 6), "aaaaaa");
1142        assert_eq!(truncate_and_trailoff("aaaaaa", 5), "aaaaa…");
1143        assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
1144        assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
1145        assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
1146    }
1147
1148    #[test]
1149    fn test_truncate_and_remove_front() {
1150        assert_eq!(truncate_and_remove_front("", 5), "");
1151        assert_eq!(truncate_and_remove_front("aaaaaa", 7), "aaaaaa");
1152        assert_eq!(truncate_and_remove_front("aaaaaa", 6), "aaaaaa");
1153        assert_eq!(truncate_and_remove_front("aaaaaa", 5), "…aaaaa");
1154        assert_eq!(truncate_and_remove_front("èèèèèè", 7), "èèèèèè");
1155        assert_eq!(truncate_and_remove_front("èèèèèè", 6), "èèèèèè");
1156        assert_eq!(truncate_and_remove_front("èèèèèè", 5), "…èèèèè");
1157    }
1158
1159    #[test]
1160    fn test_numeric_prefix_str_method() {
1161        let target = "1a";
1162        assert_eq!(
1163            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1164            NumericPrefixWithSuffix(Some(1), "a")
1165        );
1166
1167        let target = "12ab";
1168        assert_eq!(
1169            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1170            NumericPrefixWithSuffix(Some(12), "ab")
1171        );
1172
1173        let target = "12_ab";
1174        assert_eq!(
1175            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1176            NumericPrefixWithSuffix(Some(12), "_ab")
1177        );
1178
1179        let target = "1_2ab";
1180        assert_eq!(
1181            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1182            NumericPrefixWithSuffix(Some(1), "_2ab")
1183        );
1184
1185        let target = "1.2";
1186        assert_eq!(
1187            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1188            NumericPrefixWithSuffix(Some(1), ".2")
1189        );
1190
1191        let target = "1.2_a";
1192        assert_eq!(
1193            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1194            NumericPrefixWithSuffix(Some(1), ".2_a")
1195        );
1196
1197        let target = "12.2_a";
1198        assert_eq!(
1199            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1200            NumericPrefixWithSuffix(Some(12), ".2_a")
1201        );
1202
1203        let target = "12a.2_a";
1204        assert_eq!(
1205            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1206            NumericPrefixWithSuffix(Some(12), "a.2_a")
1207        );
1208    }
1209
1210    #[test]
1211    fn test_numeric_prefix_with_suffix() {
1212        let mut sorted = vec!["1-abc", "10", "11def", "2", "21-abc"];
1213        sorted.sort_by_key(|s| NumericPrefixWithSuffix::from_numeric_prefixed_str(s));
1214        assert_eq!(sorted, ["1-abc", "2", "10", "11def", "21-abc"]);
1215
1216        for numeric_prefix_less in ["numeric_prefix_less", "aaa", "~β„’Β£"] {
1217            assert_eq!(
1218                NumericPrefixWithSuffix::from_numeric_prefixed_str(numeric_prefix_less),
1219                NumericPrefixWithSuffix(None, numeric_prefix_less),
1220                "String without numeric prefix `{numeric_prefix_less}` should not be converted into NumericPrefixWithSuffix"
1221            )
1222        }
1223    }
1224
1225    #[test]
1226    fn test_word_consists_of_emojis() {
1227        let words_to_test = vec![
1228            ("πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘§πŸ‘‹πŸ₯’", true),
1229            ("πŸ‘‹", true),
1230            ("!πŸ‘‹", false),
1231            ("πŸ‘‹!", false),
1232            ("πŸ‘‹ ", false),
1233            (" πŸ‘‹", false),
1234            ("Test", false),
1235        ];
1236
1237        for (text, expected_result) in words_to_test {
1238            assert_eq!(word_consists_of_emojis(text), expected_result);
1239        }
1240    }
1241
1242    #[test]
1243    fn test_truncate_lines_and_trailoff() {
1244        let text = r#"Line 1
1245Line 2
1246Line 3"#;
1247
1248        assert_eq!(
1249            truncate_lines_and_trailoff(text, 2),
1250            r#"Line 1
1251…"#
1252        );
1253
1254        assert_eq!(
1255            truncate_lines_and_trailoff(text, 3),
1256            r#"Line 1
1257Line 2
1258…"#
1259        );
1260
1261        assert_eq!(
1262            truncate_lines_and_trailoff(text, 4),
1263            r#"Line 1
1264Line 2
1265Line 3"#
1266        );
1267    }
1268
1269    #[test]
1270    fn test_expanded_and_wrapped_usize_range() {
1271        // Neither wrap
1272        assert_eq!(
1273            expanded_and_wrapped_usize_range(2..4, 1, 1, 8).collect::<Vec<usize>>(),
1274            (1..5).collect::<Vec<usize>>()
1275        );
1276        // Start wraps
1277        assert_eq!(
1278            expanded_and_wrapped_usize_range(2..4, 3, 1, 8).collect::<Vec<usize>>(),
1279            ((0..5).chain(7..8)).collect::<Vec<usize>>()
1280        );
1281        // Start wraps all the way around
1282        assert_eq!(
1283            expanded_and_wrapped_usize_range(2..4, 5, 1, 8).collect::<Vec<usize>>(),
1284            (0..8).collect::<Vec<usize>>()
1285        );
1286        // Start wraps all the way around and past 0
1287        assert_eq!(
1288            expanded_and_wrapped_usize_range(2..4, 10, 1, 8).collect::<Vec<usize>>(),
1289            (0..8).collect::<Vec<usize>>()
1290        );
1291        // End wraps
1292        assert_eq!(
1293            expanded_and_wrapped_usize_range(3..5, 1, 4, 8).collect::<Vec<usize>>(),
1294            (0..1).chain(2..8).collect::<Vec<usize>>()
1295        );
1296        // End wraps all the way around
1297        assert_eq!(
1298            expanded_and_wrapped_usize_range(3..5, 1, 5, 8).collect::<Vec<usize>>(),
1299            (0..8).collect::<Vec<usize>>()
1300        );
1301        // End wraps all the way around and past the end
1302        assert_eq!(
1303            expanded_and_wrapped_usize_range(3..5, 1, 10, 8).collect::<Vec<usize>>(),
1304            (0..8).collect::<Vec<usize>>()
1305        );
1306        // Both start and end wrap
1307        assert_eq!(
1308            expanded_and_wrapped_usize_range(3..5, 4, 4, 8).collect::<Vec<usize>>(),
1309            (0..8).collect::<Vec<usize>>()
1310        );
1311    }
1312
1313    #[test]
1314    fn test_wrapped_usize_outward_from() {
1315        // No wrapping
1316        assert_eq!(
1317            wrapped_usize_outward_from(4, 2, 2, 10).collect::<Vec<usize>>(),
1318            vec![4, 5, 3, 6, 2]
1319        );
1320        // Wrapping at end
1321        assert_eq!(
1322            wrapped_usize_outward_from(8, 2, 3, 10).collect::<Vec<usize>>(),
1323            vec![8, 9, 7, 0, 6, 1]
1324        );
1325        // Wrapping at start
1326        assert_eq!(
1327            wrapped_usize_outward_from(1, 3, 2, 10).collect::<Vec<usize>>(),
1328            vec![1, 2, 0, 3, 9, 8]
1329        );
1330        // All values wrap around
1331        assert_eq!(
1332            wrapped_usize_outward_from(5, 10, 10, 8).collect::<Vec<usize>>(),
1333            vec![5, 6, 4, 7, 3, 0, 2, 1]
1334        );
1335        // None before / after
1336        assert_eq!(
1337            wrapped_usize_outward_from(3, 0, 0, 8).collect::<Vec<usize>>(),
1338            vec![3]
1339        );
1340        // Starting point already wrapped
1341        assert_eq!(
1342            wrapped_usize_outward_from(15, 2, 2, 10).collect::<Vec<usize>>(),
1343            vec![5, 6, 4, 7, 3]
1344        );
1345        // wrap_length of 0
1346        assert_eq!(
1347            wrapped_usize_outward_from(4, 2, 2, 0).collect::<Vec<usize>>(),
1348            Vec::<usize>::new()
1349        );
1350    }
1351
1352    #[test]
1353    fn test_split_with_ranges() {
1354        let input = "hi";
1355        let result = split_str_with_ranges(input, |c| c == ' ');
1356
1357        assert_eq!(result.len(), 1);
1358        assert_eq!(result[0], (0..2, "hi"));
1359
1360        let input = "hΓ©lloπŸ¦€world";
1361        let result = split_str_with_ranges(input, |c| c == 'πŸ¦€');
1362
1363        assert_eq!(result.len(), 2);
1364        assert_eq!(result[0], (0..6, "hΓ©llo")); // 'Γ©' is 2 bytes
1365        assert_eq!(result[1], (10..15, "world")); // 'πŸ¦€' is 4 bytes
1366    }
1367}