Why futures don't implement the typestate pattern?

130 points servermeta_net 82 comments

Calling the poll method on a Future in the Poll::Ready state is UB. Why the std library doesn't use the typestate pattern to avoid this issue? In theory it should not make a big performance difference: correctness is validated by the compiler, memory footprint should be the same and the check at runtime should be very cheap thanks to the branch predictor.

I'm implementing a socket library, and I'm tempted to use the typestate pattern (Socket<State> with possible states being Uninitialized, Open, Connecting, Receiving and Closed), but the fact that the std library doesn't use this pattern makes me dubious.

So why is it so? Are there any unintended side effects with the typestate pattern? Should I use it anyway in my libraries?