1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
//! **Rel**ation **tester** is a small testing utility for automatically
//! checking the correctness of `[Partial]Eq`, `[Partial]Ord`, `Hash`, and
//! `[DoubleEnded|Fused]Iterator` trait implementations. It's most useful when
//! used in conjuction with
//! [`quickcheck`](https://github.com/BurntSushi/quickcheck) or some other
//! property-based testing framework.
//!
//! # Rationale
//!
//! Imagine a scenario where you have a type `Foo` with a custom implementation
//! of either [`PartialEq`], [`Eq`], [`PartialOrd`], or [`Ord`]. By "custom" we mean
//! hand-written as opposed to derived. The Rust compiler alone cannot verify
//! the correctness of these implementations and thus it is up to you, the
//! programmer, to uphold certain invariants about the specific [binary
//! relation](https://en.wikipedia.org/wiki/Binary_relation) that you're
//! implementing. For example, if you implement [`PartialEq`] for `Foo`, you must
//! guarantee that `foo1 == foo2` implies `foo2 == foo1` (*symmetry*).
//!
//! Other traits such as [`Hash`] and [`Iterator`] mandate their own invariants as
//! well – some of which are very intuitive, and
//! [others](https://doc.rust-lang.org/std/hash/trait.Hash.html#prefix-collisions)
//! which are not. It's especially common for less-than-perfect implementations
//! of the [`std::iter`] family of traits to introduce off-by-one
//! bugs[^1] [^2] [^3] [^4] among others.
//!
//! The idea is, instead of keeping these invariants in your head whenever you
//! go about manually implementing one of these traits in your codebase, you can
//! add a Reltester check to your test suite and have a higher degree of
//! confidence that your implementation is correct.
//!
//! # How to use
//!
//! 1. Write some tests that generate random values of the type you wish to
//!    test. You can do this by hand or using crates such as
//!    [`quickcheck`](https://github.com/BurntSushi/quickcheck) and
//!    [`proptest`](https://github.com/proptest-rs/proptest). Calling the checkers
//!    on static, non-randomized values is possible but is less effective in
//!    catching bugs.
//! 2. Based on the traits that your type implements, call the appropriate checker(s):
//!
//!    - [`reltester::eq`](eq) for [`Eq`];
//!    - [`reltester::ord`](ord) for [`Ord`];
//!    - [`reltester::partial_eq`](partial_eq) for [`PartialEq`];
//!    - [`reltester::partial_ord`](partial_ord) for [`PartialOrd`];
//!    - [`reltester::hash`](hash) for [`Hash`];
//!    - [`reltester::iterator`](iterator) for [`Iterator`];
//!    - [`reltester::fused_iterator`](fused_iterator) for [`FusedIterator`];
//!    - [`reltester::double_ended_iterator`](double_ended_iterator) for [`DoubleEndedIterator`];
//!
//!    Some of these functions take multiple (two or three) values of the same
//!    type. This is because it takes up to three values to test some
//!    invariants.
//!
//! The [`reltester::invariants`](invariants) module is available for more
//! granular checks if you can't satisfy the type bounds of the main functions.
//!
//! ## Multi-type relations: `Foo: PartialEq<Bar>` and `Foo: PartialOrd<Bar>`
//!
//! In some cases your [`PartialEq`] and [`PartialOrd`] implementations
//! may use a non-`Self` type parameter. (Note: [`Eq`] and [`Ord`] don't accept
//! type parameters and this use case doesn't apply to them.) Reltester
//! supports this use case and exposes granular invariant checking functions in
//! the [`invariants`] module with more lax type constraints.
//!
//! ## Examples
//!
//! ### `f32` (`PartialEq`, `PartialOrd`)
//!
//! ```rust
//! use reltester;
//! use quickcheck_macros::quickcheck;
//!
//! #[quickcheck]
//! fn test_f32(a: f32, b: f32, c: f32) -> bool {
//!     // Let's check if `f32` implements `PartialEq` and `PartialOrd` correctly
//!     // (spoiler: it does).
//!     reltester::partial_eq(&a, &b, &c).is_ok()
//!         && reltester::partial_ord(&a, &b, &c).is_ok()
//! }
//! ```
//!
//! ### `u32` (`Hash`)
//!
//! ```rust
//! use reltester;
//! use quickcheck_macros::quickcheck;
//!
//! #[quickcheck]
//! fn test_u32(a: u32, b: u32) -> bool {
//!     // Unlike `f32`, `u32` implements both `Eq` and `Hash`, which allows us to
//!     // test `Hash` invariants.
//!     reltester::hash(&a, &b).is_ok()
//! }
//! ```
//!
//! ### `Vec<u32>` (`DoubleEndedIterator`, `FusedIterator`, `Iterator`)
//!
//! ```rust
//! use reltester;
//! use quickcheck_macros::quickcheck;
//!
//! #[quickcheck]
//! fn test_vec_u32(nums: Vec<u32>) -> bool {
//!     // `Iterator` is implied and checked by both `DoubleEndedIterator` and
//!     // `FusedIterator`.
//!     reltester::double_ended_iterator(nums.iter()).is_ok()
//!         && reltester::fused_iterator(nums.iter()).is_ok()
//! }
//! ```
//!
//! # TL;DR invariants of the comparison traits
//!
//! Chances are you don't need to concern yourself with the mathematical definitions of
//! comparison traits; as long as your implementations are sensible and your
//! `reltester` tests pass, you can move on and assume your implementations are
//! correct. The required invariants are listed here only for the sake of
//! completeness.
//!
//! - [`PartialEq`] requires **symmetry** and **transitivity** of `==` whenever applicable ([partial
//!   equivalence
//!   relation](https://en.wikipedia.org/wiki/Partial_equivalence_relation) in the
//!   case of `Rhs == Self`).
//! - [`Eq`] requires **symmetry**, **transitivity**, and **reflexivity** of `==` ([equivalence relation](https://en.wikipedia.org/wiki/Equivalence_relation)).
//! - [`PartialOrd`] requires **symmetry** of `==`, **transitivity** of `>`,
//!   `==`, and `<`; and **duality** of `>` and `<`. Note that duality is not
//!   common mathematical
//!   terminology, it's just what the Rust [`std`] uses to describe `a > b iff b < a`.
//!   Thus the exact mathematical definition of [`PartialOrd`] seems [open to
//!   debate](https://users.rust-lang.org/t/traits-in-std-cmp-and-mathematical-terminology/69887),
//!   though it's generally understood to mean [strict partial
//!   order](https://en.wikipedia.org/wiki/Partially_ordered_set#Strict_partial_orders).
//! - [`Ord`] requires **symmetry** and **reflexivity** of `==`; **transitivity** of `>`, `==`, and `<`; and **duality** of `>` and `<`.
//!   `==`; **transitivity** and **duality** of `>` and `<`; and must be **trichotomous**[^5]. Just like
//!   [`PartialOrd`], the mathematical definition of [`Ord`] is a bit open to
//!   interpretation, though it's generally understood to mean [total
//!   order](https://en.wikipedia.org/wiki/Total_order#Strict_and_non-strict_total_orders).
//!
//! In addition to the above, trait method default implementation overrides (for e.g.
//! [`PartialOrd::lt`] or [`Ord::max`]) must have the same behavior as the
//! default implementations. `reltester` always checks these for you.
//!
//!
//! [^1]: <https://github.com/rust-lang/rust/issues/41964>
//!
//! [^2]: <https://github.com/bevyengine/bevy/pull/7469>
//!
//! [^3]: <https://github.com/bluejekyll/trust-dns/issues/1638>
//!
//! [^4]: <https://github.com/sparsemat/sprs/issues/261>
//!
//! [^5]: Trichotomy is a corollary that follows from the definitions of `>`,
//! `==`, and `<` based on [`Ordering`](std::cmp::Ordering).

