1 // InBuffer.cpp
2 
3 #include "StdAfx.h"
4 
5 #include "../../../C/Alloc.h"
6 
7 #include "InBuffer.h"
8 
CInBuffer()9 CInBuffer::CInBuffer():
10   _buffer(0),
11   _bufferLimit(0),
12   _bufferBase(0),
13   _stream(0),
14   _bufferSize(0)
15 {}
16 
Create(UInt32 bufferSize)17 bool CInBuffer::Create(UInt32 bufferSize)
18 {
19   const UInt32 kMinBlockSize = 1;
20   if (bufferSize < kMinBlockSize)
21     bufferSize = kMinBlockSize;
22   if (_bufferBase != 0 && _bufferSize == bufferSize)
23     return true;
24   Free();
25   _bufferSize = bufferSize;
26   _bufferBase = (Byte *)::MidAlloc(bufferSize);
27   return (_bufferBase != 0);
28 }
29 
Free()30 void CInBuffer::Free()
31 {
32   ::MidFree(_bufferBase);
33   _bufferBase = 0;
34 }
35 
SetStream(ISequentialInStream * stream)36 void CInBuffer::SetStream(ISequentialInStream *stream)
37 {
38   _stream = stream;
39 }
40 
Init()41 void CInBuffer::Init()
42 {
43   _processedSize = 0;
44   _buffer = _bufferBase;
45   _bufferLimit = _buffer;
46   _wasFinished = false;
47   #ifdef _NO_EXCEPTIONS
48   ErrorCode = S_OK;
49   #endif
50 }
51 
ReadBlock()52 bool CInBuffer::ReadBlock()
53 {
54   #ifdef _NO_EXCEPTIONS
55   if (ErrorCode != S_OK)
56     return false;
57   #endif
58   if (_wasFinished)
59     return false;
60   _processedSize += (_buffer - _bufferBase);
61   UInt32 numProcessedBytes;
62   HRESULT result = _stream->Read(_bufferBase, _bufferSize, &numProcessedBytes);
63   #ifdef _NO_EXCEPTIONS
64   ErrorCode = result;
65   #else
66   if (result != S_OK)
67     throw CInBufferException(result);
68   #endif
69   _buffer = _bufferBase;
70   _bufferLimit = _buffer + numProcessedBytes;
71   _wasFinished = (numProcessedBytes == 0);
72   return (!_wasFinished);
73 }
74 
ReadBlock2()75 Byte CInBuffer::ReadBlock2()
76 {
77   if (!ReadBlock())
78   {
79     _processedSize++;
80     return 0xFF;
81   }
82   return *_buffer++;
83 }
84