xref: /aosp_15_r20/external/lzma/CPP/7zip/Compress/BitlEncoder.h (revision f6dc9357d832569d4d1f5d24eacdb3935a1ae8e6)
1 // BitlEncoder.h -- the Least Significant Bit of byte is First
2 
3 #ifndef ZIP7_INC_BITL_ENCODER_H
4 #define ZIP7_INC_BITL_ENCODER_H
5 
6 #include "../Common/OutBuffer.h"
7 
8 class CBitlEncoder
9 {
10   COutBuffer _stream;
11   unsigned _bitPos;
12   Byte _curByte;
13 public:
Create(UInt32 bufSize)14   bool Create(UInt32 bufSize) { return _stream.Create(bufSize); }
SetStream(ISequentialOutStream * outStream)15   void SetStream(ISequentialOutStream *outStream) { _stream.SetStream(outStream); }
16   // unsigned GetBitPosition() const { return (8 - _bitPos); }
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     FlushByte();
27     return _stream.Flush();
28   }
FlushByte()29   void FlushByte()
30   {
31     if (_bitPos < 8)
32       _stream.WriteByte(_curByte);
33     _bitPos = 8;
34     _curByte = 0;
35   }
WriteBits(UInt32 value,unsigned numBits)36   void WriteBits(UInt32 value, unsigned numBits)
37   {
38     while (numBits > 0)
39     {
40       if (numBits < _bitPos)
41       {
42         _curByte |= (Byte)((value & ((1 << numBits) - 1)) << (8 - _bitPos));
43         _bitPos -= numBits;
44         return;
45       }
46       numBits -= _bitPos;
47       _stream.WriteByte((Byte)(_curByte | (value << (8 - _bitPos))));
48       value >>= _bitPos;
49       _bitPos = 8;
50       _curByte = 0;
51     }
52   }
WriteByte(Byte b)53   void WriteByte(Byte b) { _stream.WriteByte(b);}
54 };
55 
56 #endif
57