#![allow(clippy::eq_op, clippy::double_comparisons)]

pub mod error;
pub mod invariants;

use error::*;
use std::{hash::Hash, iter::FusedIterator};

/// Checks the correctness of the [`Ord`] trait (and [`Eq`] and [`PartialOrd`]
/// by extension) for some values.
pub fn ord<T>(a: &T, b: &T, c: &T) -> Result<(), Error>
where
    T: Ord,
{
    eq(a, b, c)?;
    partial_ord(a, b, c)?;

    invariants::ord_methods_consistency(a, b, c)?;

    Ok(())
}

/// Checks the correctness of the [`PartialOrd`] trait (and [`PartialEq`] by
/// extension) for some values.
pub fn partial_ord<T>(a: &T, b: &T, c: &T) -> Result<(), Error>
where
    T: PartialOrd,
{
    partial_eq(a, b, c)?;

    invariants::partial_ord_methods_consistency(a, b)?;
    invariants::partial_ord_duality(a, b)?;
    invariants::partial_ord_transitivity(a, b, c)?;

    Ok(())
}

/// Checks the correctness of the [`Eq`] trait (and [`PartialEq`] by extension)
/// for some values.
///
/// The type bound is intentionally [`PartialEq`] instead of [`Eq`] to allow
/// for negative testing, i.e. ensuring that your [`PartialEq`] implementor
/// *doesn't* implement [`Eq`] when it shouldn't.
pub fn eq<T>(a: &T, b: &T, c: &T) -> Result<(), Error>
where
    T: PartialEq<T>,
{
    partial_eq(a, b, c)?;

    // Checking `Eq` is the same as checking `PartialEq`, except it also
    // requires reflexivity.
    invariants::eq_reflexivity(a)?;

    Ok(())
}

