#derive #cmp #order #comparing #macro-derive #no-std

无std cmpbyderive

导出宏CmpBy和HashBy,分别派生特质OrdPartialOrdEqPartialEq,以及Hash,用于无法自动从这些特质派生的结构和枚举

1个不稳定版本

0.1.0 2023年8月8日

15排序 中排名

Download history 55/week @ 2024-04-14 44/week @ 2024-04-21 9/week @ 2024-04-28 17/week @ 2024-05-05 10/week @ 2024-05-12 11/week @ 2024-05-19 7/week @ 2024-05-26 15/week @ 2024-06-02 8/week @ 2024-06-09 34/week @ 2024-06-16 17/week @ 2024-06-23 2/week @ 2024-06-30 9/week @ 2024-07-07 43/week @ 2024-07-14 5/week @ 2024-07-21 31/week @ 2024-07-28

每月下载量达 88
5 个crate中使用 (通过 pest_typed)

MIT/Apache

43KB
841

GitHub Crates.io docs.rs Continuous integration

cmp_by_derive

此crate提供CmpByHashBy导出宏。

  • CmpBy为无法自动从这些特质派生的类型派生特质OrdPartialOrdEqPartialEq,通过选择用于比较的字段。
  • CmpByHashBy也可以通过调用任意方法来实现它们的特质

用法

用于排序的字段使用属性#[cmp_by]标记。其他字段将被忽略。

这可以节省大量的样板代码,如SomethingElse结构体所示。

use std::cmp::Ordering;
use cmp_by_derive::CmpBy;

#[derive(CmpBy)]
struct Something {
    #[cmp_by]
    a: u16,
    #[cmp_by]
    b: u16,
    c: f32,
}

struct SomethingElse {
    a: u16,
    b: u16,
    c: f32,
}

impl Eq for SomethingElse {}

impl PartialEq<Self> for SomethingElse {
    fn eq(&self, other: &Self) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}

impl PartialOrd<Self> for SomethingElse {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for SomethingElse {
    fn cmp(&self, other: &Self) -> Ordering {
        self.a.cmp(&other.a).then_with(|| { self.b.cmp(&other.b) })
    }
}



assert_eq!(Something { a: 2, b: 0, c: 0.2 }.cmp(&Something { a: 1, b: 1, c: 1.3 }),
           SomethingElse { a: 2, b: 0, c: 0.2 }.cmp(&SomethingElse { a: 1, b: 1, c: 1.3 }));
assert_eq!(Something { a: 1, b: 0, c: 3.3 }.cmp(&Something { a: 1, b: 1, c: 2.3 }),
           SomethingElse { a: 1, b: 0, c: 3.3 }.cmp(&SomethingElse { a: 1, b: 1, c: 2.3 }));

您可以使用HashBy与使用CmpBy相同的方式

use cmp_by_derive::HashBy;
use cmp_by_derive::CmpBy;
use std::collections::hash_set::HashSet;

#[derive(HashBy, CmpBy)]
struct Something {
    #[cmp_by]
    #[hash_by]
    a: u16,
    #[cmp_by]
    #[hash_by]
    b: u16,
    c: f32,
}

let mut set = HashSet::new();
let something = Something { a: 2, b: 0, c: 0.2 };
assert!(set.insert(something));

依赖关系

~255–710KB
~17K SLoC