by gspr · 2w ago · 0 comments
I don't know if it's ever been in Rust's threat model to handle malicious code.
Note that incorrect code can still cause
1. incorrect outputs, or
2. arbitrary performance degredations
safe rust doesn't have to work magic. All it must do is prevent UB.
I thought maybe I explain this well in the README for https://github.com/tialaramex/misfortunate/ but apparently not, so that's on my FIXME list now.
When I write such an explanation it will probably use Comte as an example. Comte implements ExactSizeIterator which is a safe trait for claiming your iterator gives accurate information about how many items are left. It's lying (but equally a safe implementer might just be mistaken), and Comte is not in fact giving accurate size information. However, if you need to rely on a promise that the iterator length is correct Rust has an unsafe trait for such promises named TrustedLen.
Unlike Comte, mis-implementing TrustedLen could cause Memory Unsafety, but you would need to write the `unsafe` keyword and be lying or mistaken, which is what Rust promised you will happen.
To give a concrete example, if I tell Rust I want to put the results from this iterator over Goose into an array [Goose; 6] in usual cases it will emit code to check for overflow and panic if the Iterator makes the wrong number of Goose, even if the iterator implements ExactSizeIterator and claims to have six Goose, that panic check happens. But if it implements TrustedLen and makes the same claim, the compiler will believe it and skip the check. If it was wrong about having six Goose, your program is nonsense and anything might happen.
* Non-fused iterators, implementing FusedIterator
* Iterators that, when cloned, produce an iterator with a different set of elements
* DoubleEndedIterator which is inconsistent when iterated from each end
* A trait such that cloning a Box<dyn Trait> produces a value with a different concrete type inside
* A Display type that always produces an error from fmt()
* A Display type that replaces the Formatter with a different one
* A type that always hashes to different values.