private void InitStreamInput(Uri baseUri, string baseUriStr, Stream stream, byte[] bytes, int byteCount, Encoding encoding)
{
Debug.Assert(_ps.charPos == 0 && _ps.charsUsed == 0 && _ps.textReader == null);
Debug.Assert(baseUriStr != null);
Debug.Assert(baseUri == null || (baseUri.ToString().Equals(baseUriStr)));
_ps.stream = stream;
_ps.baseUri = baseUri;
_ps.baseUriStr = baseUriStr;
// take over the byte buffer allocated in XmlReader.Create, if available
int bufferSize;
if (bytes != null)
{
_ps.bytes = bytes;
_ps.bytesUsed = byteCount;
bufferSize = _ps.bytes.Length;
}
else
{
// allocate the byte buffer
if (_laterInitParam != null && _laterInitParam.useAsync)
{
bufferSize = AsyncBufferSize;
}
else
{
bufferSize = XmlReader.CalcBufferSize(stream);
}
if (_ps.bytes == null || _ps.bytes.Length < bufferSize)
{
_ps.bytes = new byte[bufferSize];
}
}
// allocate char buffer
if (_ps.chars == null || _ps.chars.Length < bufferSize + 1)
{
_ps.chars = new char[bufferSize + 1];
}
// make sure we have at least 4 bytes to detect the encoding (no preamble of System.Text supported encoding is longer than 4 bytes)
_ps.bytePos = 0;
while (_ps.bytesUsed < 4 && _ps.bytes.Length - _ps.bytesUsed > 0)
{
int read = stream.Read(_ps.bytes, _ps.bytesUsed, _ps.bytes.Length - _ps.bytesUsed);
if (read == 0)
{
_ps.isStreamEof = true;
break;
}
_ps.bytesUsed += read;
}
// detect & setup encoding
if (encoding == null)
{
encoding = DetectEncoding();
}
SetupEncoding(encoding);
// eat preamble
byte[] preamble = _ps.encoding.GetPreamble();
int preambleLen = preamble.Length;
int i;
for (i = 0; i < preambleLen && i < _ps.bytesUsed; i++)
{
if (_ps.bytes[i] != preamble[i])
{
break;
}
}
if (i == preambleLen)
{
_ps.bytePos = preambleLen;
}
_documentStartBytePos = _ps.bytePos;
_ps.eolNormalized = !_normalize;
// decode first characters
_ps.appendMode = true;
ReadData();
}