#ord #expression #traits #key #logic #inline #reverse

macro ord_by_key

Provides a convenient macro for implementing Ord trait with logic specified in an inline expression

2 releases

0.1.3 Nov 17, 2020
0.1.2 Nov 17, 2020
0.1.1 Nov 16, 2020
0.1.0 Nov 16, 2020

#1450 in Procedural macros

24 downloads per month

MIT/Apache

18KB
133 lines

ord_by_key

Provides a convenient macro for implementing Ord trait with logic specified in an inline expression

use core::cmp::Reverse;
// `Person` will be ordered by `last_name`, then by 
// `first_name`, then by `age` in reverse
#[ord_eq_by_key_selector(|p|
    &p.last_name,
    &p.first_name,
    Reverse(p.age),)]
pub struct Person {
    pub first_name: String,
    pub last_name: String,
    pub age: usize,
}
// Container for `&str` which will be ordered by underlying
// string length
#[ord_eq_by_key_selector(|(s)| s.len())]
pub struct StrByLen<'a>(&'a str);

assert!(StrByLen("Alex") > StrByLen("Bob"));

no_std support

ord_by_key should be compatible with no_std, but it was not tested.

License

Distributed under the terms of both the MIT license and the Apache License (Version 2.0)


lib.rs:

Provides a convenient macro for implementing Ord trait with logic specified in an inline expression

use ord_by_key::ord_eq_by_key_selector;
use core::cmp::Reverse;
// `Person` will be ordered by `last_name`, then by `first_name`, then by `age` in reverse
#[ord_eq_by_key_selector(|p|
    &p.last_name,
    &p.first_name,
    Reverse(p.age),)]
pub struct Person {
    pub first_name: String,
    pub last_name: String,
    pub age: usize,
}
use ord_by_key::ord_eq_by_key_selector;
// Container for [`&str`] which will be ordered by underlying string length
#[ord_eq_by_key_selector(|(s)| s.len())]
pub struct StrByLen<'a> (&'a str);

// Note, comparison happens just based on string length
assert!(StrByLen("Alex") > StrByLen("Bob"));
assert!(StrByLen("Alex") == StrByLen("John"));
assert!(StrByLen("Alex") < StrByLen("Michael"));

Dependencies

~1.5MB
~35K SLoC