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