Re:A JVM in Rust part 5 – Executing instructions
by pie_flavor on Monday August 28, 2023 @08:11PM
(#37301924)
The better way to do this is to use an indexing arena such as `slotmap` or `generational-arena`, so `ClassRef` is not actually a memory pointer to anything but can still be looked up in the context of the class collection. Or, if you never need to remove any values, you can use Vec as your arena and usize as your key.
[ Parent
| on HN ]
Re:A JVM in Rust part 5 – Executing instructions
by fleventynine on Monday August 28, 2023 @10:06PM
(#37302677)
IMHO, using an vector index as a pointer should be a last resort (as an alternative to unsafe). Although it's memory safe, you still have many of the traditional issues like stale pointers / use-after-free, plus you also have the cost of a bounds-check on every access and making sure you use your stored indexes with the correct container instance. If you can solve your problem by using safe code with lifetimes, that should be preferred.
Re:A JVM in Rust part 5 – Executing instructions
by pie_flavor on Monday August 28, 2023 @10:39PM
(#37302941)
What is presented here is a self-referential type, and Rust does not allow you to declare self-referential types, and an indexed arena is a solution to that. You are correct that you still have all the issues you described - that doesn't mean it should be a 'last resort' to stop using an incorrect system of lifetimes, because there is no 'safe code with lifetimes' that encodes a self-referential type. The type safety issue is solved by using slotmap or typed-generational-arena, which use unique key types.