/// Checks the correctness of the [`PartialEq`] trait
/// for some values.
pub fn partial_eq<T>(a: &T, b: &T, c: &T) -> Result<(), PartialEqError>
where
    T: PartialEq,
{
    invariants::partial_eq_methods_consistency(a, b)?;
    invariants::partial_eq_symmetry(a, b)?;
    invariants::partial_eq_transitivity(a, b, c)?;

    Ok(())
}

/// Checks the correctness of the [`Hash`] trait in relation to [`Eq`] for some
/// values.
pub fn hash<K>(a: &K, b: &K) -> Result<(), HashError>
where
    K: Hash + Eq + ?Sized,
{
    invariants::hash_consistency_with_eq(a, b)?;
    invariants::hash_prefix_collision(a, b)?;

    Ok(())
}

/// Checks the correctness of the [`Iterator`] trait for some value `iter`.
///
/// Note that `iter` must be a finite iterator.
pub fn iterator<I>(iter: I) -> Result<(), IteratorError>
where
    I: Iterator + Clone,
    I::Item: PartialEq,
{
    invariants::iterator_size_hint(iter.clone())?;
    invariants::iterator_count(iter.clone())?;
    invariants::iterator_last(iter)?;

    Ok(())
}

/// Checks the correctness of the [`DoubleEndedIterator`] trait (and
/// [`Iterator`] by extension) for some value `iter`.
///
/// Note that `iter` must be a finite iterator.
pub fn double_ended_iterator<I>(iter: I) -> Result<(), IteratorError>
where
    I: DoubleEndedIterator + Clone,
    I::Item: PartialEq,
{
    iterator(iter.clone())?;

    invariants::double_ended_iterator_next_back(iter)?;

    Ok(())
}

/// Checks the correctness of the [`FusedIterator`] trait (and
/// [`Iterator`] by extension) for some value `iter`.
///
/// Note that `iter` must be a finite iterator.
pub fn fused_iterator<I>(iter: I) -> Result<(), IteratorError>
where
    I: FusedIterator + Clone,
    I::Item: PartialEq,
{
    iterator(iter.clone())?;

    invariants::fused_iterator_none_forever(iter)?;

    Ok(())
}

#[allow(dead_code)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctest;