sort-by-borrowed-key

Crates.iosort-by-borrowed-key
lib.rssort-by-borrowed-key
version1.0.0
sourcesrc
created_at2020-05-26 19:02:32.397347
updated_at2020-05-26 19:02:32.397347
descriptionAdds two convenience methods for sorting by a borrowed key
homepage
repositoryhttps://bitbucket.org/Groomblecom/sort-by-borrowed-key.git
max_upload_size
id246319
size6,152
(groomble)

documentation

README

A crate to add two more sorting methods

Say you have a vector of tuples, which you would like to sort by one of the elements (maybe you got it by using the enumerate or zip iterator methods, then collected into a Vec). Now, if you write the following, you will get lifetime errors:

let mut letters = vec![
    (1, "C".to_string()), 
    (2, "B".to_string()),
    (3, "B".to_string()),
    (4, "A".to_string())
];
letters.sort_by_key(|x| &x.1);
println!("Letters: {:?}", letters);

So you might try not borrowing, but then you realize String isn't Copy:

let mut letters = vec![
    (1, "C".to_string()), 
    (2, "B".to_string()),
    (3, "B".to_string()),
    (4, "A".to_string())
];
letters.sort_by_key(|x| x.1);
println!("Letters: {:?}", letters);

So this fails because you'd be moving out of the array! You don't want to have to expensively clone all of these strings just to compare them. That's where this library comes in:

use sort_by_borrowed_key::SortByBorrowedKey;
let mut letters = vec![
    (1, "C".to_string()), 
    (2, "B".to_string()),
    (3, "B".to_string()),
    (4, "A".to_string())
];
letters.sort_by_borrowed_key(|x| &x.1);
let expected = vec![
    (4, "A".to_string()), 
    (2, "B".to_string()),
    (3, "B".to_string()),
    (1, "C".to_string())
];
assert_eq!(letters, expected);

That's it! The only other thing this crate adds is a unstable-sort version of the same method, sort_unstable_by_borrowed_key, which is faster but may change of the order of equal elements (see the docs for [T]::sort_unstable).

Many thanks to danieldg in ##rust on freenode IRC for help understanding how to write this, including fantastic examples!

Commit count: 0

cargo fmt