I'm writing a stream adapter that requires a shared ownership of the stream.
Is it correct to store the stream (privately) in Pin<Arc<Mutex<impl Stream>>>?
How can I call poll_next(self: Pin<&mut Stream> on the stream?
I'm writing a stream adapter that requires a shared ownership of the stream.
Is it correct to store the stream (privately) in Pin<Arc<Mutex<impl Stream>>>?
How can I call poll_next(self: Pin<&mut Stream> on the stream?
Copyright © 2021 Jogjafile Inc.
Mutexdoes not have what is called structural pinning, which is described in thestd::pinmodule documentation:Mutex<T>does not have structural pinning because the pinned-ness of the struct (theMutex) does not propagate to the field (theT) -- it is safe to get an unpinned&mut Tfrom aPin<&mut Mutex<T>>(i.e., by usingDerefinstead ofDerefMutand locking the mutex), even ifTandMutex<T>are!Unpin.In order to turn this
&mut Tinto aPin<&mut T>, you have to make another layer of unchecked guarantee, usingunsafeandPin::new_unchecked, to prove that theTitself is never moved. This seems to defeat the purpose of the "outer"Pin.Depending on what your data structures allow, you might consider one of these options:
Arc<Mutex>that pins the contents of theMutexwhen accessed through aPin(you couldn't implementDeref, but you could write methods that returnedMutexGuards and did thePin-wrapping internally)Stream, if your data structure allows it.