Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Would it be possible for ThreadLocal to return pinned references to the local data? #66

Open
eggyal opened this issue Dec 16, 2023 · 6 comments

Comments

@eggyal
Copy link

eggyal commented Dec 16, 2023

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?

@Amanieu
Copy link
Owner

Amanieu commented Dec 16, 2023

Yes, this can be guaranteed. But I'm not sure how to expose this as an API.

@eggyal
Copy link
Author

eggyal commented Dec 16, 2023

Would it not be fn get(&self) -> Option<Pin<&T>> etc ?

@Amanieu
Copy link
Owner

Amanieu commented Dec 17, 2023

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.

@eggyal
Copy link
Author

eggyal commented Dec 17, 2023

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 ?

@Amanieu
Copy link
Owner

Amanieu commented Dec 17, 2023

But the lifetime is still tied to the lifetime of the ThreadLocal. What if you forget the pinned reference and then drop the ThreadLocal?

@eggyal
Copy link
Author

eggyal commented Dec 17, 2023

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants