codingstatemachine.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. ######################## BEGIN LICENSE BLOCK ########################
  2. # The Original Code is mozilla.org code.
  3. #
  4. # The Initial Developer of the Original Code is
  5. # Netscape Communications Corporation.
  6. # Portions created by the Initial Developer are Copyright (C) 1998
  7. # the Initial Developer. All Rights Reserved.
  8. #
  9. # Contributor(s):
  10. # Mark Pilgrim - port to Python
  11. #
  12. # This library is free software; you can redistribute it and/or
  13. # modify it under the terms of the GNU Lesser General Public
  14. # License as published by the Free Software Foundation; either
  15. # version 2.1 of the License, or (at your option) any later version.
  16. #
  17. # This library is distributed in the hope that it will be useful,
  18. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  20. # Lesser General Public License for more details.
  21. #
  22. # You should have received a copy of the GNU Lesser General Public
  23. # License along with this library; if not, write to the Free Software
  24. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  25. # 02110-1301 USA
  26. ######################### END LICENSE BLOCK #########################
  27. from .constants import eStart
  28. from .compat import wrap_ord
  29. class CodingStateMachine:
  30. def __init__(self, sm):
  31. self._mModel = sm
  32. self._mCurrentBytePos = 0
  33. self._mCurrentCharLen = 0
  34. self.reset()
  35. def reset(self):
  36. self._mCurrentState = eStart
  37. def next_state(self, c):
  38. # for each byte we get its class
  39. # if it is first byte, we also get byte length
  40. # PY3K: aBuf is a byte stream, so c is an int, not a byte
  41. byteCls = self._mModel['classTable'][wrap_ord(c)]
  42. if self._mCurrentState == eStart:
  43. self._mCurrentBytePos = 0
  44. self._mCurrentCharLen = self._mModel['charLenTable'][byteCls]
  45. # from byte's class and stateTable, we get its next state
  46. curr_state = (self._mCurrentState * self._mModel['classFactor']
  47. + byteCls)
  48. self._mCurrentState = self._mModel['stateTable'][curr_state]
  49. self._mCurrentBytePos += 1
  50. return self._mCurrentState
  51. def get_current_charlen(self):
  52. return self._mCurrentCharLen
  53. def get_coding_state_machine(self):
  54. return self._mModel['name']