Improve table sort

- If the sort is already done, noop
- If the sort is on the same category but with a different direction, just reverse the order
  - I believe this is something that happens a lot
- If not, use `contiguous_slice` to avoid reallocating new entities
This commit is contained in:
Johann Tuffe 2025-04-08 11:37:24 +08:00
parent 0ddde755ee
commit fd18fd304d

View file

@ -347,19 +347,20 @@ where
/// Sorts items in the model, this should be called before it is drawn after all items have been added for the view /// Sorts items in the model, this should be called before it is drawn after all items have been added for the view
pub fn sort(&mut self, category: Category, ascending: bool) { pub fn sort(&mut self, category: Category, ascending: bool) {
self.sort = Some((category, ascending)); match self.sort {
let mut order: Vec<Entity> = self.order.iter().cloned().collect(); Some((cat, asc)) if cat == category && asc == ascending => return,
order.sort_by(|entity_a, entity_b| { Some((cat, asc)) if cat == category => self.order.make_contiguous().reverse(),
if ascending { _ => {
self.item(*entity_a) let items = &self.items;
.unwrap() self.order.make_contiguous().sort_by(|entity_a, entity_b| {
.compare(self.item(*entity_b).unwrap(), category) let cmp = items
} else { .get(*entity_a)
self.item(*entity_b) .unwrap()
.unwrap() .compare(items.get(*entity_b).unwrap(), category);
.compare(self.item(*entity_a).unwrap(), category) if ascending { cmp } else { cmp.reverse() }
});
} }
}); }
self.order = order.into(); self.sort = Some((category, ascending));
} }
} }