#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 一致性承諾)
- impl 寫入什麼
- 取得雜湊值
- 使用者定義
- 碰撞
- 穩定性
- 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 impl 所寫入的雜湊器位於 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 的一致性承諾與全序保證,在 Hash、Dict/Set 與排序演算法中維持安全。
#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 成立)。自反性(a == a)沒有保證,原因是 IEEE 754 的 NaN。
#預設的 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 的鍵與排序演算法只有在這項承諾下才能正確運作。
impl 方針如下。所有整數/布林值/字元/字串型別(i32、i64、u8..u64、bool、char、c_char、str 等)都實作 Eq。浮點型別以及包含它們的和型別(f32、f64、f64 | none 等)不實作 Eq。只有在每個欄位都是 Eq 時,才能對使用者的 struct 或 enum 寫 #[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 表示。
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 值。
排序演算法只有在這項保證下才能正確運作。
impl 方針:i32、i64、u*、bool、char、c_char、str 實作 Ord。f32 與 f64 不實作,因為 NaN 讓某些值無法比較。
#min / max / clamp
提供三個預設方法,impl 不需實作即可使用。相等時 min 回傳 self、max 回傳 rhs,因此在相等的值之中,min 保留第一個、max 保留最後一個,與 Iterator::min/max 相同(2.7)。low > high 時 clamp 會觸發 panic,與 f64::clamp 相同。
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。
#impl 寫入什麼
impl 以固定順序寫入其各個部分,每個部分用它自己的 hash 或 Hasher 的 write_<int>。長度可變的一串值(串列的項目)以 h.write_length_prefix(len) 開頭。若沒有它,相鄰的串可能彼此錯位:[[1, 2], [3]] 與 [[1], [2, 3]] 會做出相同的寫入。write_str 本身就是無前綴碼,前面永遠不會加 write_length_prefix。
標準 impl 寫入:
| 型別 | 寫入 |
|---|---|
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(member index),然後是該成員的 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
手寫的 impl 正好寫入相等性所檢查的內容:
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。這不是錯誤:在 64 位元的雜湊空間中碰撞無法避免。Dict 等資料結構會處理碰撞。
#穩定性
核心承諾是唯一的承諾。雜湊值在同一程式的不同次執行之間、不同機器之間、不同 Nabi 版本之間都可能不同,impl 所做的寫入也一樣。程式不得儲存雜湊值或把它傳給其他行程;必須保持不變的雜湊值,要直接餵位元組與整數給 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) | 比較起點/終點 |
和型別 A | B | ✓(每個成員都實作時) | ✓ | 僅 T | none | 僅 T | none | ✓ | none 優先 → 酬載 |
Dict 與 Set 是無序容器,因此沒有 PartialOrd/Ord。每個 Dict 與 Set 的 impl 都要求鍵(集合元素)是 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 定義為所有欄位相等性的 AND。PartialOrd 與 Ord 依欄位宣告順序以字典序比較。Hash 依宣告順序寫入欄位,每個欄位用它自己的 hash;enum 會先以 write_usize 寫入變體索引,只有一個變體的 enum 除外。確切的寫入內容並不穩定(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 impl 所寫入的雜湊器。它不在 prelude 中:使用者程式碼要匯入它所指名的項目(hash<H: Hasher> impl 用 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 個位元組。只有程式自己寫入的位元組與整數是穩定的;Hashimpl 的寫入並不穩定(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 上編輯此頁 最後更新: