本頁尚未翻譯,以下為英文原文。
#2.5. Comparison traits
本頁內容
- 2.5.1. The 4-trait hierarchy - why partial is needed
- 2.5.2. PartialEq - partial equality (==, !=)
- Default ne
- Examples
- 2.5.3. Eq - total equality
- 2.5.4. PartialOrd - partial order (<, >, <=, >=)
- The Ordering type
- Comparison chains
- 2.5.5. Ord - total order
- min / max / clamp
- 2.5.6. Hash - hashing (Eq consistency promise)
- What an impl writes
- Getting a hash
- User-defined
- Collisions
- Stability
- 2.5.7. Implementation matrix
- 2.5.8. Broadcast comparison traits
- 2.5.9. #[derive(Eq, Ord, Hash, ...)]
- 2.5.10. Pattern matching and cmp
- 2.5.11. core::hash - hashers
This chapter covers the trait family that defines comparison between values. Not only the ==, !=, <, >, <=, >= operators but also hashing, sorting and pattern matching dispatch through the traits of this chapter.
The traits live in two modules. PartialEq and PartialOrd carry the comparison operators, so they are defined in core::ops with the other operator traits (2.3). Eq, Ord, Hash and Ordering are defined in core::cmp. PartialEq, PartialOrd, Eq, Ord, Hash and Ordering are in the prelude (0.2.3), so user code names them without a use. The hashers a Hash impl writes to are in core::hash (2.5.11).
Nabi splits comparison into a 4-trait hierarchy (PartialEq / Eq / PartialOrd / Ord) plus a separate Hash trait. The split satisfies two practical requirements at once: NaN handling for IEEE 754 floating-point, and guaranteed hash consistency.
#2.5.1. The 4-trait hierarchy - why partial is needed
The hierarchy can be described from two viewpoints at once.
Set viewpoint: A ⊃ B means "the set of types satisfying A contains the set of types satisfying B". A is more general; B is more specific.
PartialEq ⊃ Eq // set of PartialEq types ⊇ set of Eq types
PartialOrd ⊃ Ord // (every Eq is PartialEq, but not vice versa)
PartialEq ⊃ PartialOrd
Implication viewpoint (supertrait): B ⇒ A means "implementing B automatically requires A"; in Nabi code it is written trait B: A. A is then a supertrait of B.
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
The two viewpoints express exactly the same fact from different angles. If B ⇒ A, every type that is B is also A, so A ⊃ B follows. In the set viewpoint, the supertrait is "the larger side".
The Hash trait sits on a line separate from the hierarchy above.
Eq ⊃ Hash // only some Eq types are Hash; Hash promises consistency with Eq
Partial is split out because of NaN in IEEE 754 floating point.
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 is not equal even to itself. This violates reflexivity: a == a is not guaranteed. Trait implementations therefore split by type: f32 and f64 implement only PartialEq, PartialOrd, while i32, bool, str and the like implement up to Eq, Ord and satisfy a total order.
This split keeps Hash's consistency promise and the total ordering guarantee safe in Hash, Dict / Set and sort algorithms.
#2.5.2. PartialEq - partial equality (==, !=)
Partial equality is defined as follows.
#[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
}
}
The Unicode tokens ≡ and ≠ have no infix bindings of their own. The lexer reads them as == and != (refs-lang 1.10.3), so they dispatch to eq and ne.
The promises of PartialEq are symmetry (a == b and b == a are equivalent) and transitivity (if a == b and b == c hold, a == c holds). Reflexivity (a == a) is not guaranteed, because of IEEE 754 NaN.
#Default ne
ne is implemented by default as !self.eq(rhs). A user may implement it separately, e.g. for performance.
#Examples
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 - total equality
Total equality is defined as a marker trait.
trait Eq: PartialEq<Self> {
// marker trait: no additional methods
}
Eq is a marker trait: it adds no methods, only the reflexivity promise.
The promise Eq adds is reflexivity: a == a is always true. Dict / Set keys and sort algorithms work correctly only with this promise.
The impl policy is as follows. All integer / boolean / character / string types (i32, i64, u8..u64, bool, char, c_char, str, etc.) implement Eq. Floating-point types and sum types containing them (f32, f64, f64 | none, etc.) do not implement Eq. #[derive(Eq)] on a user struct or enum is possible only when every field is Eq.
let n: i32 = 42;
n == n; //→ true (guaranteed by Eq)
#2.5.4. PartialOrd - partial order (<, >, <=, >=)
The partial order trait defines the comparison operators.
#[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
}
}
As with ≡ and ≠, the lexer reads ≤ and ≥ as <= and >=.
The promises of this trait: antisymmetry (if a < b then !(b < a)) and transitivity (for defined comparisons, if a < b and b < c then a < c). Trichotomy holds only partially: the order between two values is not always defined, and incomparable values such as NaN exist.
partial_cmp is a provided method (with a default implementation) and returns Ordering | none. It is none when the values are incomparable (NaN, etc.).
#The Ordering type
The result of a 3-way comparison is represented by this enum.
enum Ordering {
Less,
Equal,
Greater,
}
Ord::cmp returns Ordering directly. Ordering implements Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash and Debug (Less / Equal / Greater; Less < Equal < Greater), and has these inherent methods.
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
#Comparison chains
As defined by refs-lang 3.2.5, comparisons of one direction chain, each operand evaluated once:
lo <= x < hi; // lo <= x && x < hi
a < b > c; // compile error: two directions; write a < b && b > c
#2.5.5. Ord - total order
The total order trait is defined as follows.
#[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 }
}
}
The promise Ord adds is totality: the order between any two values is defined as one of Less, Equal, Greater. partial_cmp therefore never returns none; it always returns an Ordering value.
Sort algorithms work correctly only with this guarantee.
Impl policy: i32, i64, u*, bool, char, c_char, str implement Ord. f32 and f64 do not, because NaN makes some values incomparable.
#min / max / clamp
Three default methods are provided, usable without the impl implementing them. On a tie min returns self and max returns rhs, so of equal values min keeps the first and max the last, as Iterator::min / max do (2.7). clamp panics when low > high, like 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 - hashing (Eq consistency promise)
A Hash value feeds itself to a Hasher (2.5.11), which turns what it was given into a u64.
#[lang("hash_trait")]
trait Hash: Eq {
fn hash<H: Hasher>(self, ref h: H);
}
The core promise is:
a == b⇒aandbmake the same sequence of writes, so every hasher gives them the same hash
This promise underpins the correctness of every algorithm in Dict<K, V, S> and Set<T, S>.
Since Hash: Eq, a type that does not implement Eq cannot implement Hash either. f64 does not implement Eq, so it cannot implement Hash.
#What an impl writes
An impl writes its parts in a fixed order, each with its own hash or a write_<int> of the Hasher. A variable-length run of values (a list's items) starts with h.write_length_prefix(len). Without it, adjacent runs could shift into each other: [[1, 2], [3]] and [[1], [2, 3]] would make the same writes. write_str is prefix-free by itself and is never preceded by write_length_prefix.
The standard impls write:
| Type | Writes |
|---|---|
i*, u* | write_<type>(self); usize / isize as 8 bytes on every target |
bool | write_u8(0 / 1) |
char / c_char | write_u32 / write_u8 |
str | write_str(self) |
List<T> | write_length_prefix(len), then each item |
[T; N] | each item (N is part of the type) |
| tuples | each component in order |
sum A | B | write_usize(member index), then the member's hash |
NonZero / Positive | the inner value |
NonNan / Finite | the bits as write_u64, -0.0 as 0.0 |
Int | the sign, write_length_prefix(limbs), then the 32-bit limbs; the same for every form of one value |
Dict<K, V, S> / Set<T, S> | each entry hashed alone with a hasher of RandomState::new(), the results summed (wrapping); then write_length_prefix(len) and write_u64(sum) |
Dict and Set hash independently of order, as they compare. Every entry uses the process key whatever S is, so two equal dicts hash alike even when their S differ.
#Getting a hash
There is no one-call form: build a hasher, write, finish.
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
#User-defined
#[derive(PartialEq, Eq, Hash)]
struct UserId { id: u64; }
// automatic derive: possible because every field (id: u64) is Eq+Hash
A hand-written impl writes exactly what equality looks at:
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
}
}
#Collisions
Two different values of the same type may hash alike, even when a != b. This is not a bug: collisions are unavoidable in a 64-bit hash space. Data structures such as Dict handle collisions.
#Stability
The core promise is the only one. A hash value may differ between runs of the same program, between machines and between Nabi versions, and so may the writes an impl makes. A program must not store a hash or send it to another process; a hash that must stay the same comes from SipHasher13 / SipHasher24 fed bytes and integers directly (2.5.11), never from x.hash(ref h). Dict and Set hash with RandomState by default, whose key is drawn at random once per process, so where a key lands in the table differs from run to run; what they iterate and print does not, since that is insertion order (2.9.3).
#2.5.7. Implementation matrix
Trait implementations per type are summarized below.
| Type | PartialEq | Eq | PartialOrd | Ord | Hash | Behavior |
|---|---|---|---|---|---|---|
i*, u* | ✓ | ✓ | ✓ | ✓ | ✓ | nabi.eq.OP, nabi.lt.OP, ... |
f32, f64 | ✓ | ✗ | ✓ | ✗ | ✗ | nabi.eq.f64, nabi.lt.f64 |
bool | ✓ | ✓ | ✓ | ✓ | ✓ | nabi.eq.bool (< a plain body) |
char, c_char | ✓ | ✓ | ✓ | ✓ | ✓ | nabi.eq.char, ... |
str | ✓ | ✓ | ✓ | ✓ | ✓ | lexicographic |
Tuple<...> | ✓ (when every part is PartialEq) | ✓ | ✓ | ✓ | ✓ | lexicographic, 1-12 elements |
[T; N] | ✓ (T:PartialEq) | ✓ | ✓ | ✓ | ✓ | lexicographic |
List<T> | ✓ (when T:PartialEq) | ✓ | ✓ | ✓ | ✓ | lexicographic |
Dict<K,V,S> | ✓ (K:Hash, V:PartialEq) | ✓ (V:Eq) | ✗ | ✗ | ✓ (V:Hash) | order-independent comparison / hash |
Set<T,S> | ✓ (T:Hash) | ✓ | ✗ | ✗ | ✓ | order-independent comparison / hash |
Range<T> | ✓ (T:PartialEq) | ✓ (T:Eq) | ✗ | ✗ | ✓ (T:Hash) | start/end comparison |
Sum A | B | ✓ (when every member implements it) | ✓ | T | none only | T | none only | ✓ | none first → payload |
Dict and Set are unordered containers, so they have no PartialOrd / Ord. Every Dict and Set impl requires the keys (set elements) to be Hash. Set<T, S> is PartialEq, Eq and Hash for any T: Hash. Dict<K, V, S> with K: Hash is PartialEq when V: PartialEq, Eq when V: Eq and Hash when V: Hash. That holds for every S: BuildHasher: equality ignores S. Both compare and hash independently of iteration order (2.9).
List compares lexicographically: elements are compared from the front, the first differing element decides the order, and if one is a prefix of the other, the shorter one is smaller.
Only a sum with at most one term besides none is ordered (refs-lang 2.6.4). T | none is PartialOrd / Ord when T is: none is less than any T value (as in Rust and Haskell), and two T values compare by T's order. min / max / clamp follow the same order. A sum with two or more terms besides none (i32 | str) has no PartialOrd / Ord: comparing or sorting its values is a compile error; order them by a key (sort_by_key, sort_by, min_by_key).
#2.5.8. Broadcast comparison traits
Of the 20 broadcast traits of 2.6 broadcast, the 6 comparison traits are defined as follows.
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; }
Each trait handles element-wise comparison of containers such as List or Vec3; the result type (Output) is usually List<bool> or [bool; N].
See 2.6 broadcast for the full broadcast semantics.
#2.5.9. #[derive(Eq, Ord, Hash, ...)]
refs-lang 6.2 #[derive] defines the derive mechanism. All five cmp traits can be derived.
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
struct Version { major: u32; minor: u32; patch: u32; }
Derive behavior per trait: PartialEq and Eq are defined as the AND of equality of all fields. PartialOrd and Ord compare lexicographically in field declaration order. Hash writes the fields in declaration order, each with its own hash; an enum first writes its variant index with write_usize, except an enum of one variant. The exact writes are not stable (2.5.6).
The requirement is that every field (recursively) implements the same trait, and Eq / Ord also require their supertraits (PartialEq / PartialOrd, Eq) to be derived or implemented. If even one field does not implement Eq, #[derive(Eq)] is a compile error.
#2.5.10. Pattern matching and cmp
Literal patterns in match arms use PartialEq::eq.
match x {
0 => "zero",
1 => "one",
_ => "other",
}
// → 0.eq(x) → compare, 1.eq(x) → compare, ...
Range patterns (0..=10 =>) use PartialOrd::le and ge.
See refs-lang 3.11 Patterns for the full pattern semantics.
#2.5.11. core::hash - hashers
The module holds what a Hash impl writes to. It is not in the prelude: user code imports what it names (use core::hash::Hasher; for a hash<H: Hasher> impl, use core::hash::{BuildHasher, RandomState};). Calling a Hasher method on a value (h.write_str(..)) needs no use, as for every standard library 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; }
RandomStateholds a 128-bit key drawn from the operating system's random source the first time a program asks for one. EveryRandomState::new()in one process holds the same key, so two dicts with equal keys use the same hasher. It isCopy,Eq,Default, and itsDebugshows no key. It is the defaultSofDictandSet(2.9.3).DefaultHasherisRandomState's hasher. Its algorithm (SipHash-1-3 today) and so its output are unspecified and may change in any release. Itswrite_strwrites the bytes and then the byte0xFF, which UTF-8 never holds, instead of a length.- A
RandomStatebuilt at compile time (aconst, or a value made during constant evaluation) holds the all-zero key, which the run time never draws. At run time it stands for the process key. A table hashed with it during constant evaluation is rehashed with the process key on its first use at run time, once. BuildHasherDefault<H>buildsH::default()for every hash, for aDict/Setwith a hasher of the caller's (Dict<K, V, BuildHasherDefault<Fnv>>). A fixed, unkeyed hasher is faster but lets anyone who chooses the keys make them collide; use one only when keys cannot come from an attacker. Faster hashers come from packages.Debug:DefaultHasher,SipHasher13,SipHasher24andBuildHasherDefault<H>print their type name and no state (SipHasher13 { .. }), so a key never reaches a log.SipHasher13/SipHasher24are SipHash-1-3 and SipHash-2-4 under the caller's key. Their output for the bytes written is the reference SipHash and stays the same across releases and targets:write_<int>writes the integer's little-endian bytes,write_usize8 of them. Only the bytes and integers a program writes itself are stable; the writes of aHashimpl are not (2.5.6), so a stored hash, such as a sharding key, never comes fromx.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
}
For cryptographic strength use core::crypto (SHA-2, SHA-3) instead.
Found a mistake? Edit this page on GitHub. Last updated