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