Hi @alice , out of curiosity. Isn't asyncread and asyncwrite also take &mut self just like fastwebsocket read_frame and write_frame?
I encounter an issue in github where the author explain that the reason both of the method take &mut self is due to the underlying asyncread and asyncwrite of the wrapped stream.
Yes, but the difference is that with poll methods, the mutable borrow is much shorter. A call to write_frame will mutably borrow the websocket until the entire write is completed. On the other hand, a call to poll_write only borrows the websocket during the call to poll itself. Even if poll_write returns Pending to signal that the write is still ongoing, you can still call poll_read right afterwards.
Wait, i'm not sure i fully grasp it. Isn't write_frame end up calling poll method from the underlying stream when it writes the message to the socket? Or do you mean that it is longer due to several steps that need to be performed before call to the underlying stream's poll method?
The write_frame method returns a future. This future will mutably borrow the websocket until the future is destroyed, and you don't destroy the future until the write has fully completed. Poll methods do not involve a future, so this issue goes away.
Sometimes you can drop the future even though the write is still ongoing, and recreate the future when you wish to continue the write. However, this is only okay when the future is cancel safe, but write_frame is not cancel safe. This is because it uses the non-cancel safe method write_all.