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) && s.as_bytes()[i] == b'\n' {
133 // Since the i-th character is \n, valid to slice at i + 1.
134 return &s[..i + 1];
135 }
136 }
137
138 truncate_to_byte_limit(s, max_bytes)
139}
140
141#[test]
142fn test_truncate_lines_to_byte_limit() {
143 let text = "Line 1\nLine 2\nLine 3\nLine 4";
144
145 // Limit that includes all lines
146 assert_eq!(truncate_lines_to_byte_limit(text, 100), text);
147
148 // Exactly the first line
149 assert_eq!(truncate_lines_to_byte_limit(text, 7), "Line 1\n");
150
151 // Limit between lines
152 assert_eq!(truncate_lines_to_byte_limit(text, 13), "Line 1\n");
153 assert_eq!(truncate_lines_to_byte_limit(text, 20), "Line 1\nLine 2\n");
154
155 // Limit before first newline
156 assert_eq!(truncate_lines_to_byte_limit(text, 6), "Line ");
157
158 // Test with non-ASCII characters
159 let text_utf8 = "Line 1\nLΓne 2\nLine 3";
160 assert_eq!(
161 truncate_lines_to_byte_limit(text_utf8, 15),
162 "Line 1\nLΓne 2\n"
163 );
164}
165
166pub fn post_inc<T: From<u8> + AddAssign<T> + Copy>(value: &mut T) -> T {
167 let prev = *value;
168 *value += T::from(1);
169 prev
170}
171
172/// Extend a sorted vector with a sorted sequence of items, maintaining the vector's sort order and
173/// enforcing a maximum length. This also de-duplicates items. Sort the items according to the given callback. Before calling this,
174/// both `vec` and `new_items` should already be sorted according to the `cmp` comparator.
175pub fn extend_sorted<T, I, F>(vec: &mut Vec<T>, new_items: I, limit: usize, mut cmp: F)
176where
177 I: IntoIterator<Item = T>,
178 F: FnMut(&T, &T) -> Ordering,
179{
180 let mut start_index = 0;
181 for new_item in new_items {
182 if let Err(i) = vec[start_index..].binary_search_by(|m| cmp(m, &new_item)) {
183 let index = start_index + i;
184 if vec.len() < limit {
185 vec.insert(index, new_item);
186 } else if index < vec.len() {
187 vec.pop();
188 vec.insert(index, new_item);
189 }
190 start_index = index;
191 }
192 }
193}
194
195pub fn truncate_to_bottom_n_sorted_by<T, F>(items: &mut Vec<T>, limit: usize, compare: &F)
196where
197 F: Fn(&T, &T) -> Ordering,
198{
199 if limit == 0 {
200 items.truncate(0);
201 }
202 if items.len() <= limit {
203 items.sort_by(compare);
204 return;
205 }
206 // When limit is near to items.len() it may be more efficient to sort the whole list and
207 // truncate, rather than always doing selection first as is done below. It's hard to analyze
208 // where the threshold for this should be since the quickselect style algorithm used by
209 // `select_nth_unstable_by` makes the prefix partially sorted, and so its work is not wasted -
210 // the expected number of comparisons needed by `sort_by` is less than it is for some arbitrary
211 // unsorted input.
212 items.select_nth_unstable_by(limit, compare);
213 items.truncate(limit);
214 items.sort_by(compare);
215}
216
217/// Prevents execution of the application with root privileges on Unix systems.
218///
219/// This function checks if the current process is running with root privileges
220/// and terminates the program with an error message unless explicitly allowed via the
221/// `ZED_ALLOW_ROOT` environment variable.
222#[cfg(unix)]
223pub fn prevent_root_execution() {
224 let is_root = nix::unistd::geteuid().is_root();
225 let allow_root = std::env::var("ZED_ALLOW_ROOT").is_ok_and(|val| val == "true");
226
227 if is_root && !allow_root {
228 eprintln!(
229 "\
230Error: Running Zed as root or via sudo is unsupported.
231 Doing so (even once) may subtly break things for all subsequent non-root usage of Zed.
232 It is untested and not recommended, don't complain when things break.
233 If you wish to proceed anyways, set `ZED_ALLOW_ROOT=true` in your environment."
234 );
235 std::process::exit(1);
236 }
237}
238
239#[cfg(unix)]
240fn load_shell_from_passwd() -> Result<()> {
241 let buflen = match unsafe { libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) } {
242 n if n < 0 => 1024,
243 n => n as usize,
244 };
245 let mut buffer = Vec::with_capacity(buflen);
246
247 let mut pwd: std::mem::MaybeUninit<libc::passwd> = std::mem::MaybeUninit::uninit();
248 let mut result: *mut libc::passwd = std::ptr::null_mut();
249
250 let uid = unsafe { libc::getuid() };
251 let status = unsafe {
252 libc::getpwuid_r(
253 uid,
254 pwd.as_mut_ptr(),
255 buffer.as_mut_ptr() as *mut libc::c_char,
256 buflen,
257 &mut result,
258 )
259 };
260 anyhow::ensure!(!result.is_null(), "passwd entry for uid {} not found", uid);
261
262 // SAFETY: If `getpwuid_r` doesn't error, we have the entry here.
263 let entry = unsafe { pwd.assume_init() };
264
265 anyhow::ensure!(
266 status == 0,
267 "call to getpwuid_r failed. uid: {}, status: {}",
268 uid,
269 status
270 );
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 Ok(zed_path_escaped.to_string())
308}
309
310#[cfg(unix)]
311pub async 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()).await? {
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().into_owned())
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 all crates reside in a `crates` directory,
674 // so discard the prefix up to that segment to find the crate name
675 let target = file
676 .split_once("crates/")
677 .and_then(|(_, s)| s.split_once('/'))
678 .map(|(p, _)| p);
679
680 log::logger().log(
681 &log::Record::builder()
682 .target(target.unwrap_or(""))
683 .module_path(target)
684 .args(format_args!("{:?}", error))
685 .file(Some(caller.file()))
686 .line(Some(caller.line()))
687 .level(level)
688 .build(),
689 );
690}
691
692pub fn log_err<E: std::fmt::Debug>(error: &E) {
693 log_error_with_caller(*Location::caller(), error, log::Level::Warn);
694}
695
696pub trait TryFutureExt {
697 fn log_err(self) -> LogErrorFuture<Self>
698 where
699 Self: Sized;
700
701 fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
702 where
703 Self: Sized;
704
705 fn warn_on_err(self) -> LogErrorFuture<Self>
706 where
707 Self: Sized;
708 fn unwrap(self) -> UnwrapFuture<Self>
709 where
710 Self: Sized;
711}
712
713impl<F, T, E> TryFutureExt for F
714where
715 F: Future<Output = Result<T, E>>,
716 E: std::fmt::Debug,
717{
718 #[track_caller]
719 fn log_err(self) -> LogErrorFuture<Self>
720 where
721 Self: Sized,
722 {
723 let location = Location::caller();
724 LogErrorFuture(self, log::Level::Error, *location)
725 }
726
727 fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
728 where
729 Self: Sized,
730 {
731 LogErrorFuture(self, log::Level::Error, location)
732 }
733
734 #[track_caller]
735 fn warn_on_err(self) -> LogErrorFuture<Self>
736 where
737 Self: Sized,
738 {
739 let location = Location::caller();
740 LogErrorFuture(self, log::Level::Warn, *location)
741 }
742
743 fn unwrap(self) -> UnwrapFuture<Self>
744 where
745 Self: Sized,
746 {
747 UnwrapFuture(self)
748 }
749}
750
751#[must_use]
752pub struct LogErrorFuture<F>(F, log::Level, core::panic::Location<'static>);
753
754impl<F, T, E> Future for LogErrorFuture<F>
755where
756 F: Future<Output = Result<T, E>>,
757 E: std::fmt::Debug,
758{
759 type Output = Option<T>;
760
761 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
762 let level = self.1;
763 let location = self.2;
764 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
765 match inner.poll(cx) {
766 Poll::Ready(output) => Poll::Ready(match output {
767 Ok(output) => Some(output),
768 Err(error) => {
769 log_error_with_caller(location, error, level);
770 None
771 }
772 }),
773 Poll::Pending => Poll::Pending,
774 }
775 }
776}
777
778pub struct UnwrapFuture<F>(F);
779
780impl<F, T, E> Future for UnwrapFuture<F>
781where
782 F: Future<Output = Result<T, E>>,
783 E: std::fmt::Debug,
784{
785 type Output = T;
786
787 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
788 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
789 match inner.poll(cx) {
790 Poll::Ready(result) => Poll::Ready(result.unwrap()),
791 Poll::Pending => Poll::Pending,
792 }
793 }
794}
795
796pub struct Deferred<F: FnOnce()>(Option<F>);
797
798impl<F: FnOnce()> Deferred<F> {
799 /// Drop without running the deferred function.
800 pub fn abort(mut self) {
801 self.0.take();
802 }
803}
804
805impl<F: FnOnce()> Drop for Deferred<F> {
806 fn drop(&mut self) {
807 if let Some(f) = self.0.take() {
808 f()
809 }
810 }
811}
812
813/// Run the given function when the returned value is dropped (unless it's cancelled).
814#[must_use]
815pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
816 Deferred(Some(f))
817}
818
819#[cfg(any(test, feature = "test-support"))]
820mod rng {
821 use rand::prelude::*;
822
823 pub struct RandomCharIter<T: Rng> {
824 rng: T,
825 simple_text: bool,
826 }
827
828 impl<T: Rng> RandomCharIter<T> {
829 pub fn new(rng: T) -> Self {
830 Self {
831 rng,
832 simple_text: std::env::var("SIMPLE_TEXT").is_ok_and(|v| !v.is_empty()),
833 }
834 }
835
836 pub fn with_simple_text(mut self) -> Self {
837 self.simple_text = true;
838 self
839 }
840 }
841
842 impl<T: Rng> Iterator for RandomCharIter<T> {
843 type Item = char;
844
845 fn next(&mut self) -> Option<Self::Item> {
846 if self.simple_text {
847 return if self.rng.random_range(0..100) < 5 {
848 Some('\n')
849 } else {
850 Some(self.rng.random_range(b'a'..b'z' + 1).into())
851 };
852 }
853
854 match self.rng.random_range(0..100) {
855 // whitespace
856 0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
857 // two-byte greek letters
858 20..=32 => char::from_u32(self.rng.random_range(('Ξ±' as u32)..('Ο' as u32 + 1))),
859 // // three-byte characters
860 33..=45 => ['β', 'β
', 'β', 'β', 'β']
861 .choose(&mut self.rng)
862 .copied(),
863 // // four-byte characters
864 46..=58 => ['π', 'π', 'π', 'π'].choose(&mut self.rng).copied(),
865 // ascii letters
866 _ => Some(self.rng.random_range(b'a'..b'z' + 1).into()),
867 }
868 }
869 }
870}
871#[cfg(any(test, feature = "test-support"))]
872pub use rng::RandomCharIter;
873
874/// Get an embedded file as a string.
875pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
876 match A::get(path).expect(path).data {
877 Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
878 Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
879 }
880}
881
882/// Expands to an immediately-invoked function expression. Good for using the ? operator
883/// in functions which do not return an Option or Result.
884///
885/// Accepts a normal block, an async block, or an async move block.
886#[macro_export]
887macro_rules! maybe {
888 ($block:block) => {
889 (|| $block)()
890 };
891 (async $block:block) => {
892 (async || $block)()
893 };
894 (async move $block:block) => {
895 (async move || $block)()
896 };
897}
898
899pub trait RangeExt<T> {
900 fn sorted(&self) -> Self;
901 fn to_inclusive(&self) -> RangeInclusive<T>;
902 fn overlaps(&self, other: &Range<T>) -> bool;
903 fn contains_inclusive(&self, other: &Range<T>) -> bool;
904}
905
906impl<T: Ord + Clone> RangeExt<T> for Range<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.start.clone()..=self.end.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
924impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
925 fn sorted(&self) -> Self {
926 cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
927 }
928
929 fn to_inclusive(&self) -> RangeInclusive<T> {
930 self.clone()
931 }
932
933 fn overlaps(&self, other: &Range<T>) -> bool {
934 self.start() < &other.end && &other.start <= self.end()
935 }
936
937 fn contains_inclusive(&self, other: &Range<T>) -> bool {
938 self.start() <= &other.start && &other.end <= self.end()
939 }
940}
941
942/// A way to sort strings with starting numbers numerically first, falling back to alphanumeric one,
943/// case-insensitive.
944///
945/// This is useful for turning regular alphanumerically sorted sequences as `1-abc, 10, 11-def, .., 2, 21-abc`
946/// into `1-abc, 2, 10, 11-def, .., 21-abc`
947#[derive(Debug, PartialEq, Eq)]
948pub struct NumericPrefixWithSuffix<'a>(Option<u64>, &'a str);
949
950impl<'a> NumericPrefixWithSuffix<'a> {
951 pub fn from_numeric_prefixed_str(str: &'a str) -> Self {
952 let i = str.chars().take_while(|c| c.is_ascii_digit()).count();
953 let (prefix, remainder) = str.split_at(i);
954
955 let prefix = prefix.parse().ok();
956 Self(prefix, remainder)
957 }
958}
959
960/// When dealing with equality, we need to consider the case of the strings to achieve strict equality
961/// to handle cases like "a" < "A" instead of "a" == "A".
962impl Ord for NumericPrefixWithSuffix<'_> {
963 fn cmp(&self, other: &Self) -> Ordering {
964 match (self.0, other.0) {
965 (None, None) => UniCase::new(self.1)
966 .cmp(&UniCase::new(other.1))
967 .then_with(|| self.1.cmp(other.1).reverse()),
968 (None, Some(_)) => Ordering::Greater,
969 (Some(_), None) => Ordering::Less,
970 (Some(a), Some(b)) => a.cmp(&b).then_with(|| {
971 UniCase::new(self.1)
972 .cmp(&UniCase::new(other.1))
973 .then_with(|| self.1.cmp(other.1).reverse())
974 }),
975 }
976 }
977}
978
979impl PartialOrd for NumericPrefixWithSuffix<'_> {
980 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
981 Some(self.cmp(other))
982 }
983}
984
985/// Capitalizes the first character of a string.
986///
987/// This function takes a string slice as input and returns a new `String` with the first character
988/// capitalized.
989///
990/// # Examples
991///
992/// ```
993/// use util::capitalize;
994///
995/// assert_eq!(capitalize("hello"), "Hello");
996/// assert_eq!(capitalize("WORLD"), "WORLD");
997/// assert_eq!(capitalize(""), "");
998/// ```
999pub fn capitalize(str: &str) -> String {
1000 let mut chars = str.chars();
1001 match chars.next() {
1002 None => String::new(),
1003 Some(first_char) => first_char.to_uppercase().collect::<String>() + chars.as_str(),
1004 }
1005}
1006
1007fn emoji_regex() -> &'static Regex {
1008 static EMOJI_REGEX: LazyLock<Regex> =
1009 LazyLock::new(|| Regex::new("(\\p{Emoji}|\u{200D})").unwrap());
1010 &EMOJI_REGEX
1011}
1012
1013/// Returns true if the given string consists of emojis only.
1014/// E.g. "π¨βπ©βπ§βπ§π" will return true, but "π!" will return false.
1015pub fn word_consists_of_emojis(s: &str) -> bool {
1016 let mut prev_end = 0;
1017 for capture in emoji_regex().find_iter(s) {
1018 if capture.start() != prev_end {
1019 return false;
1020 }
1021 prev_end = capture.end();
1022 }
1023 prev_end == s.len()
1024}
1025
1026/// Similar to `str::split`, but also provides byte-offset ranges of the results. Unlike
1027/// `str::split`, this is not generic on pattern types and does not return an `Iterator`.
1028pub fn split_str_with_ranges(s: &str, pat: impl Fn(char) -> bool) -> Vec<(Range<usize>, &str)> {
1029 let mut result = Vec::new();
1030 let mut start = 0;
1031
1032 for (i, ch) in s.char_indices() {
1033 if pat(ch) {
1034 if i > start {
1035 result.push((start..i, &s[start..i]));
1036 }
1037 start = i + ch.len_utf8();
1038 }
1039 }
1040
1041 if s.len() > start {
1042 result.push((start..s.len(), &s[start..s.len()]));
1043 }
1044
1045 result
1046}
1047
1048pub fn default<D: Default>() -> D {
1049 Default::default()
1050}
1051
1052pub fn get_system_shell() -> String {
1053 #[cfg(target_os = "windows")]
1054 {
1055 get_windows_system_shell()
1056 }
1057
1058 #[cfg(not(target_os = "windows"))]
1059 {
1060 std::env::var("SHELL").unwrap_or("/bin/sh".to_string())
1061 }
1062}
1063
1064pub fn get_default_system_shell() -> String {
1065 #[cfg(target_os = "windows")]
1066 {
1067 get_windows_system_shell()
1068 }
1069
1070 #[cfg(not(target_os = "windows"))]
1071 {
1072 "/bin/sh".to_string()
1073 }
1074}
1075
1076#[derive(Debug)]
1077pub enum ConnectionResult<O> {
1078 Timeout,
1079 ConnectionReset,
1080 Result(anyhow::Result<O>),
1081}
1082
1083impl<O> ConnectionResult<O> {
1084 pub fn into_response(self) -> anyhow::Result<O> {
1085 match self {
1086 ConnectionResult::Timeout => anyhow::bail!("Request timed out"),
1087 ConnectionResult::ConnectionReset => anyhow::bail!("Server reset the connection"),
1088 ConnectionResult::Result(r) => r,
1089 }
1090 }
1091}
1092
1093impl<O> From<anyhow::Result<O>> for ConnectionResult<O> {
1094 fn from(result: anyhow::Result<O>) -> Self {
1095 ConnectionResult::Result(result)
1096 }
1097}
1098
1099#[track_caller]
1100pub fn some_or_debug_panic<T>(option: Option<T>) -> Option<T> {
1101 #[cfg(debug_assertions)]
1102 if option.is_none() {
1103 panic!("Unexpected None");
1104 }
1105 option
1106}
1107
1108#[cfg(test)]
1109mod tests {
1110 use super::*;
1111
1112 #[test]
1113 fn test_extend_sorted() {
1114 let mut vec = vec![];
1115
1116 extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
1117 assert_eq!(vec, &[21, 17, 13, 8, 1]);
1118
1119 extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
1120 assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
1121
1122 extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
1123 assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
1124 }
1125
1126 #[test]
1127 fn test_truncate_to_bottom_n_sorted_by() {
1128 let mut vec: Vec<u32> = vec![5, 2, 3, 4, 1];
1129 truncate_to_bottom_n_sorted_by(&mut vec, 10, &u32::cmp);
1130 assert_eq!(vec, &[1, 2, 3, 4, 5]);
1131
1132 vec = vec![5, 2, 3, 4, 1];
1133 truncate_to_bottom_n_sorted_by(&mut vec, 5, &u32::cmp);
1134 assert_eq!(vec, &[1, 2, 3, 4, 5]);
1135
1136 vec = vec![5, 2, 3, 4, 1];
1137 truncate_to_bottom_n_sorted_by(&mut vec, 4, &u32::cmp);
1138 assert_eq!(vec, &[1, 2, 3, 4]);
1139
1140 vec = vec![5, 2, 3, 4, 1];
1141 truncate_to_bottom_n_sorted_by(&mut vec, 1, &u32::cmp);
1142 assert_eq!(vec, &[1]);
1143
1144 vec = vec![5, 2, 3, 4, 1];
1145 truncate_to_bottom_n_sorted_by(&mut vec, 0, &u32::cmp);
1146 assert!(vec.is_empty());
1147 }
1148
1149 #[test]
1150 fn test_iife() {
1151 fn option_returning_function() -> Option<()> {
1152 None
1153 }
1154
1155 let foo = maybe!({
1156 option_returning_function()?;
1157 Some(())
1158 });
1159
1160 assert_eq!(foo, None);
1161 }
1162
1163 #[test]
1164 fn test_truncate_and_trailoff() {
1165 assert_eq!(truncate_and_trailoff("", 5), "");
1166 assert_eq!(truncate_and_trailoff("aaaaaa", 7), "aaaaaa");
1167 assert_eq!(truncate_and_trailoff("aaaaaa", 6), "aaaaaa");
1168 assert_eq!(truncate_and_trailoff("aaaaaa", 5), "aaaaaβ¦");
1169 assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
1170 assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
1171 assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèèβ¦");
1172 }
1173
1174 #[test]
1175 fn test_truncate_and_remove_front() {
1176 assert_eq!(truncate_and_remove_front("", 5), "");
1177 assert_eq!(truncate_and_remove_front("aaaaaa", 7), "aaaaaa");
1178 assert_eq!(truncate_and_remove_front("aaaaaa", 6), "aaaaaa");
1179 assert_eq!(truncate_and_remove_front("aaaaaa", 5), "β¦aaaaa");
1180 assert_eq!(truncate_and_remove_front("èèèèèè", 7), "èèèèèè");
1181 assert_eq!(truncate_and_remove_front("èèèèèè", 6), "èèèèèè");
1182 assert_eq!(truncate_and_remove_front("èèèèèè", 5), "β¦Γ¨Γ¨Γ¨Γ¨Γ¨");
1183 }
1184
1185 #[test]
1186 fn test_numeric_prefix_str_method() {
1187 let target = "1a";
1188 assert_eq!(
1189 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1190 NumericPrefixWithSuffix(Some(1), "a")
1191 );
1192
1193 let target = "12ab";
1194 assert_eq!(
1195 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1196 NumericPrefixWithSuffix(Some(12), "ab")
1197 );
1198
1199 let target = "12_ab";
1200 assert_eq!(
1201 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1202 NumericPrefixWithSuffix(Some(12), "_ab")
1203 );
1204
1205 let target = "1_2ab";
1206 assert_eq!(
1207 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1208 NumericPrefixWithSuffix(Some(1), "_2ab")
1209 );
1210
1211 let target = "1.2";
1212 assert_eq!(
1213 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1214 NumericPrefixWithSuffix(Some(1), ".2")
1215 );
1216
1217 let target = "1.2_a";
1218 assert_eq!(
1219 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1220 NumericPrefixWithSuffix(Some(1), ".2_a")
1221 );
1222
1223 let target = "12.2_a";
1224 assert_eq!(
1225 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1226 NumericPrefixWithSuffix(Some(12), ".2_a")
1227 );
1228
1229 let target = "12a.2_a";
1230 assert_eq!(
1231 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1232 NumericPrefixWithSuffix(Some(12), "a.2_a")
1233 );
1234 }
1235
1236 #[test]
1237 fn test_numeric_prefix_with_suffix() {
1238 let mut sorted = vec!["1-abc", "10", "11def", "2", "21-abc"];
1239 sorted.sort_by_key(|s| NumericPrefixWithSuffix::from_numeric_prefixed_str(s));
1240 assert_eq!(sorted, ["1-abc", "2", "10", "11def", "21-abc"]);
1241
1242 for numeric_prefix_less in ["numeric_prefix_less", "aaa", "~β’Β£"] {
1243 assert_eq!(
1244 NumericPrefixWithSuffix::from_numeric_prefixed_str(numeric_prefix_less),
1245 NumericPrefixWithSuffix(None, numeric_prefix_less),
1246 "String without numeric prefix `{numeric_prefix_less}` should not be converted into NumericPrefixWithSuffix"
1247 )
1248 }
1249 }
1250
1251 #[test]
1252 fn test_word_consists_of_emojis() {
1253 let words_to_test = vec![
1254 ("π¨βπ©βπ§βπ§ππ₯", true),
1255 ("π", true),
1256 ("!π", false),
1257 ("π!", false),
1258 ("π ", false),
1259 (" π", false),
1260 ("Test", false),
1261 ];
1262
1263 for (text, expected_result) in words_to_test {
1264 assert_eq!(word_consists_of_emojis(text), expected_result);
1265 }
1266 }
1267
1268 #[test]
1269 fn test_truncate_lines_and_trailoff() {
1270 let text = r#"Line 1
1271Line 2
1272Line 3"#;
1273
1274 assert_eq!(
1275 truncate_lines_and_trailoff(text, 2),
1276 r#"Line 1
1277β¦"#
1278 );
1279
1280 assert_eq!(
1281 truncate_lines_and_trailoff(text, 3),
1282 r#"Line 1
1283Line 2
1284β¦"#
1285 );
1286
1287 assert_eq!(
1288 truncate_lines_and_trailoff(text, 4),
1289 r#"Line 1
1290Line 2
1291Line 3"#
1292 );
1293 }
1294
1295 #[test]
1296 fn test_expanded_and_wrapped_usize_range() {
1297 // Neither wrap
1298 assert_eq!(
1299 expanded_and_wrapped_usize_range(2..4, 1, 1, 8).collect::<Vec<usize>>(),
1300 (1..5).collect::<Vec<usize>>()
1301 );
1302 // Start wraps
1303 assert_eq!(
1304 expanded_and_wrapped_usize_range(2..4, 3, 1, 8).collect::<Vec<usize>>(),
1305 ((0..5).chain(7..8)).collect::<Vec<usize>>()
1306 );
1307 // Start wraps all the way around
1308 assert_eq!(
1309 expanded_and_wrapped_usize_range(2..4, 5, 1, 8).collect::<Vec<usize>>(),
1310 (0..8).collect::<Vec<usize>>()
1311 );
1312 // Start wraps all the way around and past 0
1313 assert_eq!(
1314 expanded_and_wrapped_usize_range(2..4, 10, 1, 8).collect::<Vec<usize>>(),
1315 (0..8).collect::<Vec<usize>>()
1316 );
1317 // End wraps
1318 assert_eq!(
1319 expanded_and_wrapped_usize_range(3..5, 1, 4, 8).collect::<Vec<usize>>(),
1320 (0..1).chain(2..8).collect::<Vec<usize>>()
1321 );
1322 // End wraps all the way around
1323 assert_eq!(
1324 expanded_and_wrapped_usize_range(3..5, 1, 5, 8).collect::<Vec<usize>>(),
1325 (0..8).collect::<Vec<usize>>()
1326 );
1327 // End wraps all the way around and past the end
1328 assert_eq!(
1329 expanded_and_wrapped_usize_range(3..5, 1, 10, 8).collect::<Vec<usize>>(),
1330 (0..8).collect::<Vec<usize>>()
1331 );
1332 // Both start and end wrap
1333 assert_eq!(
1334 expanded_and_wrapped_usize_range(3..5, 4, 4, 8).collect::<Vec<usize>>(),
1335 (0..8).collect::<Vec<usize>>()
1336 );
1337 }
1338
1339 #[test]
1340 fn test_wrapped_usize_outward_from() {
1341 // No wrapping
1342 assert_eq!(
1343 wrapped_usize_outward_from(4, 2, 2, 10).collect::<Vec<usize>>(),
1344 vec![4, 5, 3, 6, 2]
1345 );
1346 // Wrapping at end
1347 assert_eq!(
1348 wrapped_usize_outward_from(8, 2, 3, 10).collect::<Vec<usize>>(),
1349 vec![8, 9, 7, 0, 6, 1]
1350 );
1351 // Wrapping at start
1352 assert_eq!(
1353 wrapped_usize_outward_from(1, 3, 2, 10).collect::<Vec<usize>>(),
1354 vec![1, 2, 0, 3, 9, 8]
1355 );
1356 // All values wrap around
1357 assert_eq!(
1358 wrapped_usize_outward_from(5, 10, 10, 8).collect::<Vec<usize>>(),
1359 vec![5, 6, 4, 7, 3, 0, 2, 1]
1360 );
1361 // None before / after
1362 assert_eq!(
1363 wrapped_usize_outward_from(3, 0, 0, 8).collect::<Vec<usize>>(),
1364 vec![3]
1365 );
1366 // Starting point already wrapped
1367 assert_eq!(
1368 wrapped_usize_outward_from(15, 2, 2, 10).collect::<Vec<usize>>(),
1369 vec![5, 6, 4, 7, 3]
1370 );
1371 // wrap_length of 0
1372 assert_eq!(
1373 wrapped_usize_outward_from(4, 2, 2, 0).collect::<Vec<usize>>(),
1374 Vec::<usize>::new()
1375 );
1376 }
1377
1378 #[test]
1379 fn test_split_with_ranges() {
1380 let input = "hi";
1381 let result = split_str_with_ranges(input, |c| c == ' ');
1382
1383 assert_eq!(result.len(), 1);
1384 assert_eq!(result[0], (0..2, "hi"));
1385
1386 let input = "hΓ©lloπ¦world";
1387 let result = split_str_with_ranges(input, |c| c == 'π¦');
1388
1389 assert_eq!(result.len(), 2);
1390 assert_eq!(result[0], (0..6, "hΓ©llo")); // 'Γ©' is 2 bytes
1391 assert_eq!(result[1], (10..15, "world")); // 'π¦' is 4 bytes
1392 }
1393}