#ord #partial-ord #wrapper #derive-debug #require #debugging

ordered

为添加任意部分/全序到类型的一种包装器

5个版本

0.2.2 2023年12月17日
0.2.1 2023年12月15日
0.2.0 2023年12月13日
0.1.1 2023年12月5日
0.1.0 2023年12月5日

#271 in 数据结构

Download history 974/week @ 2024-03-13 923/week @ 2024-03-20 806/week @ 2024-03-27 750/week @ 2024-04-03 728/week @ 2024-04-10 786/week @ 2024-04-17 643/week @ 2024-04-24 666/week @ 2024-05-01 450/week @ 2024-05-08 498/week @ 2024-05-15 581/week @ 2024-05-22 414/week @ 2024-05-29 384/week @ 2024-06-05 410/week @ 2024-06-12 802/week @ 2024-06-19 616/week @ 2024-06-26

2,286 个月下载量
用于 bitcoin

CC0 许可证

10KB
91

任意排序

为可以技术上实现 PartialOrd/Ord 的类型提供包装器,但出于语义原因,为该类型实现全序是没有意义的。

示例

您可能想将一个类型用作 BTreeMap 中的键,这需要 Ord,尽管为该类型实现全序可能没有意义。

use std::cmp::Ordering;
use std::collections::BTreeMap;
use ordered::{ArbitraryOrd, Ordered};

/// A Foo type.
///
/// We do not want users to be able to write `a < b` because it is meaningless
/// to compare the two but we wish to use `Foo`, for example, as a `BTreeMap` key.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum Foo {
    /// A space foo.
    Space(u32),
    /// A time foo.
    Time(u32)
}

impl ArbitraryOrd for Foo {
    fn arbitrary_cmp(&self, other: &Self) -> Ordering {
        use Foo::*;
        match (self, other) {
            (Space(_), Time(_)) => Ordering::Less,
            (Time(_), Space(_)) => Ordering::Greater,
            (Space(this), Space(that)) => this.cmp(that),
            (Time(this), Time(that)) => this.cmp(that),
        }
    }
}

let a = Foo::Space(50);
let b = Foo::Time(50);

let mut map = BTreeMap::new();

// error[E0277]: the trait bound `Foo: Ord` is not satisfied
// map.insert(a, "some interesting value");

map.insert(Ordered(a), "some interesting value");
map.insert(Ordered(b), "some other interesting value");

也许您想在一个包含不实现 Ord 的类型的复杂类型上派生 Ord

/// An example struct that contains a `Foo` but derives `PartialOrd` and `Ord`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct Adt {
    x: u32,
    p: Ordered<Foo>,
}

// Then there are various ways to get at the inner data.

let adt = Adt { x: 42, p: Foo::Space(50).into() };

println!("We can explicitly deref: {}", *adt.p);
println!("Or use deref coercion: {}", adt.p);
println!("Or we can use borrow: {}", &adt.p);

// And if all that is too complicated just use the inherent methods:

println!("Explicitly get a reference: {}", adt.p.as_inner());
println!("Or the inner type: {}", adt.p.into_inner());

最低支持的Rust版本 (MSRV)

该包的MSRV是Rust v1.56.1

许可

本项目的代码根据 Creative Commons CC0 1.0 Universal license 许可。我们使用 SPDX 许可列表SPDX IDs

无运行时依赖