-
-
Save bdarcus/2c5a5e1cf232c9328613d304d4fb0ecb to your computer and use it in GitHub Desktop.
multi level sort in rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Multi-level sort a slice of Foobars according to [(field, reverse)] | |
fn sort_by_names(f: &mut [Foobar], orderings: &[(Foofields, bool)]) { | |
use std::cmp::Ordering; | |
f.sort_by(|a, b| { | |
let mut cmp = Ordering::Equal; | |
for (field, reverse) in orderings { | |
if cmp != Ordering::Equal { | |
break; | |
} | |
cmp = match *field { | |
Foofields::Foo => a.foo.cmp(&b.foo), | |
Foofields::Bar => a.bar.cmp(&b.bar), | |
Foofields::Oof => a.oof.cmp(&b.oof), | |
}; | |
cmp = if *reverse { cmp.reverse() } else { cmp }; | |
} | |
cmp | |
}) | |
} | |
/// An arbitrary struct | |
#[derive(Debug)] | |
struct Foobar { | |
foo: i32, | |
bar: i32, | |
oof: &'static str, | |
} | |
/// Typesafe enumeration of fields on `Foobar` | |
enum Foofields { | |
Foo, | |
Bar, | |
Oof, | |
} | |
fn main() { | |
let mut f = vec![ | |
Foobar { | |
foo: 3, | |
bar: 1, | |
oof: "B", | |
}, | |
Foobar { | |
foo: 1, | |
bar: 2, | |
oof: "B", | |
}, | |
Foobar { | |
foo: 2, | |
bar: 2, | |
oof: "A", | |
}, | |
]; | |
// Apply sorts in reverse order. | |
sort_by_names(&mut f, &[( Foofields::Bar, false), (Foofields::Oof, false)]); | |
println!("{:?}", &f); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment