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