#2.5. 比较 trait
本页内容
- 2.5.1. 4 个 trait 的层次:为什么需要 partial
- 2.5.2. PartialEq:部分相等(==、!=)
- 默认的 ne
- 示例
- 2.5.3. Eq:完全相等
- 2.5.4. PartialOrd:偏序(<、>、<=、>=)
- Ordering 类型
- 比较链
- 2.5.5. Ord:全序
- min / max / clamp
- 2.5.6. Hash:哈希(与 Eq 一致的承诺)
- 实现写入的内容
- 获取哈希值
- 用户定义
- 冲突
- 稳定性
- 2.5.7. 实现矩阵
- 2.5.8. 广播比较 trait
- 2.5.9. #[derive(Eq, Ord, Hash, ...)]
- 2.5.10. 模式匹配与 cmp
- 2.5.11. core::hash:哈希器
本章介绍定义值之间比较的 trait 族。不仅 ==、!=、<、>、<=、>= 运算符,哈希、排序和模式匹配也都通过本章的 trait 分派。
这些 trait 分布在两个模块中。PartialEq 和 PartialOrd 承载比较运算符,因此与其他运算符 trait 一起定义在 core::ops 中(2.3)。Eq、Ord、Hash 和 Ordering 定义在 core::cmp 中。PartialEq、PartialOrd、Eq、Ord、Hash 和 Ordering 都在 prelude 中(0.2.3),所以用户代码无需 use 即可使用它们。Hash 实现写入的哈希器位于 core::hash(2.5.11)。
Nabi 把比较拆成一个由 4 个 trait 组成的层次(PartialEq / Eq / PartialOrd / Ord),外加一个独立的 Hash trait。这种拆分同时满足两项实际需求:IEEE 754 浮点数的 NaN 处理,以及有保证的哈希一致性。
#2.5.1. 4 个 trait 的层次:为什么需要 partial
这个层次可以同时从两个角度描述。
集合视角:A ⊃ B 表示“满足 A 的类型集合包含满足 B 的类型集合”。A 更一般,B 更具体。
PartialEq ⊃ Eq // set of PartialEq types ⊇ set of Eq types
PartialOrd ⊃ Ord // (every Eq is PartialEq, but not vice versa)
PartialEq ⊃ PartialOrd
蕴含视角(supertrait):B ⇒ A 表示“实现 B 就自动要求实现 A”;在 Nabi 代码中写作 trait B: A。此时 A 是 B 的超 trait。
trait Eq: PartialEq { ... } // PartialEq is a supertrait of Eq
trait PartialOrd: PartialEq { ... } // PartialEq is a supertrait of PartialOrd
trait Ord: PartialOrd + Eq { ... } // PartialOrd and Eq are supertraits of Ord
两种视角从不同角度表达的是完全相同的事实。如果 B ⇒ A,那么每个是 B 的类型也是 A,于是得出 A ⊃ B。在集合视角中,超 trait 是“较大的一方”。
Hash trait 位于与上述层次分开的另一条线上。
Eq ⊃ Hash // only some Eq types are Hash; Hash promises consistency with Eq
之所以单独拆出 partial,是因为 IEEE 754 浮点数中的 NaN。
let a: f64 = 0.0 / 0.0; // NaN
let b: f64 = 0.0 / 0.0; // NaN
a == b; //→ false (NaN != NaN by IEEE 754)
a < b; //→ false
a > b; //→ false
a <= b; //→ false
NaN 甚至不等于它自身。这违反了自反性:a == a 不再有保证。因此 trait 实现按类型分开:f32 和 f64 只实现 PartialEq、PartialOrd,而 i32、bool、str 等类型一直实现到 Eq、Ord,满足全序。
这种拆分使 Hash、Dict / Set 和排序算法中 Hash 的一致性承诺与全序保证都不受破坏。
#2.5.2. PartialEq:部分相等(==、!=)
部分相等的定义如下。
#[lang("eq_trait")]
trait PartialEq<Rhs = Self> {
#[infix("==")]
fn eq(self, rhs: Rhs) -> bool;
#[infix("!=")]
fn ne(self, rhs: Rhs) -> bool {
!self.eq(rhs) // default impl
}
}
Unicode 词法单元 ≡ 和 ≠ 没有自己的中缀绑定。词法分析器把它们读作 == 和 !=(refs-lang 1.10.3),因此它们分派到 eq 和 ne。
PartialEq 的承诺是对称性(a == b 与 b == a 等价)和传递性(如果 a == b 且 b == c 成立,那么 a == c 成立)。由于 IEEE 754 的 NaN,自反性(a == a)没有保证。
#默认的 ne
ne 默认实现为 !self.eq(rhs)。用户可以单独实现它,例如出于性能考虑。
#示例
let r1 = 5i32 == 5i32; //→ true
let r2 = "hi" != "hello"; //→ true
let nan: f64 = f64::NAN;
let r3 = nan == nan; //→ false (PartialEq is partial)
#2.5.3. Eq:完全相等
完全相等定义为一个标记 trait。
trait Eq: PartialEq<Self> {
// marker trait: no additional methods
}
Eq 是一个标记 trait:它不添加任何方法,只添加自反性承诺。
Eq 添加的承诺是自反性:a == a 总为真。Dict / Set 的键和排序算法只有在这一承诺下才能正确工作。
实现策略如下。所有整数、布尔、字符和字符串类型(i32、i64、u8..u64、bool、char、c_char、str 等)都实现 Eq。浮点类型以及包含它们的和类型(f32、f64、f64 | none 等)不实现 Eq。只有当每个字段都是 Eq 时,才可以在用户的结构体或枚举上使用 #[derive(Eq)]。
let n: i32 = 42;
n == n; //→ true (guaranteed by Eq)
#2.5.4. PartialOrd:偏序(<、>、<=、>=)
偏序 trait 定义比较运算符。
#[lang("cmp_trait")]
trait PartialOrd<Rhs = Self>: PartialEq<Rhs> {
#[infix("<")]
fn lt(self, rhs: Rhs) -> bool;
#[infix(">")]
fn gt(self, rhs: Rhs) -> bool;
#[infix("<=")]
fn le(self, rhs: Rhs) -> bool;
#[infix(">=")]
fn ge(self, rhs: Rhs) -> bool;
fn partial_cmp(self, rhs: Rhs) -> Ordering | none {
// default impl: combination of lt/gt/le
if self.lt(rhs) { return Ordering::Less; }
if self.gt(rhs) { return Ordering::Greater; }
if self.le(rhs) { return Ordering::Equal; }
none // NaN vs NaN etc.: incomparable
}
}
与 ≡ 和 ≠ 一样,词法分析器把 ≤ 和 ≥ 读作 <= 和 >=。
这个 trait 的承诺:反对称性(如果 a < b,那么 !(b < a))和传递性(对于有定义的比较,如果 a < b 且 b < c,那么 a < c)。三歧性只部分成立:两个值之间的顺序并不总有定义,存在像 NaN 这样不可比较的值。
partial_cmp 是一个提供的方法(带默认实现),返回 Ordering | none。当值不可比较(NaN 等)时,结果为 none。
#Ordering 类型
三路比较的结果用下面的枚举表示。
enum Ordering {
Less,
Equal,
Greater,
}
Ord::cmp 直接返回 Ordering。Ordering 实现了 Clone、Copy、PartialEq、Eq、PartialOrd、Ord、Hash 和 Debug(Less / Equal / Greater;Less < Equal < Greater),并有下面这些固有方法。
impl Ordering {
const fn is_lt(self) -> bool; // self is Less
const fn is_eq(self) -> bool; // self is Equal
const fn is_gt(self) -> bool; // self is Greater
const fn reverse(self) -> Ordering; // swaps Less and Greater; Equal stays
const fn then(self, other: Ordering) -> Ordering; // self, or other when self is Equal
fn then_with(self, f: fn() -> Ordering) -> Ordering; // self, or f() when self is Equal
}
let o = 3.cmp(7); //→ Less
o.is_lt(); //→ true
o.reverse(); //→ Greater
xs.sort_by(|a: (i64, i64), b: (i64, i64)| a.0.cmp(b.0).then(a.1.cmp(b.1))); // ties by .1
#比较链
按照 refs-lang 3.2.5 的定义,同一方向的比较可以连写,每个操作数只求值一次:
lo <= x < hi; // lo <= x && x < hi
a < b > c; // compile error: two directions; write a < b && b > c
#2.5.5. Ord:全序
全序 trait 的定义如下。
#[lang("ord_trait")]
trait Ord: Eq + PartialOrd<Self> {
fn cmp(self, rhs: Self) -> Ordering;
// default: two values with Ord are always comparable
fn min(self, rhs: Self) -> Self {
if self.le(rhs) { self } else { rhs }
}
fn max(self, rhs: Self) -> Self {
if rhs.ge(self) { rhs } else { self } // rhs on a tie: the last of equals
}
#[track_caller]
fn clamp(self, low: Self, high: Self) -> Self {
if low.gt(high) { panic("Ord::clamp: low > high; pass the bounds in order, `x.clamp(low, high)`") }
if self.lt(low) { low }
else if self.gt(high) { high }
else { self }
}
}
Ord 添加的承诺是完全性:任意两个值之间的顺序都有定义,是 Less、Equal、Greater 之一。因此 partial_cmp 从不返回 none,总是返回一个 Ordering 值。
排序算法只有在这一保证下才能正确工作。
实现策略:i32、i64、u*、bool、char、c_char、str 实现 Ord。f32 和 f64 不实现,因为 NaN 使某些值不可比较。
#min / max / clamp
提供了三个默认方法,实现无需自己实现它们即可使用。相等时 min 返回 self,max 返回 rhs,所以在相等的值中 min 保留第一个,max 保留最后一个,与 Iterator::min / max 相同(2.7)。与 f64::clamp 一样,clamp 在 low > high 时触发 panic。
let r = 3i32.min(7i32); //→ 3
let m = 5.max(10); //→ 10
let c = 100.clamp(0, 50); //→ 50
let o = 1.0f64.cmp(2.0); // ERROR: Ord is not defined for f64
let k = 1.0f64.clamp(0.0, 10.0); //→ 1.0: the inherent f64::clamp (2.1.4), not Ord's
#2.5.6. Hash:哈希(与 Eq 一致的承诺)
一个 Hash 值把自身交给 Hasher(2.5.11),由它把收到的内容变成一个 u64。
#[lang("hash_trait")]
trait Hash: Eq {
fn hash<H: Hasher>(self, ref h: H);
}
核心承诺是:
a == b⇒a和b产生相同的写入序列,因此任何哈希器都给出相同的哈希值
这一承诺是 Dict<K, V, S> 和 Set<T, S> 中所有算法正确性的基础。
由于 Hash: Eq,不实现 Eq 的类型也不能实现 Hash。f64 不实现 Eq,因此不能实现 Hash。
#实现写入的内容
实现按固定顺序写入它的各个部分,每部分用它自己的 hash 或 Hasher 的某个 write_<int>。一段变长的值序列(列表的各项)以 h.write_length_prefix(len) 开头。没有它,相邻的序列可能互相错位:[[1, 2], [3]] 和 [[1], [2, 3]] 会产生相同的写入。write_str 本身是无前缀冲突的(prefix-free),前面从不加 write_length_prefix。
标准实现写入的内容如下:
| 类型 | 写入 |
|---|---|
i*、u* | write_<type>(self);usize / isize 在所有目标上都按 8 字节写入 |
bool | write_u8(0 / 1) |
char / c_char | write_u32 / write_u8 |
str | write_str(self) |
List<T> | write_length_prefix(len),然后是每一项 |
[T; N] | 每一项(N 是类型的一部分) |
| 元组 | 按顺序写入每个分量 |
和类型 A | B | write_usize(成员索引),然后是该成员的 hash |
NonZero / Positive | 内部值 |
NonNan / Finite | 以 write_u64 写入位模式,-0.0 按 0.0 写入 |
Int | 符号、write_length_prefix(limbs),然后是各个 32 位 limb;同一个值的所有形式写入都相同 |
Dict<K, V, S> / Set<T, S> | 每个条目用一个 RandomState::new() 的哈希器单独哈希,结果相加(回绕);然后是 write_length_prefix(len) 和 write_u64(sum) |
Dict 和 Set 的哈希与顺序无关,与它们的比较方式一致。无论 S 是什么,每个条目都使用进程密钥,所以两个相等的字典即使 S 不同,哈希值也相同。
#获取哈希值
没有一步到位的写法:构建哈希器,写入,结束。
use core::hash::{BuildHasher, RandomState};
let h = RandomState::new().build_hasher();
"hello".hash(ref h);
let a = h.finish(); // the same for "hello" all through this run
#用户定义
#[derive(PartialEq, Eq, Hash)]
struct UserId { id: u64; }
// automatic derive: possible because every field (id: u64) is Eq+Hash
手写的实现只写入相等比较所看的内容:
use core::hash::Hasher;
struct Tag { name: str; }
impl PartialEq for Tag {
fn eq(self, rhs: Tag) -> bool { self.name.to_lowercase() == rhs.name.to_lowercase() }
fn ne(self, rhs: Tag) -> bool { !self.eq(rhs) }
}
impl Eq for Tag {}
impl Hash for Tag {
fn hash<H: Hasher>(self, ref h: H) {
h.write_str(self.name.to_lowercase()); // equal tags write the same
}
}
#冲突
同一类型的两个不同值可能哈希相同,即使 a != b。这不是 bug:在 64 位哈希空间中冲突不可避免。Dict 等数据结构会处理冲突。
#稳定性
核心承诺是唯一的承诺。哈希值在同一程序的不同运行之间、不同机器之间以及不同 Nabi 版本之间都可能不同,实现产生的写入也可能不同。程序不得存储哈希值或把它发送给另一个进程;需要保持不变的哈希值应来自直接喂入字节和整数的 SipHasher13 / SipHasher24(2.5.11),绝不来自 x.hash(ref h)。Dict 和 Set 默认使用 RandomState 哈希,其密钥在每个进程中随机抽取一次,所以键在表中的位置每次运行都不同;而它们迭代和打印的内容不变,因为那是插入顺序(2.9.3)。
#2.5.7. 实现矩阵
各类型的 trait 实现汇总如下。
| 类型 | PartialEq | Eq | PartialOrd | Ord | Hash | 行为 |
|---|---|---|---|---|---|---|
i*, u* | ✓ | ✓ | ✓ | ✓ | ✓ | nabi.eq.OP、nabi.lt.OP、... |
f32, f64 | ✓ | ✗ | ✓ | ✗ | ✗ | nabi.eq.f64、nabi.lt.f64 |
bool | ✓ | ✓ | ✓ | ✓ | ✓ | nabi.eq.bool(< 是普通函数体) |
char, c_char | ✓ | ✓ | ✓ | ✓ | ✓ | nabi.eq.char、... |
str | ✓ | ✓ | ✓ | ✓ | ✓ | 字典序 |
Tuple<...> | ✓(每个部分都是 PartialEq 时) | ✓ | ✓ | ✓ | ✓ | 字典序,1 到 12 个元素 |
[T; N] | ✓(T:PartialEq) | ✓ | ✓ | ✓ | ✓ | 字典序 |
List<T> | ✓(T:PartialEq 时) | ✓ | ✓ | ✓ | ✓ | 字典序 |
Dict<K,V,S> | ✓(K:Hash,V:PartialEq) | ✓(V:Eq) | ✗ | ✗ | ✓(V:Hash) | 与顺序无关的比较 / 哈希 |
Set<T,S> | ✓(T:Hash) | ✓ | ✗ | ✗ | ✓ | 与顺序无关的比较 / 哈希 |
Range<T> | ✓(T:PartialEq) | ✓(T:Eq) | ✗ | ✗ | ✓(T:Hash) | 比较 start/end |
和类型 A | B | ✓(每个成员都实现时) | ✓ | 仅 T | none | 仅 T | none | ✓ | 先 none,再比较载荷 |
Dict 和 Set 是无序容器,因此没有 PartialOrd / Ord。Dict 和 Set 的所有实现都要求键(集合元素)是 Hash。对任意 T: Hash,Set<T, S> 是 PartialEq、Eq 和 Hash。K: Hash 的 Dict<K, V, S> 在 V: PartialEq 时是 PartialEq,在 V: Eq 时是 Eq,在 V: Hash 时是 Hash。这对每个 S: BuildHasher 都成立:相等比较忽略 S。两者的比较和哈希都与迭代顺序无关(2.9)。
List 按字典序比较:从前往后比较元素,第一个不同的元素决定顺序;如果一个是另一个的前缀,较短的较小。
只有除 none 外最多含一个项的和类型才有顺序(refs-lang 2.6.4)。当 T 是 PartialOrd / Ord 时,T | none 也是:none 小于任何 T 值(与 Rust 和 Haskell 相同),两个 T 值按 T 的顺序比较。min / max / clamp 遵循同样的顺序。除 none 外含两个或更多项的和类型(i32 | str)没有 PartialOrd / Ord:比较或排序它的值是编译错误;应按某个键排序(sort_by_key、sort_by、min_by_key)。
#2.5.8. 广播比较 trait
在 2.6 广播 的 20 个广播 trait 中,6 个比较 trait 的定义如下。
trait DotEq<Rhs> { #[infix(".==")] fn dot_eq(...) -> Output; }
trait DotNe<Rhs> { #[infix(".!=")] fn dot_ne(...) -> Output; }
trait DotLt<Rhs> { #[infix(".<")] fn dot_lt(...) -> Output; }
trait DotGt<Rhs> { #[infix(".>")] fn dot_gt(...) -> Output; }
trait DotLe<Rhs> { #[infix(".<=")] fn dot_le(...) -> Output; }
trait DotGe<Rhs> { #[infix(".>=")] fn dot_ge(...) -> Output; }
每个 trait 处理 List 或 Vec3 等容器的逐元素比较;结果类型(Output)通常是 List<bool> 或 [bool; N]。
完整的广播语义见 2.6 广播。
#2.5.9. #[derive(Eq, Ord, Hash, ...)]
refs-lang 6.2 #[derive] 定义了派生机制。五个 cmp trait 都可以派生。
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
struct Version { major: u32; minor: u32; patch: u32; }
各 trait 的派生行为:PartialEq 和 Eq 定义为所有字段相等的逻辑与。PartialOrd 和 Ord 按字段声明顺序进行字典序比较。Hash 按声明顺序写入各字段,每个字段用它自己的 hash;枚举先用 write_usize 写入变体索引,只有一个变体的枚举除外。确切的写入内容不稳定(2.5.6)。
要求是每个字段(递归地)都实现同一个 trait,并且 Eq / Ord 还要求其超 trait(PartialEq / PartialOrd、Eq)已派生或已实现。只要有一个字段不实现 Eq,#[derive(Eq)] 就是编译错误。
#2.5.10. 模式匹配与 cmp
match 分支中的字面量模式使用 PartialEq::eq。
match x {
0 => "zero",
1 => "one",
_ => "other",
}
// → 0.eq(x) → compare, 1.eq(x) → compare, ...
区间模式(0..=10 =>)使用 PartialOrd::le 和 ge。
完整的模式语义见 refs-lang 3.11 模式。
#2.5.11. core::hash:哈希器
本模块包含 Hash 实现写入的目标。它不在 prelude 中:用户代码要导入它用到的名称(为 hash<H: Hasher> 实现写 use core::hash::Hasher;,或 use core::hash::{BuildHasher, RandomState};)。在值上调用 Hasher 方法(h.write_str(..))不需要 use,所有标准库 trait 都是如此。
trait Hasher {
fn write<B: AsBytes>(ref self, bytes: B); // raw bytes: no length, no terminator
fn finish(self) -> u64; // the hash so far; the state is kept
// Provided: each integer's little-endian bytes.
fn write_u8(ref self, x: u8);
fn write_u16(ref self, x: u16);
fn write_u32(ref self, x: u32);
fn write_u64(ref self, x: u64);
fn write_usize(ref self, x: usize); // 8 bytes on every target
fn write_i8(ref self, x: i8); // .. and write_i16 / i32 / i64 / isize, as the unsigned
fn write_length_prefix(ref self, len: usize); // write_usize(len)
fn write_str(ref self, s: str); // write_length_prefix(len), then the bytes
}
trait BuildHasher {
type Hasher: Hasher;
fn build_hasher(self) -> Self::Hasher;
}
struct RandomState { /* the process key */ }
impl RandomState { fn new() -> RandomState; }
impl BuildHasher for RandomState { type Hasher = DefaultHasher; }
struct DefaultHasher { /* .. */ }
struct BuildHasherDefault<H> {} // builds H::default()
impl<H: Hasher + Default> BuildHasherDefault<H> { const fn new() -> BuildHasherDefault<H>; } // also Default
impl<H: Hasher + Default> BuildHasher for BuildHasherDefault<H> { type Hasher = H; }
struct SipHasher13 { /* .. */ }
struct SipHasher24 { /* .. */ }
impl SipHasher13 { const fn with_keys(k0: u64, k1: u64) -> SipHasher13; }
impl SipHasher24 { const fn with_keys(k0: u64, k1: u64) -> SipHasher24; }
RandomState持有一个 128 位密钥,在程序第一次请求时从操作系统的随机源抽取。同一进程中的每个RandomState::new()都持有相同的密钥,所以键相同的两个字典使用相同的哈希器。它是Copy、Eq、Default,其Debug不显示密钥。它是Dict和Set的默认S(2.9.3)。DefaultHasher是RandomState的哈希器。它的算法(目前是 SipHash-1-3)以及输出都未作规定,可能在任何版本中改变。它的write_str先写入字节,再写入 UTF-8 中从不出现的字节0xFF,而不是写入长度。- 在编译时构建的
RandomState(const,或在常量求值期间生成的值)持有全零密钥,运行时从不会抽取到这个密钥。在运行时它代表进程密钥。在常量求值期间用它哈希的表,会在运行时第一次使用时用进程密钥重新哈希一次。 BuildHasherDefault<H>为每次哈希构建H::default(),用于带调用方自选哈希器的Dict/Set(Dict<K, V, BuildHasherDefault<Fnv>>)。固定的、无密钥的哈希器更快,但任何能选择键的人都可以让它们冲突;只在键不可能来自攻击者时使用。更快的哈希器由包提供。Debug:DefaultHasher、SipHasher13、SipHasher24和BuildHasherDefault<H>只打印类型名而不打印状态(SipHasher13 { .. }),因此密钥永远不会进入日志。SipHasher13/SipHasher24是使用调用方密钥的 SipHash-1-3 和 SipHash-2-4。它们对所写字节的输出就是参考 SipHash,在各版本和各目标之间保持不变:write_<int>写入整数的小端字节,write_usize写入 8 个字节。只有程序自己写入的字节和整数是稳定的;Hash实现的写入不稳定(2.5.6),因此存储的哈希值(例如分片键)绝不来自x.hash(ref h)。
use core::hash::SipHasher13;
fn shard(user: str, shards: u64) -> u64 {
let h = SipHasher13::with_keys(0x5eed, 0);
h.write(user); // the bytes alone: stable
h.finish() % shards
}
需要密码学强度时,请改用 core::crypto(SHA-2、SHA-3)。
发现错误? 在 GitHub 上编辑此页 最后更新: