Would it be possible for `ThreadLocal` to return pinned references to the local data?
eggyal opened this issue · comments
That is, could this library guarantee that the local data will not move until the ThreadLocal
is dropped, permitting unsafe code to access the local data (using raw pointers) after the the borrow of the ThreadLocal
itself expires?
Yes, this can be guaranteed. But I'm not sure how to expose this as an API.
Would it not be fn get(&self) -> Option<Pin<&T>>
etc ?
No, that's unsound: Pin
requires the underlying memory to remain valid if you mem::forget
the pin. That's not possible for references which are invalidated when their lifetime ends.
But just because the API returns a Pin<&T>
doesn't mean that's where it originated. Internally I imagine the library will store the data in a Pin<Box<[T]>>
or somesuch, and then map that to Pin<&T>
for the user.
Isn't "the underlying memory will remain valid if you mem::forget
the pin" precisely the intent we want the API to convey ?
But the lifetime is still tied to the lifetime of the ThreadLocal
. What if you forget
the pinned reference and then drop the ThreadLocal
?
I don't think that violates Pin
's guarantees but I'll readily admit that I haven't fully wrapped my head around it. I would note however that there are APIs in the standard library (including of course on Pin
itself) that return Pin<&T>
so that cannot in and of itself be unsound, which I think is what you seem to be suggesting?