1use globset::{Glob, GlobSet, GlobSetBuilder};
2use regex::Regex;
3use serde::{Deserialize, Serialize};
4use std::cmp::Ordering;
5use std::fmt::{Display, Formatter};
6use std::mem;
7use std::path::StripPrefixError;
8use std::sync::{Arc, OnceLock};
9use std::{
10 ffi::OsStr,
11 path::{Path, PathBuf},
12 sync::LazyLock,
13};
14
15use crate::rel_path::RelPath;
16
17static HOME_DIR: OnceLock<PathBuf> = OnceLock::new();
18
19/// Returns the path to the user's home directory.
20pub fn home_dir() -> &'static PathBuf {
21 HOME_DIR.get_or_init(|| {
22 if cfg!(any(test, feature = "test-support")) {
23 if cfg!(target_os = "macos") {
24 PathBuf::from("/Users/zed")
25 } else if cfg!(target_os = "windows") {
26 PathBuf::from("C:\\Users\\zed")
27 } else {
28 PathBuf::from("/home/zed")
29 }
30 } else {
31 dirs::home_dir().expect("failed to determine home directory")
32 }
33 })
34}
35
36pub trait PathExt {
37 fn compact(&self) -> PathBuf;
38 fn extension_or_hidden_file_name(&self) -> Option<&str>;
39 fn try_from_bytes<'a>(bytes: &'a [u8]) -> anyhow::Result<Self>
40 where
41 Self: From<&'a Path>,
42 {
43 #[cfg(unix)]
44 {
45 use std::os::unix::prelude::OsStrExt;
46 Ok(Self::from(Path::new(OsStr::from_bytes(bytes))))
47 }
48 #[cfg(windows)]
49 {
50 use anyhow::Context as _;
51 use tendril::fmt::{Format, WTF8};
52 WTF8::validate(bytes)
53 .then(|| {
54 // Safety: bytes are valid WTF-8 sequence.
55 Self::from(Path::new(unsafe {
56 OsStr::from_encoded_bytes_unchecked(bytes)
57 }))
58 })
59 .with_context(|| format!("Invalid WTF-8 sequence: {bytes:?}"))
60 }
61 }
62 fn local_to_wsl(&self) -> Option<PathBuf>;
63}
64
65impl<T: AsRef<Path>> PathExt for T {
66 /// Compacts a given file path by replacing the user's home directory
67 /// prefix with a tilde (`~`).
68 ///
69 /// # Returns
70 ///
71 /// * A `PathBuf` containing the compacted file path. If the input path
72 /// does not have the user's home directory prefix, or if we are not on
73 /// Linux or macOS, the original path is returned unchanged.
74 fn compact(&self) -> PathBuf {
75 if cfg!(any(target_os = "linux", target_os = "freebsd")) || cfg!(target_os = "macos") {
76 match self.as_ref().strip_prefix(home_dir().as_path()) {
77 Ok(relative_path) => {
78 let mut shortened_path = PathBuf::new();
79 shortened_path.push("~");
80 shortened_path.push(relative_path);
81 shortened_path
82 }
83 Err(_) => self.as_ref().to_path_buf(),
84 }
85 } else {
86 self.as_ref().to_path_buf()
87 }
88 }
89
90 /// Returns a file's extension or, if the file is hidden, its name without the leading dot
91 fn extension_or_hidden_file_name(&self) -> Option<&str> {
92 let path = self.as_ref();
93 let file_name = path.file_name()?.to_str()?;
94 if file_name.starts_with('.') {
95 return file_name.strip_prefix('.');
96 }
97
98 path.extension()
99 .and_then(|e| e.to_str())
100 .or_else(|| path.file_stem()?.to_str())
101 }
102
103 /// Converts a local path to one that can be used inside of WSL.
104 /// Returns `None` if the path cannot be converted into a WSL one (network share).
105 fn local_to_wsl(&self) -> Option<PathBuf> {
106 let mut new_path = PathBuf::new();
107 for component in self.as_ref().components() {
108 match component {
109 std::path::Component::Prefix(prefix) => {
110 let drive_letter = prefix.as_os_str().to_string_lossy().to_lowercase();
111 let drive_letter = drive_letter.strip_suffix(':')?;
112
113 new_path.push(format!("/mnt/{}", drive_letter));
114 }
115 std::path::Component::RootDir => {}
116 _ => new_path.push(component),
117 }
118 }
119
120 Some(new_path)
121 }
122}
123
124/// In memory, this is identical to `Path`. On non-Windows conversions to this type are no-ops. On
125/// windows, these conversions sanitize UNC paths by removing the `\\\\?\\` prefix.
126#[derive(Eq, PartialEq, Hash, Ord, PartialOrd)]
127#[repr(transparent)]
128pub struct SanitizedPath(Path);
129
130impl SanitizedPath {
131 pub fn new<T: AsRef<Path> + ?Sized>(path: &T) -> &Self {
132 #[cfg(not(target_os = "windows"))]
133 return Self::unchecked_new(path.as_ref());
134
135 #[cfg(target_os = "windows")]
136 return Self::unchecked_new(dunce::simplified(path.as_ref()));
137 }
138
139 pub fn unchecked_new<T: AsRef<Path> + ?Sized>(path: &T) -> &Self {
140 // safe because `Path` and `SanitizedPath` have the same repr and Drop impl
141 unsafe { mem::transmute::<&Path, &Self>(path.as_ref()) }
142 }
143
144 pub fn from_arc(path: Arc<Path>) -> Arc<Self> {
145 // safe because `Path` and `SanitizedPath` have the same repr and Drop impl
146 #[cfg(not(target_os = "windows"))]
147 return unsafe { mem::transmute::<Arc<Path>, Arc<Self>>(path) };
148
149 // TODO: could avoid allocating here if dunce::simplified results in the same path
150 #[cfg(target_os = "windows")]
151 return Self::new(&path).into();
152 }
153
154 pub fn new_arc<T: AsRef<Path> + ?Sized>(path: &T) -> Arc<Self> {
155 Self::new(path).into()
156 }
157
158 pub fn cast_arc(path: Arc<Self>) -> Arc<Path> {
159 // safe because `Path` and `SanitizedPath` have the same repr and Drop impl
160 unsafe { mem::transmute::<Arc<Self>, Arc<Path>>(path) }
161 }
162
163 pub fn cast_arc_ref(path: &Arc<Self>) -> &Arc<Path> {
164 // safe because `Path` and `SanitizedPath` have the same repr and Drop impl
165 unsafe { mem::transmute::<&Arc<Self>, &Arc<Path>>(path) }
166 }
167
168 pub fn starts_with(&self, prefix: &Self) -> bool {
169 self.0.starts_with(&prefix.0)
170 }
171
172 pub fn as_path(&self) -> &Path {
173 &self.0
174 }
175
176 pub fn file_name(&self) -> Option<&std::ffi::OsStr> {
177 self.0.file_name()
178 }
179
180 pub fn extension(&self) -> Option<&std::ffi::OsStr> {
181 self.0.extension()
182 }
183
184 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
185 self.0.join(path)
186 }
187
188 pub fn parent(&self) -> Option<&Self> {
189 self.0.parent().map(Self::unchecked_new)
190 }
191
192 pub fn strip_prefix(&self, base: &Self) -> Result<&Path, StripPrefixError> {
193 self.0.strip_prefix(base.as_path())
194 }
195
196 pub fn to_str(&self) -> Option<&str> {
197 self.0.to_str()
198 }
199
200 pub fn to_path_buf(&self) -> PathBuf {
201 self.0.to_path_buf()
202 }
203}
204
205impl std::fmt::Debug for SanitizedPath {
206 fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
207 std::fmt::Debug::fmt(&self.0, formatter)
208 }
209}
210
211impl Display for SanitizedPath {
212 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
213 write!(f, "{}", self.0.display())
214 }
215}
216
217impl From<&SanitizedPath> for Arc<SanitizedPath> {
218 fn from(sanitized_path: &SanitizedPath) -> Self {
219 let path: Arc<Path> = sanitized_path.0.into();
220 // safe because `Path` and `SanitizedPath` have the same repr and Drop impl
221 unsafe { mem::transmute(path) }
222 }
223}
224
225impl From<&SanitizedPath> for PathBuf {
226 fn from(sanitized_path: &SanitizedPath) -> Self {
227 sanitized_path.as_path().into()
228 }
229}
230
231impl AsRef<Path> for SanitizedPath {
232 fn as_ref(&self) -> &Path {
233 &self.0
234 }
235}
236
237#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
238pub enum PathStyle {
239 Posix,
240 Windows,
241}
242
243impl PathStyle {
244 #[cfg(target_os = "windows")]
245 pub const fn local() -> Self {
246 PathStyle::Windows
247 }
248
249 #[cfg(not(target_os = "windows"))]
250 pub const fn local() -> Self {
251 PathStyle::Posix
252 }
253
254 #[inline]
255 pub fn separator(&self) -> &'static str {
256 match self {
257 PathStyle::Posix => "/",
258 PathStyle::Windows => "\\",
259 }
260 }
261
262 pub fn is_windows(&self) -> bool {
263 *self == PathStyle::Windows
264 }
265
266 pub fn join(self, left: impl AsRef<Path>, right: impl AsRef<Path>) -> Option<String> {
267 let right = right.as_ref().to_str()?;
268 if is_absolute(right, self) {
269 return None;
270 }
271 let left = left.as_ref().to_str()?;
272 if left.is_empty() {
273 Some(right.into())
274 } else {
275 Some(format!(
276 "{left}{}{right}",
277 if left.ends_with(self.separator()) {
278 ""
279 } else {
280 self.separator()
281 }
282 ))
283 }
284 }
285
286 pub fn split(self, path_like: &str) -> (Option<&str>, &str) {
287 let Some(pos) = path_like.rfind(self.separator()) else {
288 return (None, path_like);
289 };
290 let filename_start = pos + self.separator().len();
291 (
292 Some(&path_like[..filename_start]),
293 &path_like[filename_start..],
294 )
295 }
296}
297
298#[derive(Debug, Clone)]
299pub struct RemotePathBuf {
300 style: PathStyle,
301 string: String,
302}
303
304impl RemotePathBuf {
305 pub fn new(string: String, style: PathStyle) -> Self {
306 Self { style, string }
307 }
308
309 pub fn from_str(path: &str, style: PathStyle) -> Self {
310 Self::new(path.to_string(), style)
311 }
312
313 pub fn path_style(&self) -> PathStyle {
314 self.style
315 }
316
317 pub fn to_proto(self) -> String {
318 self.string
319 }
320}
321
322impl Display for RemotePathBuf {
323 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
324 write!(f, "{}", self.string)
325 }
326}
327
328pub fn is_absolute(path_like: &str, path_style: PathStyle) -> bool {
329 path_like.starts_with('/')
330 || path_style == PathStyle::Windows
331 && (path_like.starts_with('\\')
332 || path_like
333 .chars()
334 .next()
335 .is_some_and(|c| c.is_ascii_alphabetic())
336 && path_like[1..]
337 .strip_prefix(':')
338 .is_some_and(|path| path.starts_with('/') || path.starts_with('\\')))
339}
340
341/// A delimiter to use in `path_query:row_number:column_number` strings parsing.
342pub const FILE_ROW_COLUMN_DELIMITER: char = ':';
343
344const ROW_COL_CAPTURE_REGEX: &str = r"(?xs)
345 ([^\(]+)\:(?:
346 \((\d+)[,:](\d+)\) # filename:(row,column), filename:(row:column)
347 |
348 \((\d+)\)() # filename:(row)
349 )
350 |
351 ([^\(]+)(?:
352 \((\d+)[,:](\d+)\) # filename(row,column), filename(row:column)
353 |
354 \((\d+)\)() # filename(row)
355 )
356 |
357 (.+?)(?:
358 \:+(\d+)\:(\d+)\:*$ # filename:row:column
359 |
360 \:+(\d+)\:*()$ # filename:row
361 |
362 \:+()()$
363 )";
364
365/// A representation of a path-like string with optional row and column numbers.
366/// Matching values example: `te`, `test.rs:22`, `te:22:5`, `test.c(22)`, `test.c(22,5)`etc.
367#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
368pub struct PathWithPosition {
369 pub path: PathBuf,
370 pub row: Option<u32>,
371 // Absent if row is absent.
372 pub column: Option<u32>,
373}
374
375impl PathWithPosition {
376 /// Returns a PathWithPosition from a path.
377 pub fn from_path(path: PathBuf) -> Self {
378 Self {
379 path,
380 row: None,
381 column: None,
382 }
383 }
384
385 /// Parses a string that possibly has `:row:column` or `(row, column)` suffix.
386 /// Parenthesis format is used by [MSBuild](https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-diagnostic-format-for-tasks) compatible tools
387 /// Ignores trailing `:`s, so `test.rs:22:` is parsed as `test.rs:22`.
388 /// If the suffix parsing fails, the whole string is parsed as a path.
389 ///
390 /// Be mindful that `test_file:10:1:` is a valid posix filename.
391 /// `PathWithPosition` class assumes that the ending position-like suffix is **not** part of the filename.
392 ///
393 /// # Examples
394 ///
395 /// ```
396 /// # use util::paths::PathWithPosition;
397 /// # use std::path::PathBuf;
398 /// assert_eq!(PathWithPosition::parse_str("test_file"), PathWithPosition {
399 /// path: PathBuf::from("test_file"),
400 /// row: None,
401 /// column: None,
402 /// });
403 /// assert_eq!(PathWithPosition::parse_str("test_file:10"), PathWithPosition {
404 /// path: PathBuf::from("test_file"),
405 /// row: Some(10),
406 /// column: None,
407 /// });
408 /// assert_eq!(PathWithPosition::parse_str("test_file.rs"), PathWithPosition {
409 /// path: PathBuf::from("test_file.rs"),
410 /// row: None,
411 /// column: None,
412 /// });
413 /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1"), PathWithPosition {
414 /// path: PathBuf::from("test_file.rs"),
415 /// row: Some(1),
416 /// column: None,
417 /// });
418 /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1:2"), PathWithPosition {
419 /// path: PathBuf::from("test_file.rs"),
420 /// row: Some(1),
421 /// column: Some(2),
422 /// });
423 /// ```
424 ///
425 /// # Expected parsing results when encounter ill-formatted inputs.
426 /// ```
427 /// # use util::paths::PathWithPosition;
428 /// # use std::path::PathBuf;
429 /// assert_eq!(PathWithPosition::parse_str("test_file.rs:a"), PathWithPosition {
430 /// path: PathBuf::from("test_file.rs:a"),
431 /// row: None,
432 /// column: None,
433 /// });
434 /// assert_eq!(PathWithPosition::parse_str("test_file.rs:a:b"), PathWithPosition {
435 /// path: PathBuf::from("test_file.rs:a:b"),
436 /// row: None,
437 /// column: None,
438 /// });
439 /// assert_eq!(PathWithPosition::parse_str("test_file.rs"), PathWithPosition {
440 /// path: PathBuf::from("test_file.rs"),
441 /// row: None,
442 /// column: None,
443 /// });
444 /// assert_eq!(PathWithPosition::parse_str("test_file.rs::1"), PathWithPosition {
445 /// path: PathBuf::from("test_file.rs"),
446 /// row: Some(1),
447 /// column: None,
448 /// });
449 /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1::"), PathWithPosition {
450 /// path: PathBuf::from("test_file.rs"),
451 /// row: Some(1),
452 /// column: None,
453 /// });
454 /// assert_eq!(PathWithPosition::parse_str("test_file.rs::1:2"), PathWithPosition {
455 /// path: PathBuf::from("test_file.rs"),
456 /// row: Some(1),
457 /// column: Some(2),
458 /// });
459 /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1::2"), PathWithPosition {
460 /// path: PathBuf::from("test_file.rs:1"),
461 /// row: Some(2),
462 /// column: None,
463 /// });
464 /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1:2:3"), PathWithPosition {
465 /// path: PathBuf::from("test_file.rs:1"),
466 /// row: Some(2),
467 /// column: Some(3),
468 /// });
469 /// ```
470 pub fn parse_str(s: &str) -> Self {
471 let trimmed = s.trim();
472 let path = Path::new(trimmed);
473 let maybe_file_name_with_row_col = path.file_name().unwrap_or_default().to_string_lossy();
474 if maybe_file_name_with_row_col.is_empty() {
475 return Self {
476 path: Path::new(s).to_path_buf(),
477 row: None,
478 column: None,
479 };
480 }
481
482 // Let's avoid repeated init cost on this. It is subject to thread contention, but
483 // so far this code isn't called from multiple hot paths. Getting contention here
484 // in the future seems unlikely.
485 static SUFFIX_RE: LazyLock<Regex> =
486 LazyLock::new(|| Regex::new(ROW_COL_CAPTURE_REGEX).unwrap());
487 match SUFFIX_RE
488 .captures(&maybe_file_name_with_row_col)
489 .map(|caps| caps.extract())
490 {
491 Some((_, [file_name, maybe_row, maybe_column])) => {
492 let row = maybe_row.parse::<u32>().ok();
493 let column = maybe_column.parse::<u32>().ok();
494
495 let suffix_length = maybe_file_name_with_row_col.len() - file_name.len();
496 let path_without_suffix = &trimmed[..trimmed.len() - suffix_length];
497
498 Self {
499 path: Path::new(path_without_suffix).to_path_buf(),
500 row,
501 column,
502 }
503 }
504 None => {
505 // The `ROW_COL_CAPTURE_REGEX` deals with separated digits only,
506 // but in reality there could be `foo/bar.py:22:in` inputs which we want to match too.
507 // The regex mentioned is not very extendable with "digit or random string" checks, so do this here instead.
508 let delimiter = ':';
509 let mut path_parts = s
510 .rsplitn(3, delimiter)
511 .collect::<Vec<_>>()
512 .into_iter()
513 .rev()
514 .fuse();
515 let mut path_string = path_parts.next().expect("rsplitn should have the rest of the string as its last parameter that we reversed").to_owned();
516 let mut row = None;
517 let mut column = None;
518 if let Some(maybe_row) = path_parts.next() {
519 if let Ok(parsed_row) = maybe_row.parse::<u32>() {
520 row = Some(parsed_row);
521 if let Some(parsed_column) = path_parts
522 .next()
523 .and_then(|maybe_col| maybe_col.parse::<u32>().ok())
524 {
525 column = Some(parsed_column);
526 }
527 } else {
528 path_string.push(delimiter);
529 path_string.push_str(maybe_row);
530 }
531 }
532 for split in path_parts {
533 path_string.push(delimiter);
534 path_string.push_str(split);
535 }
536
537 Self {
538 path: PathBuf::from(path_string),
539 row,
540 column,
541 }
542 }
543 }
544 }
545
546 pub fn map_path<E>(
547 self,
548 mapping: impl FnOnce(PathBuf) -> Result<PathBuf, E>,
549 ) -> Result<PathWithPosition, E> {
550 Ok(PathWithPosition {
551 path: mapping(self.path)?,
552 row: self.row,
553 column: self.column,
554 })
555 }
556
557 pub fn to_string(&self, path_to_string: impl Fn(&PathBuf) -> String) -> String {
558 let path_string = path_to_string(&self.path);
559 if let Some(row) = self.row {
560 if let Some(column) = self.column {
561 format!("{path_string}:{row}:{column}")
562 } else {
563 format!("{path_string}:{row}")
564 }
565 } else {
566 path_string
567 }
568 }
569}
570
571#[derive(Clone, Debug)]
572pub struct PathMatcher {
573 sources: Vec<String>,
574 glob: GlobSet,
575 path_style: PathStyle,
576}
577
578// impl std::fmt::Display for PathMatcher {
579// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
580// self.sources.fmt(f)
581// }
582// }
583
584impl PartialEq for PathMatcher {
585 fn eq(&self, other: &Self) -> bool {
586 self.sources.eq(&other.sources)
587 }
588}
589
590impl Eq for PathMatcher {}
591
592impl PathMatcher {
593 pub fn new(
594 globs: impl IntoIterator<Item = impl AsRef<str>>,
595 path_style: PathStyle,
596 ) -> Result<Self, globset::Error> {
597 let globs = globs
598 .into_iter()
599 .map(|as_str| Glob::new(as_str.as_ref()))
600 .collect::<Result<Vec<_>, _>>()?;
601 let sources = globs.iter().map(|glob| glob.glob().to_owned()).collect();
602 let mut glob_builder = GlobSetBuilder::new();
603 for single_glob in globs {
604 glob_builder.add(single_glob);
605 }
606 let glob = glob_builder.build()?;
607 Ok(PathMatcher {
608 glob,
609 sources,
610 path_style,
611 })
612 }
613
614 pub fn sources(&self) -> &[String] {
615 &self.sources
616 }
617
618 pub fn is_match<P: AsRef<Path>>(&self, other: P) -> bool {
619 let other_path = other.as_ref();
620 self.sources.iter().any(|source| {
621 let as_bytes = other_path.as_os_str().as_encoded_bytes();
622 as_bytes.starts_with(source.as_bytes()) || as_bytes.ends_with(source.as_bytes())
623 }) || self.glob.is_match(other_path)
624 || self.check_with_end_separator(other_path)
625 }
626
627 fn check_with_end_separator(&self, path: &Path) -> bool {
628 let path_str = path.to_string_lossy();
629 let separator = self.path_style.separator();
630 if path_str.ends_with(separator) {
631 false
632 } else {
633 self.glob.is_match(path_str.to_string() + separator)
634 }
635 }
636}
637
638impl Default for PathMatcher {
639 fn default() -> Self {
640 Self {
641 path_style: PathStyle::local(),
642 glob: GlobSet::empty(),
643 sources: vec![],
644 }
645 }
646}
647
648/// Custom character comparison that prioritizes lowercase for same letters
649fn compare_chars(a: char, b: char) -> Ordering {
650 // First compare case-insensitive
651 match a.to_ascii_lowercase().cmp(&b.to_ascii_lowercase()) {
652 Ordering::Equal => {
653 // If same letter, prioritize lowercase (lowercase < uppercase)
654 match (a.is_ascii_lowercase(), b.is_ascii_lowercase()) {
655 (true, false) => Ordering::Less, // lowercase comes first
656 (false, true) => Ordering::Greater, // uppercase comes after
657 _ => Ordering::Equal, // both same case or both non-ascii
658 }
659 }
660 other => other,
661 }
662}
663
664/// Compares two sequences of consecutive digits for natural sorting.
665///
666/// This function is a core component of natural sorting that handles numeric comparison
667/// in a way that feels natural to humans. It extracts and compares consecutive digit
668/// sequences from two iterators, handling various cases like leading zeros and very large numbers.
669///
670/// # Behavior
671///
672/// The function implements the following comparison rules:
673/// 1. Different numeric values: Compares by actual numeric value (e.g., "2" < "10")
674/// 2. Leading zeros: When values are equal, longer sequence wins (e.g., "002" > "2")
675/// 3. Large numbers: Falls back to string comparison for numbers that would overflow u128
676///
677/// # Examples
678///
679/// ```text
680/// "1" vs "2" -> Less (different values)
681/// "2" vs "10" -> Less (numeric comparison)
682/// "002" vs "2" -> Greater (leading zeros)
683/// "10" vs "010" -> Less (leading zeros)
684/// "999..." vs "1000..." -> Less (large number comparison)
685/// ```
686///
687/// # Implementation Details
688///
689/// 1. Extracts consecutive digits into strings
690/// 2. Compares sequence lengths for leading zero handling
691/// 3. For equal lengths, compares digit by digit
692/// 4. For different lengths:
693/// - Attempts numeric comparison first (for numbers up to 2^128 - 1)
694/// - Falls back to string comparison if numbers would overflow
695///
696/// The function advances both iterators past their respective numeric sequences,
697/// regardless of the comparison result.
698fn compare_numeric_segments<I>(
699 a_iter: &mut std::iter::Peekable<I>,
700 b_iter: &mut std::iter::Peekable<I>,
701) -> Ordering
702where
703 I: Iterator<Item = char>,
704{
705 // Collect all consecutive digits into strings
706 let mut a_num_str = String::new();
707 let mut b_num_str = String::new();
708
709 while let Some(&c) = a_iter.peek() {
710 if !c.is_ascii_digit() {
711 break;
712 }
713
714 a_num_str.push(c);
715 a_iter.next();
716 }
717
718 while let Some(&c) = b_iter.peek() {
719 if !c.is_ascii_digit() {
720 break;
721 }
722
723 b_num_str.push(c);
724 b_iter.next();
725 }
726
727 // First compare lengths (handle leading zeros)
728 match a_num_str.len().cmp(&b_num_str.len()) {
729 Ordering::Equal => {
730 // Same length, compare digit by digit
731 match a_num_str.cmp(&b_num_str) {
732 Ordering::Equal => Ordering::Equal,
733 ordering => ordering,
734 }
735 }
736
737 // Different lengths but same value means leading zeros
738 ordering => {
739 // Try parsing as numbers first
740 if let (Ok(a_val), Ok(b_val)) = (a_num_str.parse::<u128>(), b_num_str.parse::<u128>()) {
741 match a_val.cmp(&b_val) {
742 Ordering::Equal => ordering, // Same value, longer one is greater (leading zeros)
743 ord => ord,
744 }
745 } else {
746 // If parsing fails (overflow), compare as strings
747 a_num_str.cmp(&b_num_str)
748 }
749 }
750 }
751}
752
753/// Performs natural sorting comparison between two strings.
754///
755/// Natural sorting is an ordering that handles numeric sequences in a way that matches human expectations.
756/// For example, "file2" comes before "file10" (unlike standard lexicographic sorting).
757///
758/// # Characteristics
759///
760/// * Case-sensitive with lowercase priority: When comparing same letters, lowercase comes before uppercase
761/// * Numbers are compared by numeric value, not character by character
762/// * Leading zeros affect ordering when numeric values are equal
763/// * Can handle numbers larger than u128::MAX (falls back to string comparison)
764///
765/// # Algorithm
766///
767/// The function works by:
768/// 1. Processing strings character by character
769/// 2. When encountering digits, treating consecutive digits as a single number
770/// 3. Comparing numbers by their numeric value rather than lexicographically
771/// 4. For non-numeric characters, using case-sensitive comparison with lowercase priority
772fn natural_sort(a: &str, b: &str) -> Ordering {
773 let mut a_iter = a.chars().peekable();
774 let mut b_iter = b.chars().peekable();
775
776 loop {
777 match (a_iter.peek(), b_iter.peek()) {
778 (None, None) => return Ordering::Equal,
779 (None, _) => return Ordering::Less,
780 (_, None) => return Ordering::Greater,
781 (Some(&a_char), Some(&b_char)) => {
782 if a_char.is_ascii_digit() && b_char.is_ascii_digit() {
783 match compare_numeric_segments(&mut a_iter, &mut b_iter) {
784 Ordering::Equal => continue,
785 ordering => return ordering,
786 }
787 } else {
788 match compare_chars(a_char, b_char) {
789 Ordering::Equal => {
790 a_iter.next();
791 b_iter.next();
792 }
793 ordering => return ordering,
794 }
795 }
796 }
797 }
798 }
799}
800pub fn compare_rel_paths(
801 (path_a, a_is_file): (&RelPath, bool),
802 (path_b, b_is_file): (&RelPath, bool),
803) -> Ordering {
804 let mut components_a = path_a.components();
805 let mut components_b = path_b.components();
806
807 fn stem_and_extension(filename: &str) -> (Option<&str>, Option<&str>) {
808 if filename.is_empty() {
809 return (None, None);
810 }
811
812 match filename.rsplit_once('.') {
813 // Case 1: No dot was found. The entire name is the stem.
814 None => (Some(filename), None),
815
816 // Case 2: A dot was found.
817 Some((before, after)) => {
818 // This is the crucial check for dotfiles like ".bashrc".
819 // If `before` is empty, the dot was the first character.
820 // In that case, we revert to the "whole name is the stem" logic.
821 if before.is_empty() {
822 (Some(filename), None)
823 } else {
824 // Otherwise, we have a standard stem and extension.
825 (Some(before), Some(after))
826 }
827 }
828 }
829 }
830 loop {
831 match (components_a.next(), components_b.next()) {
832 (Some(component_a), Some(component_b)) => {
833 let a_is_file = a_is_file && components_a.rest().is_empty();
834 let b_is_file = b_is_file && components_b.rest().is_empty();
835
836 let ordering = a_is_file.cmp(&b_is_file).then_with(|| {
837 let (a_stem, a_extension) = a_is_file
838 .then(|| stem_and_extension(component_a))
839 .unwrap_or_default();
840 let path_string_a = if a_is_file { a_stem } else { Some(component_a) };
841
842 let (b_stem, b_extension) = b_is_file
843 .then(|| stem_and_extension(component_b))
844 .unwrap_or_default();
845 let path_string_b = if b_is_file { b_stem } else { Some(component_b) };
846
847 let compare_components = match (path_string_a, path_string_b) {
848 (Some(a), Some(b)) => natural_sort(&a, &b),
849 (Some(_), None) => Ordering::Greater,
850 (None, Some(_)) => Ordering::Less,
851 (None, None) => Ordering::Equal,
852 };
853
854 compare_components.then_with(|| {
855 if a_is_file && b_is_file {
856 let ext_a = a_extension.unwrap_or_default();
857 let ext_b = b_extension.unwrap_or_default();
858 ext_a.cmp(ext_b)
859 } else {
860 Ordering::Equal
861 }
862 })
863 });
864
865 if !ordering.is_eq() {
866 return ordering;
867 }
868 }
869 (Some(_), None) => break Ordering::Greater,
870 (None, Some(_)) => break Ordering::Less,
871 (None, None) => break Ordering::Equal,
872 }
873 }
874}
875
876pub fn compare_paths(
877 (path_a, a_is_file): (&Path, bool),
878 (path_b, b_is_file): (&Path, bool),
879) -> Ordering {
880 let mut components_a = path_a.components().peekable();
881 let mut components_b = path_b.components().peekable();
882
883 loop {
884 match (components_a.next(), components_b.next()) {
885 (Some(component_a), Some(component_b)) => {
886 let a_is_file = components_a.peek().is_none() && a_is_file;
887 let b_is_file = components_b.peek().is_none() && b_is_file;
888
889 let ordering = a_is_file.cmp(&b_is_file).then_with(|| {
890 let path_a = Path::new(component_a.as_os_str());
891 let path_string_a = if a_is_file {
892 path_a.file_stem()
893 } else {
894 path_a.file_name()
895 }
896 .map(|s| s.to_string_lossy());
897
898 let path_b = Path::new(component_b.as_os_str());
899 let path_string_b = if b_is_file {
900 path_b.file_stem()
901 } else {
902 path_b.file_name()
903 }
904 .map(|s| s.to_string_lossy());
905
906 let compare_components = match (path_string_a, path_string_b) {
907 (Some(a), Some(b)) => natural_sort(&a, &b),
908 (Some(_), None) => Ordering::Greater,
909 (None, Some(_)) => Ordering::Less,
910 (None, None) => Ordering::Equal,
911 };
912
913 compare_components.then_with(|| {
914 if a_is_file && b_is_file {
915 let ext_a = path_a.extension().unwrap_or_default();
916 let ext_b = path_b.extension().unwrap_or_default();
917 ext_a.cmp(ext_b)
918 } else {
919 Ordering::Equal
920 }
921 })
922 });
923
924 if !ordering.is_eq() {
925 return ordering;
926 }
927 }
928 (Some(_), None) => break Ordering::Greater,
929 (None, Some(_)) => break Ordering::Less,
930 (None, None) => break Ordering::Equal,
931 }
932 }
933}
934
935#[cfg(test)]
936mod tests {
937 use super::*;
938 use util_macros::perf;
939
940 #[perf]
941 fn compare_paths_with_dots() {
942 let mut paths = vec![
943 (Path::new("test_dirs"), false),
944 (Path::new("test_dirs/1.46"), false),
945 (Path::new("test_dirs/1.46/bar_1"), true),
946 (Path::new("test_dirs/1.46/bar_2"), true),
947 (Path::new("test_dirs/1.45"), false),
948 (Path::new("test_dirs/1.45/foo_2"), true),
949 (Path::new("test_dirs/1.45/foo_1"), true),
950 ];
951 paths.sort_by(|&a, &b| compare_paths(a, b));
952 assert_eq!(
953 paths,
954 vec![
955 (Path::new("test_dirs"), false),
956 (Path::new("test_dirs/1.45"), false),
957 (Path::new("test_dirs/1.45/foo_1"), true),
958 (Path::new("test_dirs/1.45/foo_2"), true),
959 (Path::new("test_dirs/1.46"), false),
960 (Path::new("test_dirs/1.46/bar_1"), true),
961 (Path::new("test_dirs/1.46/bar_2"), true),
962 ]
963 );
964 let mut paths = vec![
965 (Path::new("root1/one.txt"), true),
966 (Path::new("root1/one.two.txt"), true),
967 ];
968 paths.sort_by(|&a, &b| compare_paths(a, b));
969 assert_eq!(
970 paths,
971 vec![
972 (Path::new("root1/one.txt"), true),
973 (Path::new("root1/one.two.txt"), true),
974 ]
975 );
976 }
977
978 #[perf]
979 fn compare_paths_with_same_name_different_extensions() {
980 let mut paths = vec![
981 (Path::new("test_dirs/file.rs"), true),
982 (Path::new("test_dirs/file.txt"), true),
983 (Path::new("test_dirs/file.md"), true),
984 (Path::new("test_dirs/file"), true),
985 (Path::new("test_dirs/file.a"), true),
986 ];
987 paths.sort_by(|&a, &b| compare_paths(a, b));
988 assert_eq!(
989 paths,
990 vec![
991 (Path::new("test_dirs/file"), true),
992 (Path::new("test_dirs/file.a"), true),
993 (Path::new("test_dirs/file.md"), true),
994 (Path::new("test_dirs/file.rs"), true),
995 (Path::new("test_dirs/file.txt"), true),
996 ]
997 );
998 }
999
1000 #[perf]
1001 fn compare_paths_case_semi_sensitive() {
1002 let mut paths = vec![
1003 (Path::new("test_DIRS"), false),
1004 (Path::new("test_DIRS/foo_1"), true),
1005 (Path::new("test_DIRS/foo_2"), true),
1006 (Path::new("test_DIRS/bar"), true),
1007 (Path::new("test_DIRS/BAR"), true),
1008 (Path::new("test_dirs"), false),
1009 (Path::new("test_dirs/foo_1"), true),
1010 (Path::new("test_dirs/foo_2"), true),
1011 (Path::new("test_dirs/bar"), true),
1012 (Path::new("test_dirs/BAR"), true),
1013 ];
1014 paths.sort_by(|&a, &b| compare_paths(a, b));
1015 assert_eq!(
1016 paths,
1017 vec![
1018 (Path::new("test_dirs"), false),
1019 (Path::new("test_dirs/bar"), true),
1020 (Path::new("test_dirs/BAR"), true),
1021 (Path::new("test_dirs/foo_1"), true),
1022 (Path::new("test_dirs/foo_2"), true),
1023 (Path::new("test_DIRS"), false),
1024 (Path::new("test_DIRS/bar"), true),
1025 (Path::new("test_DIRS/BAR"), true),
1026 (Path::new("test_DIRS/foo_1"), true),
1027 (Path::new("test_DIRS/foo_2"), true),
1028 ]
1029 );
1030 }
1031
1032 #[perf]
1033 fn path_with_position_parse_posix_path() {
1034 // Test POSIX filename edge cases
1035 // Read more at https://en.wikipedia.org/wiki/Filename
1036 assert_eq!(
1037 PathWithPosition::parse_str("test_file"),
1038 PathWithPosition {
1039 path: PathBuf::from("test_file"),
1040 row: None,
1041 column: None
1042 }
1043 );
1044
1045 assert_eq!(
1046 PathWithPosition::parse_str("a:bc:.zip:1"),
1047 PathWithPosition {
1048 path: PathBuf::from("a:bc:.zip"),
1049 row: Some(1),
1050 column: None
1051 }
1052 );
1053
1054 assert_eq!(
1055 PathWithPosition::parse_str("one.second.zip:1"),
1056 PathWithPosition {
1057 path: PathBuf::from("one.second.zip"),
1058 row: Some(1),
1059 column: None
1060 }
1061 );
1062
1063 // Trim off trailing `:`s for otherwise valid input.
1064 assert_eq!(
1065 PathWithPosition::parse_str("test_file:10:1:"),
1066 PathWithPosition {
1067 path: PathBuf::from("test_file"),
1068 row: Some(10),
1069 column: Some(1)
1070 }
1071 );
1072
1073 assert_eq!(
1074 PathWithPosition::parse_str("test_file.rs:"),
1075 PathWithPosition {
1076 path: PathBuf::from("test_file.rs"),
1077 row: None,
1078 column: None
1079 }
1080 );
1081
1082 assert_eq!(
1083 PathWithPosition::parse_str("test_file.rs:1:"),
1084 PathWithPosition {
1085 path: PathBuf::from("test_file.rs"),
1086 row: Some(1),
1087 column: None
1088 }
1089 );
1090
1091 assert_eq!(
1092 PathWithPosition::parse_str("ab\ncd"),
1093 PathWithPosition {
1094 path: PathBuf::from("ab\ncd"),
1095 row: None,
1096 column: None
1097 }
1098 );
1099
1100 assert_eq!(
1101 PathWithPosition::parse_str("👋\nab"),
1102 PathWithPosition {
1103 path: PathBuf::from("👋\nab"),
1104 row: None,
1105 column: None
1106 }
1107 );
1108
1109 assert_eq!(
1110 PathWithPosition::parse_str("Types.hs:(617,9)-(670,28):"),
1111 PathWithPosition {
1112 path: PathBuf::from("Types.hs"),
1113 row: Some(617),
1114 column: Some(9),
1115 }
1116 );
1117 }
1118
1119 #[perf]
1120 #[cfg(not(target_os = "windows"))]
1121 fn path_with_position_parse_posix_path_with_suffix() {
1122 assert_eq!(
1123 PathWithPosition::parse_str("foo/bar:34:in"),
1124 PathWithPosition {
1125 path: PathBuf::from("foo/bar"),
1126 row: Some(34),
1127 column: None,
1128 }
1129 );
1130 assert_eq!(
1131 PathWithPosition::parse_str("foo/bar.rs:1902:::15:"),
1132 PathWithPosition {
1133 path: PathBuf::from("foo/bar.rs:1902"),
1134 row: Some(15),
1135 column: None
1136 }
1137 );
1138
1139 assert_eq!(
1140 PathWithPosition::parse_str("app-editors:zed-0.143.6:20240710-201212.log:34:"),
1141 PathWithPosition {
1142 path: PathBuf::from("app-editors:zed-0.143.6:20240710-201212.log"),
1143 row: Some(34),
1144 column: None,
1145 }
1146 );
1147
1148 assert_eq!(
1149 PathWithPosition::parse_str("crates/file_finder/src/file_finder.rs:1902:13:"),
1150 PathWithPosition {
1151 path: PathBuf::from("crates/file_finder/src/file_finder.rs"),
1152 row: Some(1902),
1153 column: Some(13),
1154 }
1155 );
1156
1157 assert_eq!(
1158 PathWithPosition::parse_str("crate/utils/src/test:today.log:34"),
1159 PathWithPosition {
1160 path: PathBuf::from("crate/utils/src/test:today.log"),
1161 row: Some(34),
1162 column: None,
1163 }
1164 );
1165 assert_eq!(
1166 PathWithPosition::parse_str("/testing/out/src/file_finder.odin(7:15)"),
1167 PathWithPosition {
1168 path: PathBuf::from("/testing/out/src/file_finder.odin"),
1169 row: Some(7),
1170 column: Some(15),
1171 }
1172 );
1173 }
1174
1175 #[perf]
1176 #[cfg(target_os = "windows")]
1177 fn path_with_position_parse_windows_path() {
1178 assert_eq!(
1179 PathWithPosition::parse_str("crates\\utils\\paths.rs"),
1180 PathWithPosition {
1181 path: PathBuf::from("crates\\utils\\paths.rs"),
1182 row: None,
1183 column: None
1184 }
1185 );
1186
1187 assert_eq!(
1188 PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs"),
1189 PathWithPosition {
1190 path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
1191 row: None,
1192 column: None
1193 }
1194 );
1195 }
1196
1197 #[perf]
1198 #[cfg(target_os = "windows")]
1199 fn path_with_position_parse_windows_path_with_suffix() {
1200 assert_eq!(
1201 PathWithPosition::parse_str("crates\\utils\\paths.rs:101"),
1202 PathWithPosition {
1203 path: PathBuf::from("crates\\utils\\paths.rs"),
1204 row: Some(101),
1205 column: None
1206 }
1207 );
1208
1209 assert_eq!(
1210 PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1:20"),
1211 PathWithPosition {
1212 path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"),
1213 row: Some(1),
1214 column: Some(20)
1215 }
1216 );
1217
1218 assert_eq!(
1219 PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs(1902,13)"),
1220 PathWithPosition {
1221 path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
1222 row: Some(1902),
1223 column: Some(13)
1224 }
1225 );
1226
1227 // Trim off trailing `:`s for otherwise valid input.
1228 assert_eq!(
1229 PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1902:13:"),
1230 PathWithPosition {
1231 path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"),
1232 row: Some(1902),
1233 column: Some(13)
1234 }
1235 );
1236
1237 assert_eq!(
1238 PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1902:13:15:"),
1239 PathWithPosition {
1240 path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs:1902"),
1241 row: Some(13),
1242 column: Some(15)
1243 }
1244 );
1245
1246 assert_eq!(
1247 PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1902:::15:"),
1248 PathWithPosition {
1249 path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs:1902"),
1250 row: Some(15),
1251 column: None
1252 }
1253 );
1254
1255 assert_eq!(
1256 PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs(1902,13):"),
1257 PathWithPosition {
1258 path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"),
1259 row: Some(1902),
1260 column: Some(13),
1261 }
1262 );
1263
1264 assert_eq!(
1265 PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs(1902):"),
1266 PathWithPosition {
1267 path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"),
1268 row: Some(1902),
1269 column: None,
1270 }
1271 );
1272
1273 assert_eq!(
1274 PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs:1902:13:"),
1275 PathWithPosition {
1276 path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
1277 row: Some(1902),
1278 column: Some(13),
1279 }
1280 );
1281
1282 assert_eq!(
1283 PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs(1902,13):"),
1284 PathWithPosition {
1285 path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
1286 row: Some(1902),
1287 column: Some(13),
1288 }
1289 );
1290
1291 assert_eq!(
1292 PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs(1902):"),
1293 PathWithPosition {
1294 path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
1295 row: Some(1902),
1296 column: None,
1297 }
1298 );
1299
1300 assert_eq!(
1301 PathWithPosition::parse_str("crates/utils/paths.rs:101"),
1302 PathWithPosition {
1303 path: PathBuf::from("crates\\utils\\paths.rs"),
1304 row: Some(101),
1305 column: None,
1306 }
1307 );
1308 }
1309
1310 #[perf]
1311 fn test_path_compact() {
1312 let path: PathBuf = [
1313 home_dir().to_string_lossy().into_owned(),
1314 "some_file.txt".to_string(),
1315 ]
1316 .iter()
1317 .collect();
1318 if cfg!(any(target_os = "linux", target_os = "freebsd")) || cfg!(target_os = "macos") {
1319 assert_eq!(path.compact().to_str(), Some("~/some_file.txt"));
1320 } else {
1321 assert_eq!(path.compact().to_str(), path.to_str());
1322 }
1323 }
1324
1325 #[perf]
1326 fn test_extension_or_hidden_file_name() {
1327 // No dots in name
1328 let path = Path::new("/a/b/c/file_name.rs");
1329 assert_eq!(path.extension_or_hidden_file_name(), Some("rs"));
1330
1331 // Single dot in name
1332 let path = Path::new("/a/b/c/file.name.rs");
1333 assert_eq!(path.extension_or_hidden_file_name(), Some("rs"));
1334
1335 // Multiple dots in name
1336 let path = Path::new("/a/b/c/long.file.name.rs");
1337 assert_eq!(path.extension_or_hidden_file_name(), Some("rs"));
1338
1339 // Hidden file, no extension
1340 let path = Path::new("/a/b/c/.gitignore");
1341 assert_eq!(path.extension_or_hidden_file_name(), Some("gitignore"));
1342
1343 // Hidden file, with extension
1344 let path = Path::new("/a/b/c/.eslintrc.js");
1345 assert_eq!(path.extension_or_hidden_file_name(), Some("eslintrc.js"));
1346 }
1347
1348 #[perf]
1349 fn edge_of_glob() {
1350 let path = Path::new("/work/node_modules");
1351 let path_matcher =
1352 PathMatcher::new(&["**/node_modules/**".to_owned()], PathStyle::Posix).unwrap();
1353 assert!(
1354 path_matcher.is_match(path),
1355 "Path matcher should match {path:?}"
1356 );
1357 }
1358
1359 #[perf]
1360 fn project_search() {
1361 let path = Path::new("/Users/someonetoignore/work/zed/zed.dev/node_modules");
1362 let path_matcher =
1363 PathMatcher::new(&["**/node_modules/**".to_owned()], PathStyle::Posix).unwrap();
1364 assert!(
1365 path_matcher.is_match(path),
1366 "Path matcher should match {path:?}"
1367 );
1368 }
1369
1370 #[perf]
1371 #[cfg(target_os = "windows")]
1372 fn test_sanitized_path() {
1373 let path = Path::new("C:\\Users\\someone\\test_file.rs");
1374 let sanitized_path = SanitizedPath::new(path);
1375 assert_eq!(
1376 sanitized_path.to_string(),
1377 "C:\\Users\\someone\\test_file.rs"
1378 );
1379
1380 let path = Path::new("\\\\?\\C:\\Users\\someone\\test_file.rs");
1381 let sanitized_path = SanitizedPath::new(path);
1382 assert_eq!(
1383 sanitized_path.to_string(),
1384 "C:\\Users\\someone\\test_file.rs"
1385 );
1386 }
1387
1388 #[perf]
1389 fn test_compare_numeric_segments() {
1390 // Helper function to create peekable iterators and test
1391 fn compare(a: &str, b: &str) -> Ordering {
1392 let mut a_iter = a.chars().peekable();
1393 let mut b_iter = b.chars().peekable();
1394
1395 let result = compare_numeric_segments(&mut a_iter, &mut b_iter);
1396
1397 // Verify iterators advanced correctly
1398 assert!(
1399 !a_iter.next().is_some_and(|c| c.is_ascii_digit()),
1400 "Iterator a should have consumed all digits"
1401 );
1402 assert!(
1403 !b_iter.next().is_some_and(|c| c.is_ascii_digit()),
1404 "Iterator b should have consumed all digits"
1405 );
1406
1407 result
1408 }
1409
1410 // Basic numeric comparisons
1411 assert_eq!(compare("0", "0"), Ordering::Equal);
1412 assert_eq!(compare("1", "2"), Ordering::Less);
1413 assert_eq!(compare("9", "10"), Ordering::Less);
1414 assert_eq!(compare("10", "9"), Ordering::Greater);
1415 assert_eq!(compare("99", "100"), Ordering::Less);
1416
1417 // Leading zeros
1418 assert_eq!(compare("0", "00"), Ordering::Less);
1419 assert_eq!(compare("00", "0"), Ordering::Greater);
1420 assert_eq!(compare("01", "1"), Ordering::Greater);
1421 assert_eq!(compare("001", "1"), Ordering::Greater);
1422 assert_eq!(compare("001", "01"), Ordering::Greater);
1423
1424 // Same value different representation
1425 assert_eq!(compare("000100", "100"), Ordering::Greater);
1426 assert_eq!(compare("100", "0100"), Ordering::Less);
1427 assert_eq!(compare("0100", "00100"), Ordering::Less);
1428
1429 // Large numbers
1430 assert_eq!(compare("9999999999", "10000000000"), Ordering::Less);
1431 assert_eq!(
1432 compare(
1433 "340282366920938463463374607431768211455", // u128::MAX
1434 "340282366920938463463374607431768211456"
1435 ),
1436 Ordering::Less
1437 );
1438 assert_eq!(
1439 compare(
1440 "340282366920938463463374607431768211456", // > u128::MAX
1441 "340282366920938463463374607431768211455"
1442 ),
1443 Ordering::Greater
1444 );
1445
1446 // Iterator advancement verification
1447 let mut a_iter = "123abc".chars().peekable();
1448 let mut b_iter = "456def".chars().peekable();
1449
1450 compare_numeric_segments(&mut a_iter, &mut b_iter);
1451
1452 assert_eq!(a_iter.collect::<String>(), "abc");
1453 assert_eq!(b_iter.collect::<String>(), "def");
1454 }
1455
1456 #[perf]
1457 fn test_natural_sort() {
1458 // Basic alphanumeric
1459 assert_eq!(natural_sort("a", "b"), Ordering::Less);
1460 assert_eq!(natural_sort("b", "a"), Ordering::Greater);
1461 assert_eq!(natural_sort("a", "a"), Ordering::Equal);
1462
1463 // Case sensitivity
1464 assert_eq!(natural_sort("a", "A"), Ordering::Less);
1465 assert_eq!(natural_sort("A", "a"), Ordering::Greater);
1466 assert_eq!(natural_sort("aA", "aa"), Ordering::Greater);
1467 assert_eq!(natural_sort("aa", "aA"), Ordering::Less);
1468
1469 // Numbers
1470 assert_eq!(natural_sort("1", "2"), Ordering::Less);
1471 assert_eq!(natural_sort("2", "10"), Ordering::Less);
1472 assert_eq!(natural_sort("02", "10"), Ordering::Less);
1473 assert_eq!(natural_sort("02", "2"), Ordering::Greater);
1474
1475 // Mixed alphanumeric
1476 assert_eq!(natural_sort("a1", "a2"), Ordering::Less);
1477 assert_eq!(natural_sort("a2", "a10"), Ordering::Less);
1478 assert_eq!(natural_sort("a02", "a2"), Ordering::Greater);
1479 assert_eq!(natural_sort("a1b", "a1c"), Ordering::Less);
1480
1481 // Multiple numeric segments
1482 assert_eq!(natural_sort("1a2", "1a10"), Ordering::Less);
1483 assert_eq!(natural_sort("1a10", "1a2"), Ordering::Greater);
1484 assert_eq!(natural_sort("2a1", "10a1"), Ordering::Less);
1485
1486 // Special characters
1487 assert_eq!(natural_sort("a-1", "a-2"), Ordering::Less);
1488 assert_eq!(natural_sort("a_1", "a_2"), Ordering::Less);
1489 assert_eq!(natural_sort("a.1", "a.2"), Ordering::Less);
1490
1491 // Unicode
1492 assert_eq!(natural_sort("文1", "文2"), Ordering::Less);
1493 assert_eq!(natural_sort("文2", "文10"), Ordering::Less);
1494 assert_eq!(natural_sort("🔤1", "🔤2"), Ordering::Less);
1495
1496 // Empty and special cases
1497 assert_eq!(natural_sort("", ""), Ordering::Equal);
1498 assert_eq!(natural_sort("", "a"), Ordering::Less);
1499 assert_eq!(natural_sort("a", ""), Ordering::Greater);
1500 assert_eq!(natural_sort(" ", " "), Ordering::Less);
1501
1502 // Mixed everything
1503 assert_eq!(natural_sort("File-1.txt", "File-2.txt"), Ordering::Less);
1504 assert_eq!(natural_sort("File-02.txt", "File-2.txt"), Ordering::Greater);
1505 assert_eq!(natural_sort("File-2.txt", "File-10.txt"), Ordering::Less);
1506 assert_eq!(natural_sort("File_A1", "File_A2"), Ordering::Less);
1507 assert_eq!(natural_sort("File_a1", "File_A1"), Ordering::Less);
1508 }
1509
1510 #[perf]
1511 fn test_compare_paths() {
1512 // Helper function for cleaner tests
1513 fn compare(a: &str, is_a_file: bool, b: &str, is_b_file: bool) -> Ordering {
1514 compare_paths((Path::new(a), is_a_file), (Path::new(b), is_b_file))
1515 }
1516
1517 // Basic path comparison
1518 assert_eq!(compare("a", true, "b", true), Ordering::Less);
1519 assert_eq!(compare("b", true, "a", true), Ordering::Greater);
1520 assert_eq!(compare("a", true, "a", true), Ordering::Equal);
1521
1522 // Files vs Directories
1523 assert_eq!(compare("a", true, "a", false), Ordering::Greater);
1524 assert_eq!(compare("a", false, "a", true), Ordering::Less);
1525 assert_eq!(compare("b", false, "a", true), Ordering::Less);
1526
1527 // Extensions
1528 assert_eq!(compare("a.txt", true, "a.md", true), Ordering::Greater);
1529 assert_eq!(compare("a.md", true, "a.txt", true), Ordering::Less);
1530 assert_eq!(compare("a", true, "a.txt", true), Ordering::Less);
1531
1532 // Nested paths
1533 assert_eq!(compare("dir/a", true, "dir/b", true), Ordering::Less);
1534 assert_eq!(compare("dir1/a", true, "dir2/a", true), Ordering::Less);
1535 assert_eq!(compare("dir/sub/a", true, "dir/a", true), Ordering::Less);
1536
1537 // Case sensitivity in paths
1538 assert_eq!(
1539 compare("Dir/file", true, "dir/file", true),
1540 Ordering::Greater
1541 );
1542 assert_eq!(
1543 compare("dir/File", true, "dir/file", true),
1544 Ordering::Greater
1545 );
1546 assert_eq!(compare("dir/file", true, "Dir/File", true), Ordering::Less);
1547
1548 // Hidden files and special names
1549 assert_eq!(compare(".hidden", true, "visible", true), Ordering::Less);
1550 assert_eq!(compare("_special", true, "normal", true), Ordering::Less);
1551 assert_eq!(compare(".config", false, ".data", false), Ordering::Less);
1552
1553 // Mixed numeric paths
1554 assert_eq!(
1555 compare("dir1/file", true, "dir2/file", true),
1556 Ordering::Less
1557 );
1558 assert_eq!(
1559 compare("dir2/file", true, "dir10/file", true),
1560 Ordering::Less
1561 );
1562 assert_eq!(
1563 compare("dir02/file", true, "dir2/file", true),
1564 Ordering::Greater
1565 );
1566
1567 // Root paths
1568 assert_eq!(compare("/a", true, "/b", true), Ordering::Less);
1569 assert_eq!(compare("/", false, "/a", true), Ordering::Less);
1570
1571 // Complex real-world examples
1572 assert_eq!(
1573 compare("project/src/main.rs", true, "project/src/lib.rs", true),
1574 Ordering::Greater
1575 );
1576 assert_eq!(
1577 compare(
1578 "project/tests/test_1.rs",
1579 true,
1580 "project/tests/test_2.rs",
1581 true
1582 ),
1583 Ordering::Less
1584 );
1585 assert_eq!(
1586 compare(
1587 "project/v1.0.0/README.md",
1588 true,
1589 "project/v1.10.0/README.md",
1590 true
1591 ),
1592 Ordering::Less
1593 );
1594 }
1595
1596 #[perf]
1597 fn test_natural_sort_case_sensitivity() {
1598 std::thread::sleep(std::time::Duration::from_millis(100));
1599 // Same letter different case - lowercase should come first
1600 assert_eq!(natural_sort("a", "A"), Ordering::Less);
1601 assert_eq!(natural_sort("A", "a"), Ordering::Greater);
1602 assert_eq!(natural_sort("a", "a"), Ordering::Equal);
1603 assert_eq!(natural_sort("A", "A"), Ordering::Equal);
1604
1605 // Mixed case strings
1606 assert_eq!(natural_sort("aaa", "AAA"), Ordering::Less);
1607 assert_eq!(natural_sort("AAA", "aaa"), Ordering::Greater);
1608 assert_eq!(natural_sort("aAa", "AaA"), Ordering::Less);
1609
1610 // Different letters
1611 assert_eq!(natural_sort("a", "b"), Ordering::Less);
1612 assert_eq!(natural_sort("A", "b"), Ordering::Less);
1613 assert_eq!(natural_sort("a", "B"), Ordering::Less);
1614 }
1615
1616 #[perf]
1617 fn test_natural_sort_with_numbers() {
1618 // Basic number ordering
1619 assert_eq!(natural_sort("file1", "file2"), Ordering::Less);
1620 assert_eq!(natural_sort("file2", "file10"), Ordering::Less);
1621 assert_eq!(natural_sort("file10", "file2"), Ordering::Greater);
1622
1623 // Numbers in different positions
1624 assert_eq!(natural_sort("1file", "2file"), Ordering::Less);
1625 assert_eq!(natural_sort("file1text", "file2text"), Ordering::Less);
1626 assert_eq!(natural_sort("text1file", "text2file"), Ordering::Less);
1627
1628 // Multiple numbers in string
1629 assert_eq!(natural_sort("file1-2", "file1-10"), Ordering::Less);
1630 assert_eq!(natural_sort("2-1file", "10-1file"), Ordering::Less);
1631
1632 // Leading zeros
1633 assert_eq!(natural_sort("file002", "file2"), Ordering::Greater);
1634 assert_eq!(natural_sort("file002", "file10"), Ordering::Less);
1635
1636 // Very large numbers
1637 assert_eq!(
1638 natural_sort("file999999999999999999999", "file999999999999999999998"),
1639 Ordering::Greater
1640 );
1641
1642 // u128 edge cases
1643
1644 // Numbers near u128::MAX (340,282,366,920,938,463,463,374,607,431,768,211,455)
1645 assert_eq!(
1646 natural_sort(
1647 "file340282366920938463463374607431768211454",
1648 "file340282366920938463463374607431768211455"
1649 ),
1650 Ordering::Less
1651 );
1652
1653 // Equal length numbers that overflow u128
1654 assert_eq!(
1655 natural_sort(
1656 "file340282366920938463463374607431768211456",
1657 "file340282366920938463463374607431768211455"
1658 ),
1659 Ordering::Greater
1660 );
1661
1662 // Different length numbers that overflow u128
1663 assert_eq!(
1664 natural_sort(
1665 "file3402823669209384634633746074317682114560",
1666 "file340282366920938463463374607431768211455"
1667 ),
1668 Ordering::Greater
1669 );
1670
1671 // Leading zeros with numbers near u128::MAX
1672 assert_eq!(
1673 natural_sort(
1674 "file0340282366920938463463374607431768211455",
1675 "file340282366920938463463374607431768211455"
1676 ),
1677 Ordering::Greater
1678 );
1679
1680 // Very large numbers with different lengths (both overflow u128)
1681 assert_eq!(
1682 natural_sort(
1683 "file999999999999999999999999999999999999999999999999",
1684 "file9999999999999999999999999999999999999999999999999"
1685 ),
1686 Ordering::Less
1687 );
1688
1689 // Mixed case with numbers
1690 assert_eq!(natural_sort("File1", "file2"), Ordering::Greater);
1691 assert_eq!(natural_sort("file1", "File2"), Ordering::Less);
1692 }
1693
1694 #[perf]
1695 fn test_natural_sort_edge_cases() {
1696 // Empty strings
1697 assert_eq!(natural_sort("", ""), Ordering::Equal);
1698 assert_eq!(natural_sort("", "a"), Ordering::Less);
1699 assert_eq!(natural_sort("a", ""), Ordering::Greater);
1700
1701 // Special characters
1702 assert_eq!(natural_sort("file-1", "file_1"), Ordering::Less);
1703 assert_eq!(natural_sort("file.1", "file_1"), Ordering::Less);
1704 assert_eq!(natural_sort("file 1", "file_1"), Ordering::Less);
1705
1706 // Unicode characters
1707 // 9312 vs 9313
1708 assert_eq!(natural_sort("file①", "file②"), Ordering::Less);
1709 // 9321 vs 9313
1710 assert_eq!(natural_sort("file⑩", "file②"), Ordering::Greater);
1711 // 28450 vs 23383
1712 assert_eq!(natural_sort("file漢", "file字"), Ordering::Greater);
1713
1714 // Mixed alphanumeric with special chars
1715 assert_eq!(natural_sort("file-1a", "file-1b"), Ordering::Less);
1716 assert_eq!(natural_sort("file-1.2", "file-1.10"), Ordering::Less);
1717 assert_eq!(natural_sort("file-1.10", "file-1.2"), Ordering::Greater);
1718 }
1719}