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