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