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