util.rs

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