mwillsey / symbol_table

A string interner
MIT License
9 stars 8 forks source link

Question on safety of returning a string reference in `resolve` #6

Closed ravern closed 6 months ago

ravern commented 6 months ago

Not trying to report a bug, just curious how some of the code here works. Thanks in advance, and no pressure on answering this quickly!


In the following lines, the comment asserts that it is safe to return a reference to the string because we know it will never be moved.

https://github.com/mwillsey/symbol_table/blob/d521c91691bf208ef625f16f3d6bc75c2f7390be/src/lib.rs#L176-L181

However, in the following lines, strs.push is called, which I expect might copy the contents of the Vec to a new location should the Vec need to be grown. I couldn't find any other code to handle this case.

https://github.com/mwillsey/symbol_table/blob/d521c91691bf208ef625f16f3d6bc75c2f7390be/src/lib.rs#L97-L98

My question is just whether there's something I missed here? Or is my assumption that Vec copies its contents wrong?

mwillsey commented 6 months ago

You are correct that Vec might move its contents around, but the string doesn't sit in the vec! The Vec holds Strings (well, actually Box<str>s), and that additional layer of indirection is what makes this safe.

ravern commented 6 months ago

That makes so much sense, thanks!