1 // MSBFDecoder.h
2 // the Most Significant Bit of byte is First
3 
4 #ifndef __STREAM_MSBFDECODER_H
5 #define __STREAM_MSBFDECODER_H
6 
7 #include "../../Common/Types.h"
8 #include "../IStream.h"
9 
10 namespace NStream {
11 namespace NMSBF {
12 
13 const int kNumBigValueBits = 8 * 4;
14 const int kNumValueBytes = 3;
15 const int kNumValueBits = 8  * kNumValueBytes;
16 
17 const UInt32 kMask = (1 << kNumValueBits) - 1;
18 
19 template<class TInByte>
20 class CDecoder
21 {
22   UInt32 m_BitPos;
23   UInt32 m_Value;
24 public:
25   TInByte m_Stream;
Create(UInt32 bufferSize)26   bool Create(UInt32 bufferSize) { return m_Stream.Create(bufferSize); }
SetStream(ISequentialInStream * inStream)27   void SetStream(ISequentialInStream *inStream) { m_Stream.SetStream(inStream);}
ReleaseStream()28   void ReleaseStream() { m_Stream.ReleaseStream();}
29 
Init()30   void Init()
31   {
32     m_Stream.Init();
33     m_BitPos = kNumBigValueBits;
34     Normalize();
35   }
36 
GetProcessedSize()37   UInt64 GetProcessedSize() const
38     { return m_Stream.GetProcessedSize() - (kNumBigValueBits - m_BitPos) / 8; }
GetBitPosition()39   UInt32 GetBitPosition() const { return (m_BitPos & 7); }
40 
Normalize()41   void Normalize()
42   {
43     for (;m_BitPos >= 8; m_BitPos -= 8)
44       m_Value = (m_Value << 8) | m_Stream.ReadByte();
45   }
46 
GetValue(UInt32 numBits)47   UInt32 GetValue(UInt32 numBits) const
48   {
49     // return (m_Value << m_BitPos) >> (kNumBigValueBits - numBits);
50     return ((m_Value >> (8 - m_BitPos)) & kMask) >> (kNumValueBits - numBits);
51   }
52 
MovePos(UInt32 numBits)53   void MovePos(UInt32 numBits)
54   {
55     m_BitPos += numBits;
56     Normalize();
57   }
58 
ReadBits(UInt32 numBits)59   UInt32 ReadBits(UInt32 numBits)
60   {
61     UInt32 res = GetValue(numBits);
62     MovePos(numBits);
63     return res;
64   }
65 };
66 
67 }}
68 
69 #endif
70