Imported Upstream version 9.20
[platform/upstream/7zip.git] / CPP / 7zip / Compress / BitmEncoder.h
1 // BitmEncoder.h -- the Most Significant Bit of byte is First\r
2 \r
3 #ifndef __BITM_ENCODER_H\r
4 #define __BITM_ENCODER_H\r
5 \r
6 #include "../IStream.h"\r
7 \r
8 template<class TOutByte>\r
9 class CBitmEncoder\r
10 {\r
11   TOutByte m_Stream;\r
12   unsigned m_BitPos;\r
13   Byte m_CurByte;\r
14 public:\r
15   bool Create(UInt32 bufferSize) { return m_Stream.Create(bufferSize); }\r
16   void SetStream(ISequentialOutStream *outStream) { m_Stream.SetStream(outStream);}\r
17   void ReleaseStream() { m_Stream.ReleaseStream(); }\r
18   UInt64 GetProcessedSize() const { return m_Stream.GetProcessedSize() + (8 - m_BitPos + 7) / 8; }\r
19   void Init()\r
20   {\r
21     m_Stream.Init();\r
22     m_BitPos = 8;\r
23     m_CurByte = 0;\r
24   }\r
25   HRESULT Flush()\r
26   {\r
27     if (m_BitPos < 8)\r
28       WriteBits(0, m_BitPos);\r
29     return m_Stream.Flush();\r
30   }\r
31   void WriteBits(UInt32 value, unsigned numBits)\r
32   {\r
33     while (numBits > 0)\r
34     {\r
35       if (numBits < m_BitPos)\r
36       {\r
37         m_CurByte |= ((Byte)value << (m_BitPos -= numBits));\r
38         return;\r
39       }\r
40       numBits -= m_BitPos;\r
41       UInt32 newBits = (value >> numBits);\r
42       value -= (newBits << numBits);\r
43       m_Stream.WriteByte((Byte)(m_CurByte | newBits));\r
44       m_BitPos = 8;\r
45       m_CurByte = 0;\r
46     }\r
47   }\r
48 };\r
49 \r
50 #endif\r