file_model: Use binary search to find index

Binary search is a fast method to sort for an item within
a sorted list. We have a sorted list, so we can take advantage
of binary search instead of having a linear traversal through
the list.

Because binary search requires a sorted list, we need to use
the same logic for sorting and searching. Here we factor out
the filename comparison logic into `util::compare_by_name()`.
In the future we may want to have a module for sorting algorithm
logic and checking what sorting algortihm Nautilus uses.
This commit is contained in:
Christopher Davis 2022-07-14 15:25:03 -04:00
parent d609c4e0b2
commit 5f7aa595db
2 changed files with 18 additions and 13 deletions

View file

@ -101,13 +101,7 @@ impl LpFileModel {
});
// Then sort by name.
vec.sort_by(|file_a, file_b| {
let name_a = util::get_file_display_name(file_a).unwrap_or_default();
let name_b = util::get_file_display_name(file_b).unwrap_or_default();
util::utf8_collate_key_for_filename(&name_a)
.cmp(&util::utf8_collate_key_for_filename(&name_b))
});
vec.sort_by(util::compare_by_name);
model.imp().directory.set(directory.clone()).unwrap();
}
@ -127,6 +121,8 @@ impl LpFileModel {
pub fn index_of(&self, file: &gio::File) -> Option<u32> {
let imp = self.imp();
let vec = imp.inner.borrow();
vec.iter().position(|f| f.equal(file)).map(|p| p as u32)
vec.binary_search_by(|a| util::compare_by_name(a, file))
.ok()
.map(|i| i as u32)
}
}