In the docs for the
Ord trait, they talk about various requirements that a correct implementation of must meet. For example, if A<B and B<C, then A<C. The problem is that while the trait docs say that ordering relations have these properties, you could implement it in a way that doesn't follow them. For example, you could implement it such that
a.cmp(b)==Ordering::Greater for all
b. By itself, this incorrect implementation doesn't pose a threat to memory safety, and without unsafe code, it never will. However, you could write unsafe code is that only correct if the implementation of
Ord is valid. It's not easy to come up with an example of this off the top of my head, but it could go a little bit like this:
- You compare A and B, and find that A<B.
- You compare B and C, and find that B<C.
- You assume that this means A<C, and store some value somewhere based on that assumption.
- Later on, you compare A and C, and find that A>C.
- You read a value from the place that you would have stored it if A was greater than C, which is uninitialized because you previously assumed A was less than C based on the properties
Ord implementations should have.
It essentially boils down to one piece of advice: assume that people using your interface might be writing broken code, and make sure that your code will never do anything invalid as a result of mistakes they made.