Coder.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #region Using
  2. using System.IO;
  3. #endregion
  4. namespace SharpCompress.Compressors.PPMd.I1
  5. {
  6. /// <summary>
  7. /// A simple range coder.
  8. /// </summary>
  9. /// <remarks>
  10. /// Note that in most cases fields are used rather than properties for performance reasons (for example,
  11. /// <see cref="_scale"/> is a field rather than a property).
  12. /// </remarks>
  13. internal class Coder
  14. {
  15. private const uint RANGE_TOP = 1 << 24;
  16. private const uint RANGE_BOTTOM = 1 << 15;
  17. private uint _low;
  18. private uint _code;
  19. private uint _range;
  20. public uint _lowCount;
  21. public uint _highCount;
  22. public uint _scale;
  23. public void RangeEncoderInitialize()
  24. {
  25. _low = 0;
  26. _range = uint.MaxValue;
  27. }
  28. public void RangeEncoderNormalize(Stream stream)
  29. {
  30. while ((_low ^ (_low + _range)) < RANGE_TOP ||
  31. _range < RANGE_BOTTOM && ((_range = (uint)-_low & (RANGE_BOTTOM - 1)) != 0 || true))
  32. {
  33. stream.WriteByte((byte)(_low >> 24));
  34. _range <<= 8;
  35. _low <<= 8;
  36. }
  37. }
  38. public void RangeEncodeSymbol()
  39. {
  40. _low += _lowCount * (_range /= _scale);
  41. _range *= _highCount - _lowCount;
  42. }
  43. public void RangeShiftEncodeSymbol(int rangeShift)
  44. {
  45. _low += _lowCount * (_range >>= rangeShift);
  46. _range *= _highCount - _lowCount;
  47. }
  48. public void RangeEncoderFlush(Stream stream)
  49. {
  50. for (uint index = 0; index < 4; index++)
  51. {
  52. stream.WriteByte((byte)(_low >> 24));
  53. _low <<= 8;
  54. }
  55. }
  56. public void RangeDecoderInitialize(Stream stream)
  57. {
  58. _low = 0;
  59. _code = 0;
  60. _range = uint.MaxValue;
  61. for (uint index = 0; index < 4; index++)
  62. {
  63. _code = (_code << 8) | (byte)stream.ReadByte();
  64. }
  65. }
  66. public void RangeDecoderNormalize(Stream stream)
  67. {
  68. while ((_low ^ (_low + _range)) < RANGE_TOP ||
  69. _range < RANGE_BOTTOM && ((_range = (uint)-_low & (RANGE_BOTTOM - 1)) != 0 || true))
  70. {
  71. _code = (_code << 8) | (byte)stream.ReadByte();
  72. _range <<= 8;
  73. _low <<= 8;
  74. }
  75. }
  76. public uint RangeGetCurrentCount()
  77. {
  78. return (_code - _low) / (_range /= _scale);
  79. }
  80. public uint RangeGetCurrentShiftCount(int rangeShift)
  81. {
  82. return (_code - _low) / (_range >>= rangeShift);
  83. }
  84. public void RangeRemoveSubrange()
  85. {
  86. _low += _range * _lowCount;
  87. _range *= _highCount - _lowCount;
  88. }
  89. }
  90. }