diff options
author | Ben Bridle <bridle.benjamin@gmail.com> | 2024-05-30 19:24:00 +1200 |
---|---|---|
committer | Ben Bridle <bridle.benjamin@gmail.com> | 2024-05-30 19:24:00 +1200 |
commit | 241175559706f4b6a9807013f8075a5238643251 (patch) | |
tree | 99decc9d23493247c91e3ab010c67b4ce1a32cff | |
parent | 955b20a073eb566467158cf5089c923ca45e6748 (diff) | |
download | bedrock-pc-241175559706f4b6a9807013f8075a5238643251.zip |
Sort directory children in case-agnostic alphabetic order
-rw-r--r-- | src/devices/file/directory_entry.rs | 47 |
1 files changed, 37 insertions, 10 deletions
diff --git a/src/devices/file/directory_entry.rs b/src/devices/file/directory_entry.rs index c4ce146..7f0e69b 100644 --- a/src/devices/file/directory_entry.rs +++ b/src/devices/file/directory_entry.rs @@ -10,21 +10,48 @@ pub struct DirectoryChild { impl PartialOrd for DirectoryChild { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { - let entry_type_ord = self.entry_type.cmp(&other.entry_type); - let final_order = match entry_type_ord { - Ordering::Equal => self.byte_path.cmp(&other.byte_path), - _ => entry_type_ord, - }; - Some(final_order) + Some(self.cmp(other)) } } impl Ord for DirectoryChild { fn cmp(&self, other: &Self) -> Ordering { - let entry_type_ord = self.entry_type.cmp(&other.entry_type); - match entry_type_ord { - Ordering::Equal => self.byte_path.cmp(&other.byte_path), - _ => entry_type_ord, + match self.entry_type.cmp(&other.entry_type) { + Ordering::Equal => + compare_ascii_arrays(&self.byte_path,&other.byte_path), + other => other, } } } + +// Compare two ASCII arrays in case-agnostic alphabetic order. +fn compare_ascii_arrays(left: &[u8], right: &[u8]) -> Ordering { + let l = std::cmp::min(left.len(), right.len()); + let lhs = &left[..l]; + let rhs = &right[..l]; + + for i in 0..l { + let a = remap_ascii(lhs[i]); + let b = remap_ascii(rhs[i]); + match a.cmp(&b) { + Ordering::Equal => (), + non_eq => return non_eq, + } + } + + left.len().cmp(&right.len()) +} + +// Remap ASCII values so that they sort in case-agnostic alphabetic order: +// !"#$%&'()*+,-./0123456789:;<=>? +// @`AaBbCcDdEeFfGgHhIiJjKkLlMmNnOo +// PpQqRrSsTtUuVvWwXxYyZz[{\|]}^~_ +fn remap_ascii(c: u8) -> u8 { + if 0x40 <= c && c <= 0x5F { + (c - 0x40) * 2 + 0x40 + } else if 0x60 <= c && c <= 0x7F { + (c - 0x60) * 2 + 0x41 + } else { + c + } +} |