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