stateful.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # -*- test-case-name: twisted.test.test_stateful -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. from io import BytesIO
  5. from twisted.internet import protocol
  6. class StatefulProtocol(protocol.Protocol):
  7. """A Protocol that stores state for you.
  8. state is a pair (function, num_bytes). When num_bytes bytes of data arrives
  9. from the network, function is called. It is expected to return the next
  10. state or None to keep same state. Initial state is returned by
  11. getInitialState (override it).
  12. """
  13. _sful_data = None, None, 0
  14. def makeConnection(self, transport):
  15. protocol.Protocol.makeConnection(self, transport)
  16. self._sful_data = self.getInitialState(), BytesIO(), 0
  17. def getInitialState(self):
  18. raise NotImplementedError
  19. def dataReceived(self, data):
  20. state, buffer, offset = self._sful_data
  21. buffer.seek(0, 2)
  22. buffer.write(data)
  23. blen = buffer.tell() # how many bytes total is in the buffer
  24. buffer.seek(offset)
  25. while blen - offset >= state[1]:
  26. d = buffer.read(state[1])
  27. offset += state[1]
  28. next = state[0](d)
  29. if (
  30. self.transport.disconnecting
  31. ): # XXX: argh stupid hack borrowed right from LineReceiver
  32. return # dataReceived won't be called again, so who cares about consistent state
  33. if next:
  34. state = next
  35. if offset != 0:
  36. b = buffer.read()
  37. buffer.seek(0)
  38. buffer.truncate()
  39. buffer.write(b)
  40. offset = 0
  41. self._sful_data = state, buffer, offset