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