Poisoning

Although all unsafe code must ensure it has minimal exception safety, not alltypes ensure maximal exception safety. Even if the type does, your code mayascribe additional meaning to it. For instance, an integer is certainlyexception-safe, but has no semantics on its own. It’s possible that code thatpanics could fail to correctly update the integer, producing an inconsistentprogram state.

This is usually fine, because anything that witnesses an exception is aboutto get destroyed. For instance, if you send a Vec to another thread and thatthread panics, it doesn’t matter if the Vec is in a weird state. It will bedropped and go away forever. However some types are especially good at smugglingvalues across the panic boundary.

These types may choose to explicitly poison themselves if they witness a panic.Poisoning doesn’t entail anything in particular. Generally it just meanspreventing normal usage from proceeding. The most notable example of this is thestandard library’s Mutex type. A Mutex will poison itself if one of itsMutexGuards (the thing it returns when a lock is obtained) is dropped during apanic. Any future attempts to lock the Mutex will return an Err or panic.

Mutex poisons not for true safety in the sense that Rust normally cares about. Itpoisons as a safety-guard against blindly using the data that comes out of a Mutexthat has witnessed a panic while locked. The data in such a Mutex was likely in themiddle of being modified, and as such may be in an inconsistent or incomplete state.It is important to note that one cannot violate memory safety with such a typeif it is correctly written. After all, it must be minimally exception-safe!

However if the Mutex contained, say, a BinaryHeap that does not actually have theheap property, it’s unlikely that any code that uses it will dowhat the author intended. As such, the program should not proceed normally.Still, if you’re double-plus-sure that you can do something with the value,the Mutex exposes a method to get the lock anyway. It is safe, after all.Just maybe nonsense.