private void Init(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen)
{
_stream = stream;
_encoding = encoding;
_decoder = encoding.GetDecoder();
if (bufferSize < MinBufferSize)
{
bufferSize = MinBufferSize;
}
_byteBuffer = new byte[bufferSize];
_maxCharsPerBuffer = encoding.GetMaxCharCount(bufferSize);
_charBuffer = new char[_maxCharsPerBuffer];
_byteLen = 0;
_bytePos = 0;
_detectEncoding = detectEncodingFromByteOrderMarks;
// Encoding.GetPreamble() always allocates and returns a new byte[] array for
// encodings that have a preamble.
// We can avoid repeated allocations for the default and commonly used Encoding.UTF8
// encoding by using our own private cached instance of the UTF8 preamble.
// We specifically look for Encoding.UTF8 because we know it has a preamble,
// whereas other instances of UTF8Encoding may not have a preamble enabled, and
// there's no public way to tell if the preamble is enabled for an instance other
// than calling GetPreamble(), which we're trying to avoid.
// This means that other instances of UTF8Encoding are excluded from this optimization.
_preamble = object.ReferenceEquals(encoding, Encoding.UTF8) ?
(s_utf8Preamble ?? (s_utf8Preamble = encoding.GetPreamble())) :
encoding.GetPreamble();
_checkPreamble = (_preamble.Length > 0);
_isBlocked = false;
_closable = !leaveOpen;
}