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