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 let shell_cmd = format!(
325 "{}printf '%s' {marker}; /usr/bin/env;",
326 shell_cmd_prefix.as_deref().unwrap_or("")
327 );
328
329 let output = set_pre_exec_to_start_new_session(
330 std::process::Command::new(&shell).args(["-l", "-i", "-c", &shell_cmd]),
331 )
332 .output()
333 .context("failed to spawn login shell to source login environment variables")?;
334 if !output.status.success() {
335 Err(anyhow!("login shell exited with error"))?;
336 }
337
338 let stdout = String::from_utf8_lossy(&output.stdout);
339
340 if let Some(env_output_start) = stdout.find(marker) {
341 let env_output = &stdout[env_output_start + marker.len()..];
342
343 parse_env_output(env_output, |key, value| unsafe { env::set_var(key, value) });
344
345 log::info!(
346 "set environment variables from shell:{}, path:{}",
347 shell,
348 env::var("PATH").unwrap_or_default(),
349 );
350 }
351
352 Ok(())
353}
354
355/// Configures the process to start a new session, to prevent interactive shells from taking control
356/// of the terminal.
357///
358/// For more details: https://registerspill.thorstenball.com/p/how-to-lose-control-of-your-shell
359pub fn set_pre_exec_to_start_new_session(
360 command: &mut std::process::Command,
361) -> &mut std::process::Command {
362 // safety: code in pre_exec should be signal safe.
363 // https://man7.org/linux/man-pages/man7/signal-safety.7.html
364 #[cfg(not(target_os = "windows"))]
365 unsafe {
366 use std::os::unix::process::CommandExt;
367 command.pre_exec(|| {
368 libc::setsid();
369 Ok(())
370 });
371 };
372 command
373}
374
375/// Parse the result of calling `usr/bin/env` with no arguments
376pub fn parse_env_output(env: &str, mut f: impl FnMut(String, String)) {
377 let mut current_key: Option<String> = None;
378 let mut current_value: Option<String> = None;
379
380 for line in env.split_terminator('\n') {
381 if let Some(separator_index) = line.find('=') {
382 if !line[..separator_index].is_empty() {
383 if let Some((key, value)) = Option::zip(current_key.take(), current_value.take()) {
384 f(key, value)
385 }
386 current_key = Some(line[..separator_index].to_string());
387 current_value = Some(line[separator_index + 1..].to_string());
388 continue;
389 };
390 }
391 if let Some(value) = current_value.as_mut() {
392 value.push('\n');
393 value.push_str(line);
394 }
395 }
396 if let Some((key, value)) = Option::zip(current_key.take(), current_value.take()) {
397 f(key, value)
398 }
399}
400
401pub fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
402 use serde_json::Value;
403
404 match (source, target) {
405 (Value::Object(source), Value::Object(target)) => {
406 for (key, value) in source {
407 if let Some(target) = target.get_mut(&key) {
408 merge_json_value_into(value, target);
409 } else {
410 target.insert(key, value);
411 }
412 }
413 }
414
415 (Value::Array(source), Value::Array(target)) => {
416 for value in source {
417 target.push(value);
418 }
419 }
420
421 (source, target) => *target = source,
422 }
423}
424
425pub fn merge_non_null_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
426 use serde_json::Value;
427 if let Value::Object(source_object) = source {
428 let target_object = if let Value::Object(target) = target {
429 target
430 } else {
431 *target = Value::Object(Default::default());
432 target.as_object_mut().unwrap()
433 };
434 for (key, value) in source_object {
435 if let Some(target) = target_object.get_mut(&key) {
436 merge_non_null_json_value_into(value, target);
437 } else if !value.is_null() {
438 target_object.insert(key, value);
439 }
440 }
441 } else if !source.is_null() {
442 *target = source
443 }
444}
445
446pub fn measure<R>(label: &str, f: impl FnOnce() -> R) -> R {
447 static ZED_MEASUREMENTS: OnceLock<bool> = OnceLock::new();
448 let zed_measurements = ZED_MEASUREMENTS.get_or_init(|| {
449 env::var("ZED_MEASUREMENTS")
450 .map(|measurements| measurements == "1" || measurements == "true")
451 .unwrap_or(false)
452 });
453
454 if *zed_measurements {
455 let start = Instant::now();
456 let result = f();
457 let elapsed = start.elapsed();
458 eprintln!("{}: {:?}", label, elapsed);
459 result
460 } else {
461 f()
462 }
463}
464
465pub fn iterate_expanded_and_wrapped_usize_range(
466 range: Range<usize>,
467 additional_before: usize,
468 additional_after: usize,
469 wrap_length: usize,
470) -> impl Iterator<Item = usize> {
471 let start_wraps = range.start < additional_before;
472 let end_wraps = wrap_length < range.end + additional_after;
473 if start_wraps && end_wraps {
474 Either::Left(0..wrap_length)
475 } else if start_wraps {
476 let wrapped_start = (range.start + wrap_length).saturating_sub(additional_before);
477 if wrapped_start <= range.end {
478 Either::Left(0..wrap_length)
479 } else {
480 Either::Right((0..range.end + additional_after).chain(wrapped_start..wrap_length))
481 }
482 } else if end_wraps {
483 let wrapped_end = range.end + additional_after - wrap_length;
484 if range.start <= wrapped_end {
485 Either::Left(0..wrap_length)
486 } else {
487 Either::Right((0..wrapped_end).chain(range.start - additional_before..wrap_length))
488 }
489 } else {
490 Either::Left((range.start - additional_before)..(range.end + additional_after))
491 }
492}
493
494#[cfg(target_os = "windows")]
495pub fn get_windows_system_shell() -> String {
496 use std::path::PathBuf;
497
498 fn find_pwsh_in_programfiles(find_alternate: bool, find_preview: bool) -> Option<PathBuf> {
499 #[cfg(target_pointer_width = "64")]
500 let env_var = if find_alternate {
501 "ProgramFiles(x86)"
502 } else {
503 "ProgramFiles"
504 };
505
506 #[cfg(target_pointer_width = "32")]
507 let env_var = if find_alternate {
508 "ProgramW6432"
509 } else {
510 "ProgramFiles"
511 };
512
513 let install_base_dir = PathBuf::from(std::env::var_os(env_var)?).join("PowerShell");
514 install_base_dir
515 .read_dir()
516 .ok()?
517 .filter_map(Result::ok)
518 .filter(|entry| matches!(entry.file_type(), Ok(ft) if ft.is_dir()))
519 .filter_map(|entry| {
520 let dir_name = entry.file_name();
521 let dir_name = dir_name.to_string_lossy();
522
523 let version = if find_preview {
524 let dash_index = dir_name.find('-')?;
525 if &dir_name[dash_index + 1..] != "preview" {
526 return None;
527 };
528 dir_name[..dash_index].parse::<u32>().ok()?
529 } else {
530 dir_name.parse::<u32>().ok()?
531 };
532
533 let exe_path = entry.path().join("pwsh.exe");
534 if exe_path.exists() {
535 Some((version, exe_path))
536 } else {
537 None
538 }
539 })
540 .max_by_key(|(version, _)| *version)
541 .map(|(_, path)| path)
542 }
543
544 fn find_pwsh_in_msix(find_preview: bool) -> Option<PathBuf> {
545 let msix_app_dir =
546 PathBuf::from(std::env::var_os("LOCALAPPDATA")?).join("Microsoft\\WindowsApps");
547 if !msix_app_dir.exists() {
548 return None;
549 }
550
551 let prefix = if find_preview {
552 "Microsoft.PowerShellPreview_"
553 } else {
554 "Microsoft.PowerShell_"
555 };
556 msix_app_dir
557 .read_dir()
558 .ok()?
559 .filter_map(|entry| {
560 let entry = entry.ok()?;
561 if !matches!(entry.file_type(), Ok(ft) if ft.is_dir()) {
562 return None;
563 }
564
565 if !entry.file_name().to_string_lossy().starts_with(prefix) {
566 return None;
567 }
568
569 let exe_path = entry.path().join("pwsh.exe");
570 exe_path.exists().then_some(exe_path)
571 })
572 .next()
573 }
574
575 fn find_pwsh_in_scoop() -> Option<PathBuf> {
576 let pwsh_exe =
577 PathBuf::from(std::env::var_os("USERPROFILE")?).join("scoop\\shims\\pwsh.exe");
578 pwsh_exe.exists().then_some(pwsh_exe)
579 }
580
581 static SYSTEM_SHELL: LazyLock<String> = LazyLock::new(|| {
582 find_pwsh_in_programfiles(false, false)
583 .or_else(|| find_pwsh_in_programfiles(true, false))
584 .or_else(|| find_pwsh_in_msix(false))
585 .or_else(|| find_pwsh_in_programfiles(false, true))
586 .or_else(|| find_pwsh_in_msix(true))
587 .or_else(|| find_pwsh_in_programfiles(true, true))
588 .or_else(find_pwsh_in_scoop)
589 .map(|p| p.to_string_lossy().to_string())
590 .unwrap_or("powershell.exe".to_string())
591 });
592
593 (*SYSTEM_SHELL).clone()
594}
595
596pub trait ResultExt<E> {
597 type Ok;
598
599 fn log_err(self) -> Option<Self::Ok>;
600 /// Assert that this result should never be an error in development or tests.
601 fn debug_assert_ok(self, reason: &str) -> Self;
602 fn warn_on_err(self) -> Option<Self::Ok>;
603 fn log_with_level(self, level: log::Level) -> Option<Self::Ok>;
604 fn anyhow(self) -> anyhow::Result<Self::Ok>
605 where
606 E: Into<anyhow::Error>;
607}
608
609impl<T, E> ResultExt<E> for Result<T, E>
610where
611 E: std::fmt::Debug,
612{
613 type Ok = T;
614
615 #[track_caller]
616 fn log_err(self) -> Option<T> {
617 self.log_with_level(log::Level::Error)
618 }
619
620 #[track_caller]
621 fn debug_assert_ok(self, reason: &str) -> Self {
622 if let Err(error) = &self {
623 debug_panic!("{reason} - {error:?}");
624 }
625 self
626 }
627
628 #[track_caller]
629 fn warn_on_err(self) -> Option<T> {
630 self.log_with_level(log::Level::Warn)
631 }
632
633 #[track_caller]
634 fn log_with_level(self, level: log::Level) -> Option<T> {
635 match self {
636 Ok(value) => Some(value),
637 Err(error) => {
638 log_error_with_caller(*Location::caller(), error, level);
639 None
640 }
641 }
642 }
643
644 fn anyhow(self) -> anyhow::Result<T>
645 where
646 E: Into<anyhow::Error>,
647 {
648 self.map_err(Into::into)
649 }
650}
651
652fn log_error_with_caller<E>(caller: core::panic::Location<'_>, error: E, level: log::Level)
653where
654 E: std::fmt::Debug,
655{
656 #[cfg(not(target_os = "windows"))]
657 let file = caller.file();
658 #[cfg(target_os = "windows")]
659 let file = caller.file().replace('\\', "/");
660 // In this codebase, the first segment of the file path is
661 // the 'crates' folder, followed by the crate name.
662 let target = file.split('/').nth(1);
663
664 log::logger().log(
665 &log::Record::builder()
666 .target(target.unwrap_or(""))
667 .module_path(target)
668 .args(format_args!("{:?}", error))
669 .file(Some(caller.file()))
670 .line(Some(caller.line()))
671 .level(level)
672 .build(),
673 );
674}
675
676pub fn log_err<E: std::fmt::Debug>(error: &E) {
677 log_error_with_caller(*Location::caller(), error, log::Level::Warn);
678}
679
680pub trait TryFutureExt {
681 fn log_err(self) -> LogErrorFuture<Self>
682 where
683 Self: Sized;
684
685 fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
686 where
687 Self: Sized;
688
689 fn warn_on_err(self) -> LogErrorFuture<Self>
690 where
691 Self: Sized;
692 fn unwrap(self) -> UnwrapFuture<Self>
693 where
694 Self: Sized;
695}
696
697impl<F, T, E> TryFutureExt for F
698where
699 F: Future<Output = Result<T, E>>,
700 E: std::fmt::Debug,
701{
702 #[track_caller]
703 fn log_err(self) -> LogErrorFuture<Self>
704 where
705 Self: Sized,
706 {
707 let location = Location::caller();
708 LogErrorFuture(self, log::Level::Error, *location)
709 }
710
711 fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
712 where
713 Self: Sized,
714 {
715 LogErrorFuture(self, log::Level::Error, location)
716 }
717
718 #[track_caller]
719 fn warn_on_err(self) -> LogErrorFuture<Self>
720 where
721 Self: Sized,
722 {
723 let location = Location::caller();
724 LogErrorFuture(self, log::Level::Warn, *location)
725 }
726
727 fn unwrap(self) -> UnwrapFuture<Self>
728 where
729 Self: Sized,
730 {
731 UnwrapFuture(self)
732 }
733}
734
735#[must_use]
736pub struct LogErrorFuture<F>(F, log::Level, core::panic::Location<'static>);
737
738impl<F, T, E> Future for LogErrorFuture<F>
739where
740 F: Future<Output = Result<T, E>>,
741 E: std::fmt::Debug,
742{
743 type Output = Option<T>;
744
745 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
746 let level = self.1;
747 let location = self.2;
748 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
749 match inner.poll(cx) {
750 Poll::Ready(output) => Poll::Ready(match output {
751 Ok(output) => Some(output),
752 Err(error) => {
753 log_error_with_caller(location, error, level);
754 None
755 }
756 }),
757 Poll::Pending => Poll::Pending,
758 }
759 }
760}
761
762pub struct UnwrapFuture<F>(F);
763
764impl<F, T, E> Future for UnwrapFuture<F>
765where
766 F: Future<Output = Result<T, E>>,
767 E: std::fmt::Debug,
768{
769 type Output = T;
770
771 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
772 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
773 match inner.poll(cx) {
774 Poll::Ready(result) => Poll::Ready(result.unwrap()),
775 Poll::Pending => Poll::Pending,
776 }
777 }
778}
779
780pub struct Deferred<F: FnOnce()>(Option<F>);
781
782impl<F: FnOnce()> Deferred<F> {
783 /// Drop without running the deferred function.
784 pub fn abort(mut self) {
785 self.0.take();
786 }
787}
788
789impl<F: FnOnce()> Drop for Deferred<F> {
790 fn drop(&mut self) {
791 if let Some(f) = self.0.take() {
792 f()
793 }
794 }
795}
796
797/// Run the given function when the returned value is dropped (unless it's cancelled).
798#[must_use]
799pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
800 Deferred(Some(f))
801}
802
803#[cfg(any(test, feature = "test-support"))]
804mod rng {
805 use rand::{Rng, seq::SliceRandom};
806 pub struct RandomCharIter<T: Rng> {
807 rng: T,
808 simple_text: bool,
809 }
810
811 impl<T: Rng> RandomCharIter<T> {
812 pub fn new(rng: T) -> Self {
813 Self {
814 rng,
815 simple_text: std::env::var("SIMPLE_TEXT").map_or(false, |v| !v.is_empty()),
816 }
817 }
818
819 pub fn with_simple_text(mut self) -> Self {
820 self.simple_text = true;
821 self
822 }
823 }
824
825 impl<T: Rng> Iterator for RandomCharIter<T> {
826 type Item = char;
827
828 fn next(&mut self) -> Option<Self::Item> {
829 if self.simple_text {
830 return if self.rng.gen_range(0..100) < 5 {
831 Some('\n')
832 } else {
833 Some(self.rng.gen_range(b'a'..b'z' + 1).into())
834 };
835 }
836
837 match self.rng.gen_range(0..100) {
838 // whitespace
839 0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
840 // two-byte greek letters
841 20..=32 => char::from_u32(self.rng.gen_range(('α' as u32)..('ω' as u32 + 1))),
842 // // three-byte characters
843 33..=45 => ['✋', '✅', '❌', '❎', '⭐']
844 .choose(&mut self.rng)
845 .copied(),
846 // // four-byte characters
847 46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.rng).copied(),
848 // ascii letters
849 _ => Some(self.rng.gen_range(b'a'..b'z' + 1).into()),
850 }
851 }
852 }
853}
854#[cfg(any(test, feature = "test-support"))]
855pub use rng::RandomCharIter;
856/// Get an embedded file as a string.
857pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
858 match A::get(path).expect(path).data {
859 Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
860 Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
861 }
862}
863
864/// Expands to an immediately-invoked function expression. Good for using the ? operator
865/// in functions which do not return an Option or Result.
866///
867/// Accepts a normal block, an async block, or an async move block.
868#[macro_export]
869macro_rules! maybe {
870 ($block:block) => {
871 (|| $block)()
872 };
873 (async $block:block) => {
874 (|| async $block)()
875 };
876 (async move $block:block) => {
877 (|| async move $block)()
878 };
879}
880
881pub trait RangeExt<T> {
882 fn sorted(&self) -> Self;
883 fn to_inclusive(&self) -> RangeInclusive<T>;
884 fn overlaps(&self, other: &Range<T>) -> bool;
885 fn contains_inclusive(&self, other: &Range<T>) -> bool;
886}
887
888impl<T: Ord + Clone> RangeExt<T> for Range<T> {
889 fn sorted(&self) -> Self {
890 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
891 }
892
893 fn to_inclusive(&self) -> RangeInclusive<T> {
894 self.start.clone()..=self.end.clone()
895 }
896
897 fn overlaps(&self, other: &Range<T>) -> bool {
898 self.start < other.end && other.start < self.end
899 }
900
901 fn contains_inclusive(&self, other: &Range<T>) -> bool {
902 self.start <= other.start && other.end <= self.end
903 }
904}
905
906impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
907 fn sorted(&self) -> Self {
908 cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
909 }
910
911 fn to_inclusive(&self) -> RangeInclusive<T> {
912 self.clone()
913 }
914
915 fn overlaps(&self, other: &Range<T>) -> bool {
916 self.start() < &other.end && &other.start <= self.end()
917 }
918
919 fn contains_inclusive(&self, other: &Range<T>) -> bool {
920 self.start() <= &other.start && &other.end <= self.end()
921 }
922}
923
924/// A way to sort strings with starting numbers numerically first, falling back to alphanumeric one,
925/// case-insensitive.
926///
927/// This is useful for turning regular alphanumerically sorted sequences as `1-abc, 10, 11-def, .., 2, 21-abc`
928/// into `1-abc, 2, 10, 11-def, .., 21-abc`
929#[derive(Debug, PartialEq, Eq)]
930pub struct NumericPrefixWithSuffix<'a>(Option<u64>, &'a str);
931
932impl<'a> NumericPrefixWithSuffix<'a> {
933 pub fn from_numeric_prefixed_str(str: &'a str) -> Self {
934 let i = str.chars().take_while(|c| c.is_ascii_digit()).count();
935 let (prefix, remainder) = str.split_at(i);
936
937 let prefix = prefix.parse().ok();
938 Self(prefix, remainder)
939 }
940}
941
942/// When dealing with equality, we need to consider the case of the strings to achieve strict equality
943/// to handle cases like "a" < "A" instead of "a" == "A".
944impl Ord for NumericPrefixWithSuffix<'_> {
945 fn cmp(&self, other: &Self) -> Ordering {
946 match (self.0, other.0) {
947 (None, None) => UniCase::new(self.1)
948 .cmp(&UniCase::new(other.1))
949 .then_with(|| self.1.cmp(other.1).reverse()),
950 (None, Some(_)) => Ordering::Greater,
951 (Some(_), None) => Ordering::Less,
952 (Some(a), Some(b)) => a.cmp(&b).then_with(|| {
953 UniCase::new(self.1)
954 .cmp(&UniCase::new(other.1))
955 .then_with(|| self.1.cmp(other.1).reverse())
956 }),
957 }
958 }
959}
960
961impl PartialOrd for NumericPrefixWithSuffix<'_> {
962 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
963 Some(self.cmp(other))
964 }
965}
966
967/// Capitalizes the first character of a string.
968///
969/// This function takes a string slice as input and returns a new `String` with the first character
970/// capitalized.
971///
972/// # Examples
973///
974/// ```
975/// use util::capitalize;
976///
977/// assert_eq!(capitalize("hello"), "Hello");
978/// assert_eq!(capitalize("WORLD"), "WORLD");
979/// assert_eq!(capitalize(""), "");
980/// ```
981pub fn capitalize(str: &str) -> String {
982 let mut chars = str.chars();
983 match chars.next() {
984 None => String::new(),
985 Some(first_char) => first_char.to_uppercase().collect::<String>() + chars.as_str(),
986 }
987}
988
989fn emoji_regex() -> &'static Regex {
990 static EMOJI_REGEX: LazyLock<Regex> =
991 LazyLock::new(|| Regex::new("(\\p{Emoji}|\u{200D})").unwrap());
992 &EMOJI_REGEX
993}
994
995/// Returns true if the given string consists of emojis only.
996/// E.g. "👨👩👧👧👋" will return true, but "👋!" will return false.
997pub fn word_consists_of_emojis(s: &str) -> bool {
998 let mut prev_end = 0;
999 for capture in emoji_regex().find_iter(s) {
1000 if capture.start() != prev_end {
1001 return false;
1002 }
1003 prev_end = capture.end();
1004 }
1005 prev_end == s.len()
1006}
1007
1008pub fn default<D: Default>() -> D {
1009 Default::default()
1010}
1011
1012pub fn get_system_shell() -> String {
1013 #[cfg(target_os = "windows")]
1014 {
1015 get_windows_system_shell()
1016 }
1017
1018 #[cfg(not(target_os = "windows"))]
1019 {
1020 std::env::var("SHELL").unwrap_or("/bin/sh".to_string())
1021 }
1022}
1023
1024#[cfg(test)]
1025mod tests {
1026 use super::*;
1027
1028 #[test]
1029 fn test_extend_sorted() {
1030 let mut vec = vec![];
1031
1032 extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
1033 assert_eq!(vec, &[21, 17, 13, 8, 1]);
1034
1035 extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
1036 assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
1037
1038 extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
1039 assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
1040 }
1041
1042 #[test]
1043 fn test_truncate_to_bottom_n_sorted_by() {
1044 let mut vec: Vec<u32> = vec![5, 2, 3, 4, 1];
1045 truncate_to_bottom_n_sorted_by(&mut vec, 10, &u32::cmp);
1046 assert_eq!(vec, &[1, 2, 3, 4, 5]);
1047
1048 vec = vec![5, 2, 3, 4, 1];
1049 truncate_to_bottom_n_sorted_by(&mut vec, 5, &u32::cmp);
1050 assert_eq!(vec, &[1, 2, 3, 4, 5]);
1051
1052 vec = vec![5, 2, 3, 4, 1];
1053 truncate_to_bottom_n_sorted_by(&mut vec, 4, &u32::cmp);
1054 assert_eq!(vec, &[1, 2, 3, 4]);
1055
1056 vec = vec![5, 2, 3, 4, 1];
1057 truncate_to_bottom_n_sorted_by(&mut vec, 1, &u32::cmp);
1058 assert_eq!(vec, &[1]);
1059
1060 vec = vec![5, 2, 3, 4, 1];
1061 truncate_to_bottom_n_sorted_by(&mut vec, 0, &u32::cmp);
1062 assert!(vec.is_empty());
1063 }
1064
1065 #[test]
1066 fn test_iife() {
1067 fn option_returning_function() -> Option<()> {
1068 None
1069 }
1070
1071 let foo = maybe!({
1072 option_returning_function()?;
1073 Some(())
1074 });
1075
1076 assert_eq!(foo, None);
1077 }
1078
1079 #[test]
1080 fn test_truncate_and_trailoff() {
1081 assert_eq!(truncate_and_trailoff("", 5), "");
1082 assert_eq!(truncate_and_trailoff("aaaaaa", 7), "aaaaaa");
1083 assert_eq!(truncate_and_trailoff("aaaaaa", 6), "aaaaaa");
1084 assert_eq!(truncate_and_trailoff("aaaaaa", 5), "aaaaa…");
1085 assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
1086 assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
1087 assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
1088 }
1089
1090 #[test]
1091 fn test_truncate_and_remove_front() {
1092 assert_eq!(truncate_and_remove_front("", 5), "");
1093 assert_eq!(truncate_and_remove_front("aaaaaa", 7), "aaaaaa");
1094 assert_eq!(truncate_and_remove_front("aaaaaa", 6), "aaaaaa");
1095 assert_eq!(truncate_and_remove_front("aaaaaa", 5), "…aaaaa");
1096 assert_eq!(truncate_and_remove_front("èèèèèè", 7), "èèèèèè");
1097 assert_eq!(truncate_and_remove_front("èèèèèè", 6), "èèèèèè");
1098 assert_eq!(truncate_and_remove_front("èèèèèè", 5), "…èèèèè");
1099 }
1100
1101 #[test]
1102 fn test_numeric_prefix_str_method() {
1103 let target = "1a";
1104 assert_eq!(
1105 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1106 NumericPrefixWithSuffix(Some(1), "a")
1107 );
1108
1109 let target = "12ab";
1110 assert_eq!(
1111 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1112 NumericPrefixWithSuffix(Some(12), "ab")
1113 );
1114
1115 let target = "12_ab";
1116 assert_eq!(
1117 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1118 NumericPrefixWithSuffix(Some(12), "_ab")
1119 );
1120
1121 let target = "1_2ab";
1122 assert_eq!(
1123 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1124 NumericPrefixWithSuffix(Some(1), "_2ab")
1125 );
1126
1127 let target = "1.2";
1128 assert_eq!(
1129 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1130 NumericPrefixWithSuffix(Some(1), ".2")
1131 );
1132
1133 let target = "1.2_a";
1134 assert_eq!(
1135 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1136 NumericPrefixWithSuffix(Some(1), ".2_a")
1137 );
1138
1139 let target = "12.2_a";
1140 assert_eq!(
1141 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1142 NumericPrefixWithSuffix(Some(12), ".2_a")
1143 );
1144
1145 let target = "12a.2_a";
1146 assert_eq!(
1147 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1148 NumericPrefixWithSuffix(Some(12), "a.2_a")
1149 );
1150 }
1151
1152 #[test]
1153 fn test_numeric_prefix_with_suffix() {
1154 let mut sorted = vec!["1-abc", "10", "11def", "2", "21-abc"];
1155 sorted.sort_by_key(|s| NumericPrefixWithSuffix::from_numeric_prefixed_str(s));
1156 assert_eq!(sorted, ["1-abc", "2", "10", "11def", "21-abc"]);
1157
1158 for numeric_prefix_less in ["numeric_prefix_less", "aaa", "~™£"] {
1159 assert_eq!(
1160 NumericPrefixWithSuffix::from_numeric_prefixed_str(numeric_prefix_less),
1161 NumericPrefixWithSuffix(None, numeric_prefix_less),
1162 "String without numeric prefix `{numeric_prefix_less}` should not be converted into NumericPrefixWithSuffix"
1163 )
1164 }
1165 }
1166
1167 #[test]
1168 fn test_word_consists_of_emojis() {
1169 let words_to_test = vec![
1170 ("👨👩👧👧👋🥒", true),
1171 ("👋", true),
1172 ("!👋", false),
1173 ("👋!", false),
1174 ("👋 ", false),
1175 (" 👋", false),
1176 ("Test", false),
1177 ];
1178
1179 for (text, expected_result) in words_to_test {
1180 assert_eq!(word_consists_of_emojis(text), expected_result);
1181 }
1182 }
1183
1184 #[test]
1185 fn test_truncate_lines_and_trailoff() {
1186 let text = r#"Line 1
1187Line 2
1188Line 3"#;
1189
1190 assert_eq!(
1191 truncate_lines_and_trailoff(text, 2),
1192 r#"Line 1
1193…"#
1194 );
1195
1196 assert_eq!(
1197 truncate_lines_and_trailoff(text, 3),
1198 r#"Line 1
1199Line 2
1200…"#
1201 );
1202
1203 assert_eq!(
1204 truncate_lines_and_trailoff(text, 4),
1205 r#"Line 1
1206Line 2
1207Line 3"#
1208 );
1209 }
1210
1211 #[test]
1212 fn test_iterate_expanded_and_wrapped_usize_range() {
1213 // Neither wrap
1214 assert_eq!(
1215 iterate_expanded_and_wrapped_usize_range(2..4, 1, 1, 8).collect::<Vec<usize>>(),
1216 (1..5).collect::<Vec<usize>>()
1217 );
1218 // Start wraps
1219 assert_eq!(
1220 iterate_expanded_and_wrapped_usize_range(2..4, 3, 1, 8).collect::<Vec<usize>>(),
1221 ((0..5).chain(7..8)).collect::<Vec<usize>>()
1222 );
1223 // Start wraps all the way around
1224 assert_eq!(
1225 iterate_expanded_and_wrapped_usize_range(2..4, 5, 1, 8).collect::<Vec<usize>>(),
1226 (0..8).collect::<Vec<usize>>()
1227 );
1228 // Start wraps all the way around and past 0
1229 assert_eq!(
1230 iterate_expanded_and_wrapped_usize_range(2..4, 10, 1, 8).collect::<Vec<usize>>(),
1231 (0..8).collect::<Vec<usize>>()
1232 );
1233 // End wraps
1234 assert_eq!(
1235 iterate_expanded_and_wrapped_usize_range(3..5, 1, 4, 8).collect::<Vec<usize>>(),
1236 (0..1).chain(2..8).collect::<Vec<usize>>()
1237 );
1238 // End wraps all the way around
1239 assert_eq!(
1240 iterate_expanded_and_wrapped_usize_range(3..5, 1, 5, 8).collect::<Vec<usize>>(),
1241 (0..8).collect::<Vec<usize>>()
1242 );
1243 // End wraps all the way around and past the end
1244 assert_eq!(
1245 iterate_expanded_and_wrapped_usize_range(3..5, 1, 10, 8).collect::<Vec<usize>>(),
1246 (0..8).collect::<Vec<usize>>()
1247 );
1248 // Both start and end wrap
1249 assert_eq!(
1250 iterate_expanded_and_wrapped_usize_range(3..5, 4, 4, 8).collect::<Vec<usize>>(),
1251 (0..8).collect::<Vec<usize>>()
1252 );
1253 }
1254}