1 // Stream/MSBFEncoder.h 2 3 #ifndef __STREAM_MSBFENCODER_H 4 #define __STREAM_MSBFENCODER_H 5 6 #include "Common/Defs.h" 7 #include "../IStream.h" 8 #include "OutBuffer.h" 9 10 namespace NStream { 11 namespace NMSBF { 12 13 template<class TOutByte> 14 class CEncoder 15 { 16 TOutByte m_Stream; 17 int m_BitPos; 18 Byte m_CurByte; 19 public: Create(UInt32 bufferSize)20 bool Create(UInt32 bufferSize) { return m_Stream.Create(bufferSize); } SetStream(ISequentialOutStream * outStream)21 void SetStream(ISequentialOutStream *outStream) { m_Stream.SetStream(outStream);} ReleaseStream()22 void ReleaseStream() { m_Stream.ReleaseStream(); } Init()23 void Init() 24 { 25 m_Stream.Init(); 26 m_BitPos = 8; 27 m_CurByte = 0; 28 } Flush()29 HRESULT Flush() 30 { 31 if(m_BitPos < 8) 32 WriteBits(0, m_BitPos); 33 return m_Stream.Flush(); 34 } 35 WriteBits(UInt32 value,int numBits)36 void WriteBits(UInt32 value, int numBits) 37 { 38 while(numBits > 0) 39 { 40 if (numBits < m_BitPos) 41 { 42 m_CurByte |= ((Byte)value << (m_BitPos -= numBits)); 43 return; 44 } 45 numBits -= m_BitPos; 46 UInt32 newBits = (value >> numBits); 47 value -= (newBits << numBits); 48 m_Stream.WriteByte(m_CurByte | (Byte)newBits); 49 m_BitPos = 8; 50 m_CurByte = 0; 51 } 52 } GetProcessedSize()53 UInt64 GetProcessedSize() const { 54 return m_Stream.GetProcessedSize() + (8 - m_BitPos + 7) / 8; } 55 }; 56 57 }} 58 59 #endif 60