[][src]Macro colmac::sorted

macro_rules! sorted {
    ( $collection:expr ) => { ... };
    ( $collection:expr, $compare_fn:expr ) => { ... };
}

Creates a sorted Vec with cloned elements of the input collection, leaving the original collection untouched.

The input collection should support .iter() method that returns an Iterator over its elemnts.

There are two ways to invoke this macro:

  1. with one argument, a mutable collection
    1. uses slice::sort_unstable to sort
  2. with two arguments, a mutable collection followed by a closure
    1. passes the closure to slice::sort_unstable_by to sort

Examples

#[macro_use] extern crate colmac;
use std::cmp::Ordering::{Equal, Greater, Less};

// sort without a custom closure
let v1 = vec![2, 4, -1];
let v1_sorted = sorted!(v1);
assert_eq!(vec![2, 4, -1], v1);  // v1 is not modified
assert_eq!(vec![-1, 2, 4], v1_sorted);

// sort with; sort in reverse order
let v2 = vec![2, 4, -1];
let v2_sorted = sorted!(v2, |a, b| match a.cmp(b) {
    Less => Greater,
    Greater => Less,
    Equal => Equal,
});
assert_eq!(vec![2, 4, -1], v2);  // v2 is not modified
assert_eq!(vec![4, 2, -1], v2_sorted);