orlp / slotmap

Slotmap data structure for Rust
zlib License
1.08k stars 70 forks source link

Detect wrongly interchanged keys during runtime #103

Open elftausend opened 11 months ago

elftausend commented 11 months ago

This pull request refers to the following statement located in the docs:

If you have multiple slot maps it’s an error to use the key of one slot map on another slot map. The result is safe, but unspecified, and can not be detected at runtime, so it can lead to a hard to find bug.

However, there may be a way to detect such occurrences during runtime, though. It utilises the core::panic::Location and #[track_caller] to match a SlotMap with a DefaultKey. This mechanic is used in RefCell as well.

I implemented a proof-of-concept for SlotMap only and would like to hear your opinion about this idea.

orlp commented 8 months ago

This is certainly an interesting idea to do in debug mode. I think for FFI / serialization purposes it should be a best-effort optional thing though. So the location would be inside an Option and the test would be self.loc.zip(other.loc).map(|a, b| a == b).unwrap_or(true).