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 #[cfg(target_os = "macos")]
394 crate::command::reset_exception_ports();
395 Ok(())
396 });
397 };
398 command
399}
400
401pub fn merge_json_lenient_value_into(
402 source: serde_json_lenient::Value,
403 target: &mut serde_json_lenient::Value,
404) {
405 match (source, target) {
406 (serde_json_lenient::Value::Object(source), serde_json_lenient::Value::Object(target)) => {
407 for (key, value) in source {
408 if let Some(target) = target.get_mut(&key) {
409 merge_json_lenient_value_into(value, target);
410 } else {
411 target.insert(key, value);
412 }
413 }
414 }
415
416 (serde_json_lenient::Value::Array(source), serde_json_lenient::Value::Array(target)) => {
417 for value in source {
418 target.push(value);
419 }
420 }
421
422 (source, target) => *target = source,
423 }
424}
425
426pub fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
427 use serde_json::Value;
428
429 match (source, target) {
430 (Value::Object(source), Value::Object(target)) => {
431 for (key, value) in source {
432 if let Some(target) = target.get_mut(&key) {
433 merge_json_value_into(value, target);
434 } else {
435 target.insert(key, value);
436 }
437 }
438 }
439
440 (Value::Array(source), Value::Array(target)) => {
441 for value in source {
442 target.push(value);
443 }
444 }
445
446 (source, target) => *target = source,
447 }
448}
449
450pub fn merge_non_null_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
451 use serde_json::Value;
452 if let Value::Object(source_object) = source {
453 let target_object = if let Value::Object(target) = target {
454 target
455 } else {
456 *target = Value::Object(Default::default());
457 target.as_object_mut().unwrap()
458 };
459 for (key, value) in source_object {
460 if let Some(target) = target_object.get_mut(&key) {
461 merge_non_null_json_value_into(value, target);
462 } else if !value.is_null() {
463 target_object.insert(key, value);
464 }
465 }
466 } else if !source.is_null() {
467 *target = source
468 }
469}
470
471pub fn measure<R>(label: &str, f: impl FnOnce() -> R) -> R {
472 static ZED_MEASUREMENTS: OnceLock<bool> = OnceLock::new();
473 let zed_measurements = ZED_MEASUREMENTS.get_or_init(|| {
474 env::var("ZED_MEASUREMENTS")
475 .map(|measurements| measurements == "1" || measurements == "true")
476 .unwrap_or(false)
477 });
478
479 if *zed_measurements {
480 let start = Instant::now();
481 let result = f();
482 let elapsed = start.elapsed();
483 eprintln!("{}: {:?}", label, elapsed);
484 result
485 } else {
486 f()
487 }
488}
489
490pub fn expanded_and_wrapped_usize_range(
491 range: Range<usize>,
492 additional_before: usize,
493 additional_after: usize,
494 wrap_length: usize,
495) -> impl Iterator<Item = usize> {
496 let start_wraps = range.start < additional_before;
497 let end_wraps = wrap_length < range.end + additional_after;
498 if start_wraps && end_wraps {
499 Either::Left(0..wrap_length)
500 } else if start_wraps {
501 let wrapped_start = (range.start + wrap_length).saturating_sub(additional_before);
502 if wrapped_start <= range.end {
503 Either::Left(0..wrap_length)
504 } else {
505 Either::Right((0..range.end + additional_after).chain(wrapped_start..wrap_length))
506 }
507 } else if end_wraps {
508 let wrapped_end = range.end + additional_after - wrap_length;
509 if range.start <= wrapped_end {
510 Either::Left(0..wrap_length)
511 } else {
512 Either::Right((0..wrapped_end).chain(range.start - additional_before..wrap_length))
513 }
514 } else {
515 Either::Left((range.start - additional_before)..(range.end + additional_after))
516 }
517}
518
519/// Yields `[i, i + 1, i - 1, i + 2, ..]`, each modulo `wrap_length` and bounded by
520/// `additional_before` and `additional_after`. If the wrapping causes overlap, duplicates are not
521/// emitted. If wrap_length is 0, nothing is yielded.
522pub fn wrapped_usize_outward_from(
523 start: usize,
524 additional_before: usize,
525 additional_after: usize,
526 wrap_length: usize,
527) -> impl Iterator<Item = usize> {
528 let mut count = 0;
529 let mut after_offset = 1;
530 let mut before_offset = 1;
531
532 std::iter::from_fn(move || {
533 count += 1;
534 if count > wrap_length {
535 None
536 } else if count == 1 {
537 Some(start % wrap_length)
538 } else if after_offset <= additional_after && after_offset <= before_offset {
539 let value = (start + after_offset) % wrap_length;
540 after_offset += 1;
541 Some(value)
542 } else if before_offset <= additional_before {
543 let value = (start + wrap_length - before_offset) % wrap_length;
544 before_offset += 1;
545 Some(value)
546 } else if after_offset <= additional_after {
547 let value = (start + after_offset) % wrap_length;
548 after_offset += 1;
549 Some(value)
550 } else {
551 None
552 }
553 })
554}
555
556pub trait ResultExt<E> {
557 type Ok;
558
559 fn log_err(self) -> Option<Self::Ok>;
560 /// Assert that this result should never be an error in development or tests.
561 fn debug_assert_ok(self, reason: &str) -> Self;
562 fn warn_on_err(self) -> Option<Self::Ok>;
563 fn log_with_level(self, level: log::Level) -> Option<Self::Ok>;
564 fn anyhow(self) -> anyhow::Result<Self::Ok>
565 where
566 E: Into<anyhow::Error>;
567}
568
569impl<T, E> ResultExt<E> for Result<T, E>
570where
571 E: std::fmt::Debug,
572{
573 type Ok = T;
574
575 #[track_caller]
576 fn log_err(self) -> Option<T> {
577 self.log_with_level(log::Level::Error)
578 }
579
580 #[track_caller]
581 fn debug_assert_ok(self, reason: &str) -> Self {
582 if let Err(error) = &self {
583 debug_panic!("{reason} - {error:?}");
584 }
585 self
586 }
587
588 #[track_caller]
589 fn warn_on_err(self) -> Option<T> {
590 self.log_with_level(log::Level::Warn)
591 }
592
593 #[track_caller]
594 fn log_with_level(self, level: log::Level) -> Option<T> {
595 match self {
596 Ok(value) => Some(value),
597 Err(error) => {
598 log_error_with_caller(*Location::caller(), error, level);
599 None
600 }
601 }
602 }
603
604 fn anyhow(self) -> anyhow::Result<T>
605 where
606 E: Into<anyhow::Error>,
607 {
608 self.map_err(Into::into)
609 }
610}
611
612fn log_error_with_caller<E>(caller: core::panic::Location<'_>, error: E, level: log::Level)
613where
614 E: std::fmt::Debug,
615{
616 #[cfg(not(target_os = "windows"))]
617 let file = caller.file();
618 #[cfg(target_os = "windows")]
619 let file = caller.file().replace('\\', "/");
620 // In this codebase all crates reside in a `crates` directory,
621 // so discard the prefix up to that segment to find the crate name
622 let file = file.split_once("crates/");
623 let target = file.as_ref().and_then(|(_, s)| s.split_once("/src/"));
624
625 let module_path = target.map(|(krate, module)| {
626 if module.starts_with(krate) {
627 module.trim_end_matches(".rs").replace('/', "::")
628 } else {
629 krate.to_owned() + "::" + &module.trim_end_matches(".rs").replace('/', "::")
630 }
631 });
632 let file = file.map(|(_, file)| format!("crates/{file}"));
633 log::logger().log(
634 &log::Record::builder()
635 .target(module_path.as_deref().unwrap_or(""))
636 .module_path(file.as_deref())
637 .args(format_args!("{:?}", error))
638 .file(Some(caller.file()))
639 .line(Some(caller.line()))
640 .level(level)
641 .build(),
642 );
643}
644
645pub fn log_err<E: std::fmt::Debug>(error: &E) {
646 log_error_with_caller(*Location::caller(), error, log::Level::Error);
647}
648
649pub trait TryFutureExt {
650 fn log_err(self) -> LogErrorFuture<Self>
651 where
652 Self: Sized;
653
654 fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
655 where
656 Self: Sized;
657
658 fn warn_on_err(self) -> LogErrorFuture<Self>
659 where
660 Self: Sized;
661 fn unwrap(self) -> UnwrapFuture<Self>
662 where
663 Self: Sized;
664}
665
666impl<F, T, E> TryFutureExt for F
667where
668 F: Future<Output = Result<T, E>>,
669 E: std::fmt::Debug,
670{
671 #[track_caller]
672 fn log_err(self) -> LogErrorFuture<Self>
673 where
674 Self: Sized,
675 {
676 let location = Location::caller();
677 LogErrorFuture(self, log::Level::Error, *location)
678 }
679
680 fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
681 where
682 Self: Sized,
683 {
684 LogErrorFuture(self, log::Level::Error, location)
685 }
686
687 #[track_caller]
688 fn warn_on_err(self) -> LogErrorFuture<Self>
689 where
690 Self: Sized,
691 {
692 let location = Location::caller();
693 LogErrorFuture(self, log::Level::Warn, *location)
694 }
695
696 fn unwrap(self) -> UnwrapFuture<Self>
697 where
698 Self: Sized,
699 {
700 UnwrapFuture(self)
701 }
702}
703
704#[must_use]
705pub struct LogErrorFuture<F>(F, log::Level, core::panic::Location<'static>);
706
707impl<F, T, E> Future for LogErrorFuture<F>
708where
709 F: Future<Output = Result<T, E>>,
710 E: std::fmt::Debug,
711{
712 type Output = Option<T>;
713
714 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
715 let level = self.1;
716 let location = self.2;
717 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
718 match inner.poll(cx) {
719 Poll::Ready(output) => Poll::Ready(match output {
720 Ok(output) => Some(output),
721 Err(error) => {
722 log_error_with_caller(location, error, level);
723 None
724 }
725 }),
726 Poll::Pending => Poll::Pending,
727 }
728 }
729}
730
731pub struct UnwrapFuture<F>(F);
732
733impl<F, T, E> Future for UnwrapFuture<F>
734where
735 F: Future<Output = Result<T, E>>,
736 E: std::fmt::Debug,
737{
738 type Output = T;
739
740 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
741 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
742 match inner.poll(cx) {
743 Poll::Ready(result) => Poll::Ready(result.unwrap()),
744 Poll::Pending => Poll::Pending,
745 }
746 }
747}
748
749pub struct Deferred<F: FnOnce()>(Option<F>);
750
751impl<F: FnOnce()> Deferred<F> {
752 /// Drop without running the deferred function.
753 pub fn abort(mut self) {
754 self.0.take();
755 }
756}
757
758impl<F: FnOnce()> Drop for Deferred<F> {
759 fn drop(&mut self) {
760 if let Some(f) = self.0.take() {
761 f()
762 }
763 }
764}
765
766/// Run the given function when the returned value is dropped (unless it's cancelled).
767#[must_use]
768pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
769 Deferred(Some(f))
770}
771
772#[cfg(any(test, feature = "test-support"))]
773mod rng {
774 use rand::prelude::*;
775
776 pub struct RandomCharIter<T: Rng> {
777 rng: T,
778 simple_text: bool,
779 }
780
781 impl<T: Rng> RandomCharIter<T> {
782 pub fn new(rng: T) -> Self {
783 Self {
784 rng,
785 simple_text: std::env::var("SIMPLE_TEXT").is_ok_and(|v| !v.is_empty()),
786 }
787 }
788
789 pub fn with_simple_text(mut self) -> Self {
790 self.simple_text = true;
791 self
792 }
793 }
794
795 impl<T: Rng> Iterator for RandomCharIter<T> {
796 type Item = char;
797
798 fn next(&mut self) -> Option<Self::Item> {
799 if self.simple_text {
800 return if self.rng.random_range(0..100) < 5 {
801 Some('\n')
802 } else {
803 Some(self.rng.random_range(b'a'..b'z' + 1).into())
804 };
805 }
806
807 match self.rng.random_range(0..100) {
808 // whitespace
809 0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
810 // two-byte greek letters
811 20..=32 => char::from_u32(self.rng.random_range(('Ξ±' as u32)..('Ο' as u32 + 1))),
812 // // three-byte characters
813 33..=45 => ['β', 'β
', 'β', 'β', 'β']
814 .choose(&mut self.rng)
815 .copied(),
816 // // four-byte characters
817 46..=58 => ['π', 'π', 'π', 'π'].choose(&mut self.rng).copied(),
818 // ascii letters
819 _ => Some(self.rng.random_range(b'a'..b'z' + 1).into()),
820 }
821 }
822 }
823}
824#[cfg(any(test, feature = "test-support"))]
825pub use rng::RandomCharIter;
826
827/// Get an embedded file as a string.
828pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
829 match A::get(path).expect(path).data {
830 Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
831 Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
832 }
833}
834
835/// Expands to an immediately-invoked function expression. Good for using the ? operator
836/// in functions which do not return an Option or Result.
837///
838/// Accepts a normal block, an async block, or an async move block.
839#[macro_export]
840macro_rules! maybe {
841 ($block:block) => {
842 (|| $block)()
843 };
844 (async $block:block) => {
845 (async || $block)()
846 };
847 (async move $block:block) => {
848 (async move || $block)()
849 };
850}
851
852pub trait RangeExt<T> {
853 fn sorted(&self) -> Self;
854 fn to_inclusive(&self) -> RangeInclusive<T>;
855 fn overlaps(&self, other: &Range<T>) -> bool;
856 fn contains_inclusive(&self, other: &Range<T>) -> bool;
857}
858
859impl<T: Ord + Clone> RangeExt<T> for Range<T> {
860 fn sorted(&self) -> Self {
861 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
862 }
863
864 fn to_inclusive(&self) -> RangeInclusive<T> {
865 self.start.clone()..=self.end.clone()
866 }
867
868 fn overlaps(&self, other: &Range<T>) -> bool {
869 self.start < other.end && other.start < self.end
870 }
871
872 fn contains_inclusive(&self, other: &Range<T>) -> bool {
873 self.start <= other.start && other.end <= self.end
874 }
875}
876
877impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
878 fn sorted(&self) -> Self {
879 cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
880 }
881
882 fn to_inclusive(&self) -> RangeInclusive<T> {
883 self.clone()
884 }
885
886 fn overlaps(&self, other: &Range<T>) -> bool {
887 self.start() < &other.end && &other.start <= self.end()
888 }
889
890 fn contains_inclusive(&self, other: &Range<T>) -> bool {
891 self.start() <= &other.start && &other.end <= self.end()
892 }
893}
894
895/// A way to sort strings with starting numbers numerically first, falling back to alphanumeric one,
896/// case-insensitive.
897///
898/// This is useful for turning regular alphanumerically sorted sequences as `1-abc, 10, 11-def, .., 2, 21-abc`
899/// into `1-abc, 2, 10, 11-def, .., 21-abc`
900#[derive(Debug, PartialEq, Eq)]
901pub struct NumericPrefixWithSuffix<'a>(Option<u64>, &'a str);
902
903impl<'a> NumericPrefixWithSuffix<'a> {
904 pub fn from_numeric_prefixed_str(str: &'a str) -> Self {
905 let i = str.chars().take_while(|c| c.is_ascii_digit()).count();
906 let (prefix, remainder) = str.split_at(i);
907
908 let prefix = prefix.parse().ok();
909 Self(prefix, remainder)
910 }
911}
912
913/// When dealing with equality, we need to consider the case of the strings to achieve strict equality
914/// to handle cases like "a" < "A" instead of "a" == "A".
915impl Ord for NumericPrefixWithSuffix<'_> {
916 fn cmp(&self, other: &Self) -> Ordering {
917 match (self.0, other.0) {
918 (None, None) => UniCase::new(self.1)
919 .cmp(&UniCase::new(other.1))
920 .then_with(|| self.1.cmp(other.1).reverse()),
921 (None, Some(_)) => Ordering::Greater,
922 (Some(_), None) => Ordering::Less,
923 (Some(a), Some(b)) => a.cmp(&b).then_with(|| {
924 UniCase::new(self.1)
925 .cmp(&UniCase::new(other.1))
926 .then_with(|| self.1.cmp(other.1).reverse())
927 }),
928 }
929 }
930}
931
932impl PartialOrd for NumericPrefixWithSuffix<'_> {
933 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
934 Some(self.cmp(other))
935 }
936}
937
938/// Capitalizes the first character of a string.
939///
940/// This function takes a string slice as input and returns a new `String` with the first character
941/// capitalized.
942///
943/// # Examples
944///
945/// ```
946/// use util::capitalize;
947///
948/// assert_eq!(capitalize("hello"), "Hello");
949/// assert_eq!(capitalize("WORLD"), "WORLD");
950/// assert_eq!(capitalize(""), "");
951/// ```
952pub fn capitalize(str: &str) -> String {
953 let mut chars = str.chars();
954 match chars.next() {
955 None => String::new(),
956 Some(first_char) => first_char.to_uppercase().collect::<String>() + chars.as_str(),
957 }
958}
959
960fn emoji_regex() -> &'static Regex {
961 static EMOJI_REGEX: LazyLock<Regex> =
962 LazyLock::new(|| Regex::new("(\\p{Emoji}|\u{200D})").unwrap());
963 &EMOJI_REGEX
964}
965
966/// Returns true if the given string consists of emojis only.
967/// E.g. "π¨βπ©βπ§βπ§π" will return true, but "π!" will return false.
968pub fn word_consists_of_emojis(s: &str) -> bool {
969 let mut prev_end = 0;
970 for capture in emoji_regex().find_iter(s) {
971 if capture.start() != prev_end {
972 return false;
973 }
974 prev_end = capture.end();
975 }
976 prev_end == s.len()
977}
978
979/// Similar to `str::split`, but also provides byte-offset ranges of the results. Unlike
980/// `str::split`, this is not generic on pattern types and does not return an `Iterator`.
981pub fn split_str_with_ranges(s: &str, pat: impl Fn(char) -> bool) -> Vec<(Range<usize>, &str)> {
982 let mut result = Vec::new();
983 let mut start = 0;
984
985 for (i, ch) in s.char_indices() {
986 if pat(ch) {
987 if i > start {
988 result.push((start..i, &s[start..i]));
989 }
990 start = i + ch.len_utf8();
991 }
992 }
993
994 if s.len() > start {
995 result.push((start..s.len(), &s[start..s.len()]));
996 }
997
998 result
999}
1000
1001pub fn default<D: Default>() -> D {
1002 Default::default()
1003}
1004
1005pub use self::shell::{
1006 get_default_system_shell, get_default_system_shell_preferring_bash, get_system_shell,
1007};
1008
1009#[derive(Debug)]
1010pub enum ConnectionResult<O> {
1011 Timeout,
1012 ConnectionReset,
1013 Result(anyhow::Result<O>),
1014}
1015
1016impl<O> ConnectionResult<O> {
1017 pub fn into_response(self) -> anyhow::Result<O> {
1018 match self {
1019 ConnectionResult::Timeout => anyhow::bail!("Request timed out"),
1020 ConnectionResult::ConnectionReset => anyhow::bail!("Server reset the connection"),
1021 ConnectionResult::Result(r) => r,
1022 }
1023 }
1024}
1025
1026impl<O> From<anyhow::Result<O>> for ConnectionResult<O> {
1027 fn from(result: anyhow::Result<O>) -> Self {
1028 ConnectionResult::Result(result)
1029 }
1030}
1031
1032#[track_caller]
1033pub fn some_or_debug_panic<T>(option: Option<T>) -> Option<T> {
1034 #[cfg(debug_assertions)]
1035 if option.is_none() {
1036 panic!("Unexpected None");
1037 }
1038 option
1039}
1040
1041#[cfg(test)]
1042mod tests {
1043 use super::*;
1044
1045 #[test]
1046 fn test_extend_sorted() {
1047 let mut vec = vec![];
1048
1049 extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
1050 assert_eq!(vec, &[21, 17, 13, 8, 1]);
1051
1052 extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
1053 assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
1054
1055 extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
1056 assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
1057 }
1058
1059 #[test]
1060 fn test_truncate_to_bottom_n_sorted_by() {
1061 let mut vec: Vec<u32> = vec![5, 2, 3, 4, 1];
1062 truncate_to_bottom_n_sorted_by(&mut vec, 10, &u32::cmp);
1063 assert_eq!(vec, &[1, 2, 3, 4, 5]);
1064
1065 vec = vec![5, 2, 3, 4, 1];
1066 truncate_to_bottom_n_sorted_by(&mut vec, 5, &u32::cmp);
1067 assert_eq!(vec, &[1, 2, 3, 4, 5]);
1068
1069 vec = vec![5, 2, 3, 4, 1];
1070 truncate_to_bottom_n_sorted_by(&mut vec, 4, &u32::cmp);
1071 assert_eq!(vec, &[1, 2, 3, 4]);
1072
1073 vec = vec![5, 2, 3, 4, 1];
1074 truncate_to_bottom_n_sorted_by(&mut vec, 1, &u32::cmp);
1075 assert_eq!(vec, &[1]);
1076
1077 vec = vec![5, 2, 3, 4, 1];
1078 truncate_to_bottom_n_sorted_by(&mut vec, 0, &u32::cmp);
1079 assert!(vec.is_empty());
1080 }
1081
1082 #[test]
1083 fn test_iife() {
1084 fn option_returning_function() -> Option<()> {
1085 None
1086 }
1087
1088 let foo = maybe!({
1089 option_returning_function()?;
1090 Some(())
1091 });
1092
1093 assert_eq!(foo, None);
1094 }
1095
1096 #[test]
1097 fn test_truncate_and_trailoff() {
1098 assert_eq!(truncate_and_trailoff("", 5), "");
1099 assert_eq!(truncate_and_trailoff("aaaaaa", 7), "aaaaaa");
1100 assert_eq!(truncate_and_trailoff("aaaaaa", 6), "aaaaaa");
1101 assert_eq!(truncate_and_trailoff("aaaaaa", 5), "aaaaaβ¦");
1102 assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
1103 assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
1104 assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèèβ¦");
1105 }
1106
1107 #[test]
1108 fn test_truncate_and_remove_front() {
1109 assert_eq!(truncate_and_remove_front("", 5), "");
1110 assert_eq!(truncate_and_remove_front("aaaaaa", 7), "aaaaaa");
1111 assert_eq!(truncate_and_remove_front("aaaaaa", 6), "aaaaaa");
1112 assert_eq!(truncate_and_remove_front("aaaaaa", 5), "β¦aaaaa");
1113 assert_eq!(truncate_and_remove_front("èèèèèè", 7), "èèèèèè");
1114 assert_eq!(truncate_and_remove_front("èèèèèè", 6), "èèèèèè");
1115 assert_eq!(truncate_and_remove_front("èèèèèè", 5), "β¦Γ¨Γ¨Γ¨Γ¨Γ¨");
1116 }
1117
1118 #[test]
1119 fn test_numeric_prefix_str_method() {
1120 let target = "1a";
1121 assert_eq!(
1122 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1123 NumericPrefixWithSuffix(Some(1), "a")
1124 );
1125
1126 let target = "12ab";
1127 assert_eq!(
1128 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1129 NumericPrefixWithSuffix(Some(12), "ab")
1130 );
1131
1132 let target = "12_ab";
1133 assert_eq!(
1134 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1135 NumericPrefixWithSuffix(Some(12), "_ab")
1136 );
1137
1138 let target = "1_2ab";
1139 assert_eq!(
1140 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1141 NumericPrefixWithSuffix(Some(1), "_2ab")
1142 );
1143
1144 let target = "1.2";
1145 assert_eq!(
1146 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1147 NumericPrefixWithSuffix(Some(1), ".2")
1148 );
1149
1150 let target = "1.2_a";
1151 assert_eq!(
1152 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1153 NumericPrefixWithSuffix(Some(1), ".2_a")
1154 );
1155
1156 let target = "12.2_a";
1157 assert_eq!(
1158 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1159 NumericPrefixWithSuffix(Some(12), ".2_a")
1160 );
1161
1162 let target = "12a.2_a";
1163 assert_eq!(
1164 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1165 NumericPrefixWithSuffix(Some(12), "a.2_a")
1166 );
1167 }
1168
1169 #[test]
1170 fn test_numeric_prefix_with_suffix() {
1171 let mut sorted = vec!["1-abc", "10", "11def", "2", "21-abc"];
1172 sorted.sort_by_key(|s| NumericPrefixWithSuffix::from_numeric_prefixed_str(s));
1173 assert_eq!(sorted, ["1-abc", "2", "10", "11def", "21-abc"]);
1174
1175 for numeric_prefix_less in ["numeric_prefix_less", "aaa", "~β’Β£"] {
1176 assert_eq!(
1177 NumericPrefixWithSuffix::from_numeric_prefixed_str(numeric_prefix_less),
1178 NumericPrefixWithSuffix(None, numeric_prefix_less),
1179 "String without numeric prefix `{numeric_prefix_less}` should not be converted into NumericPrefixWithSuffix"
1180 )
1181 }
1182 }
1183
1184 #[test]
1185 fn test_word_consists_of_emojis() {
1186 let words_to_test = vec![
1187 ("π¨βπ©βπ§βπ§ππ₯", true),
1188 ("π", true),
1189 ("!π", false),
1190 ("π!", false),
1191 ("π ", false),
1192 (" π", false),
1193 ("Test", false),
1194 ];
1195
1196 for (text, expected_result) in words_to_test {
1197 assert_eq!(word_consists_of_emojis(text), expected_result);
1198 }
1199 }
1200
1201 #[test]
1202 fn test_truncate_lines_and_trailoff() {
1203 let text = r#"Line 1
1204Line 2
1205Line 3"#;
1206
1207 assert_eq!(
1208 truncate_lines_and_trailoff(text, 2),
1209 r#"Line 1
1210β¦"#
1211 );
1212
1213 assert_eq!(
1214 truncate_lines_and_trailoff(text, 3),
1215 r#"Line 1
1216Line 2
1217β¦"#
1218 );
1219
1220 assert_eq!(
1221 truncate_lines_and_trailoff(text, 4),
1222 r#"Line 1
1223Line 2
1224Line 3"#
1225 );
1226 }
1227
1228 #[test]
1229 fn test_expanded_and_wrapped_usize_range() {
1230 // Neither wrap
1231 assert_eq!(
1232 expanded_and_wrapped_usize_range(2..4, 1, 1, 8).collect::<Vec<usize>>(),
1233 (1..5).collect::<Vec<usize>>()
1234 );
1235 // Start wraps
1236 assert_eq!(
1237 expanded_and_wrapped_usize_range(2..4, 3, 1, 8).collect::<Vec<usize>>(),
1238 ((0..5).chain(7..8)).collect::<Vec<usize>>()
1239 );
1240 // Start wraps all the way around
1241 assert_eq!(
1242 expanded_and_wrapped_usize_range(2..4, 5, 1, 8).collect::<Vec<usize>>(),
1243 (0..8).collect::<Vec<usize>>()
1244 );
1245 // Start wraps all the way around and past 0
1246 assert_eq!(
1247 expanded_and_wrapped_usize_range(2..4, 10, 1, 8).collect::<Vec<usize>>(),
1248 (0..8).collect::<Vec<usize>>()
1249 );
1250 // End wraps
1251 assert_eq!(
1252 expanded_and_wrapped_usize_range(3..5, 1, 4, 8).collect::<Vec<usize>>(),
1253 (0..1).chain(2..8).collect::<Vec<usize>>()
1254 );
1255 // End wraps all the way around
1256 assert_eq!(
1257 expanded_and_wrapped_usize_range(3..5, 1, 5, 8).collect::<Vec<usize>>(),
1258 (0..8).collect::<Vec<usize>>()
1259 );
1260 // End wraps all the way around and past the end
1261 assert_eq!(
1262 expanded_and_wrapped_usize_range(3..5, 1, 10, 8).collect::<Vec<usize>>(),
1263 (0..8).collect::<Vec<usize>>()
1264 );
1265 // Both start and end wrap
1266 assert_eq!(
1267 expanded_and_wrapped_usize_range(3..5, 4, 4, 8).collect::<Vec<usize>>(),
1268 (0..8).collect::<Vec<usize>>()
1269 );
1270 }
1271
1272 #[test]
1273 fn test_wrapped_usize_outward_from() {
1274 // No wrapping
1275 assert_eq!(
1276 wrapped_usize_outward_from(4, 2, 2, 10).collect::<Vec<usize>>(),
1277 vec![4, 5, 3, 6, 2]
1278 );
1279 // Wrapping at end
1280 assert_eq!(
1281 wrapped_usize_outward_from(8, 2, 3, 10).collect::<Vec<usize>>(),
1282 vec![8, 9, 7, 0, 6, 1]
1283 );
1284 // Wrapping at start
1285 assert_eq!(
1286 wrapped_usize_outward_from(1, 3, 2, 10).collect::<Vec<usize>>(),
1287 vec![1, 2, 0, 3, 9, 8]
1288 );
1289 // All values wrap around
1290 assert_eq!(
1291 wrapped_usize_outward_from(5, 10, 10, 8).collect::<Vec<usize>>(),
1292 vec![5, 6, 4, 7, 3, 0, 2, 1]
1293 );
1294 // None before / after
1295 assert_eq!(
1296 wrapped_usize_outward_from(3, 0, 0, 8).collect::<Vec<usize>>(),
1297 vec![3]
1298 );
1299 // Starting point already wrapped
1300 assert_eq!(
1301 wrapped_usize_outward_from(15, 2, 2, 10).collect::<Vec<usize>>(),
1302 vec![5, 6, 4, 7, 3]
1303 );
1304 // wrap_length of 0
1305 assert_eq!(
1306 wrapped_usize_outward_from(4, 2, 2, 0).collect::<Vec<usize>>(),
1307 Vec::<usize>::new()
1308 );
1309 }
1310
1311 #[test]
1312 fn test_split_with_ranges() {
1313 let input = "hi";
1314 let result = split_str_with_ranges(input, |c| c == ' ');
1315
1316 assert_eq!(result.len(), 1);
1317 assert_eq!(result[0], (0..2, "hi"));
1318
1319 let input = "hΓ©lloπ¦world";
1320 let result = split_str_with_ranges(input, |c| c == 'π¦');
1321
1322 assert_eq!(result.len(), 2);
1323 assert_eq!(result[0], (0..6, "hΓ©llo")); // 'Γ©' is 2 bytes
1324 assert_eq!(result[1], (10..15, "world")); // 'π¦' is 4 bytes
1325 }
1326}