From 86fdd16342863c7073ff2c656ac109746e782165 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustav=20S=C3=B6rn=C3=A4s?= Date: Sat, 31 Jul 2021 21:11:54 +0200 Subject: wip bad diagnostic --- cli/src/main.rs | 31 +++++++++++++------------------ 1 file changed, 13 insertions(+), 18 deletions(-) (limited to 'cli/src') diff --git a/cli/src/main.rs b/cli/src/main.rs index 22f0da2..7d25b50 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -146,14 +146,7 @@ fn main() { SortTarget::Date => transactions.sort_by_key(|t| t.date), } for i in 1..sort.len() { - //TODO macro? dynamic dispatch? trait objects? - match (&sort[i-1], &sort[i]) { - (SortTarget::Amount, SortTarget::Date) - => inner_sort_by_key(&mut transactions, |t| t.amount, |t| t.date), - (SortTarget::Date, SortTarget::Amount) - => inner_sort_by_key(&mut transactions, |t| t.date, |t| t.amount), - _ => panic!(), - } + inner_sort_by(&mut transactions, sort_by_func(&sort[i-1]), sort_by_func(&sort[i])); } } println!("{}", Table::new(transactions).with(Style::psql())); @@ -161,11 +154,16 @@ fn main() { } } -fn inner_sort_by_key(v: &mut [T], mut outer_key: F, mut inner_key: G) -where F: FnMut(&T) -> K, - G: FnMut(&T) -> L, - K: Ord, - L: Ord, +fn sort_by_func(sort: &SortTarget) -> impl FnMut(&Transaction, &Transaction) -> std::cmp::Ordering { + match sort { + SortTarget::Amount => |t1: &Transaction, t2: &Transaction| t1.amount.cmp(&t2.amount), + SortTarget::Date => |t1: &Transaction, t2: &Transaction| t1.date.cmp(&t2.date), + } +} + +fn inner_sort_by(v: &mut [T], mut outer_cmp: F, mut inner_cmp: F) +where + F: FnMut(&T, &T) -> std::cmp::Ordering, { // Early out if v.len() < 2 { @@ -173,16 +171,13 @@ where F: FnMut(&T) -> K, } let mut lower = 0; // Lower bound of current equal range - let mut last_k = outer_key(&v[0]); // Current key for i in 0..v.len() { - let i_k = outer_key(&v[i]); - if i_k != last_k { + if outer_cmp(&v[i], &v[lower]) != std::cmp::Ordering::Equal { let upper = i; if upper - lower > 1 { - v[lower..upper].sort_by_key(&mut inner_key); + v[lower..upper].sort_by(&mut inner_cmp); } lower = i; - last_k = i_k; } } } -- cgit v1.2.1