System.IO.BinaryReader.InternalReadChars C# (CSharp) Method

InternalReadChars() private method

private InternalReadChars ( char buffer, int index, int count ) : int
buffer char
index int
count int
return int
        private int InternalReadChars(char[] buffer, int index, int count)
        {
            Debug.Assert(buffer != null);
            Debug.Assert(index >= 0 && count >= 0);
            Debug.Assert(_stream != null);

            int numBytes = 0;
            int charsRemaining = count;

            if (_charBytes == null)
            {
                _charBytes = new byte[MaxCharBytesSize];
            }

            while (charsRemaining > 0)
            {
                int charsRead = 0;
                // We really want to know what the minimum number of bytes per char
                // is for our encoding.  Otherwise for UnicodeEncoding we'd have to
                // do ~1+log(n) reads to read n characters.
                numBytes = charsRemaining;

                if (_2BytesPerChar)
                {
                    numBytes <<= 1;
                }
                if (numBytes > MaxCharBytesSize)
                {
                    numBytes = MaxCharBytesSize;
                }

                int position = 0;
                byte[] byteBuffer = null;
                if (_isMemoryStream)
                {
                    MemoryStream mStream = _stream as MemoryStream;
                    Debug.Assert(mStream != null, "_stream as MemoryStream != null");

                    position = mStream.InternalGetPosition();
                    numBytes = mStream.InternalEmulateRead(numBytes);
                    byteBuffer = mStream.InternalGetBuffer();
                }
                else
                {
                    numBytes = _stream.Read(_charBytes, 0, numBytes);
                    byteBuffer = _charBytes;
                }

                if (numBytes == 0)
                {
                    return (count - charsRemaining);
                }

                Debug.Assert(byteBuffer != null, "expected byteBuffer to be non-null");
                charsRead = _decoder.GetChars(byteBuffer, position, numBytes, buffer, index, flush: false);

                charsRemaining -= charsRead;
                index += charsRead;
            }

            // this should never fail
            Debug.Assert(charsRemaining >= 0, "We read too many characters.");

            // we may have read fewer than the number of characters requested if end of stream reached 
            // or if the encoding makes the char count too big for the buffer (e.g. fallback sequence)
            return (count - charsRemaining);
        }