MailKit.Net.Imap.ImapStream.ReadAhead C# (CSharp) Method

ReadAhead() private method

private ReadAhead ( int atleast, CancellationToken cancellationToken ) : int
atleast int
cancellationToken System.Threading.CancellationToken
return int
		unsafe int ReadAhead (int atleast, CancellationToken cancellationToken)
		{
			int left = inputEnd - inputIndex;

			if (left >= atleast)
				return left;

			int start = inputStart;
			int end = inputEnd;
			int nread;

			if (left > 0) {
				int index = inputIndex;

				// attempt to align the end of the remaining input with ReadAheadSize
				if (index >= start) {
					start -= Math.Min (ReadAheadSize, left);
					Buffer.BlockCopy (input, index, input, start, left);
					index = start;
					start += left;
				} else if (index > 0) {
					int shift = Math.Min (index, end - start);
					Buffer.BlockCopy (input, index, input, index - shift, left);
					index -= shift;
					start = index + left;
				} else {
					// we can't shift...
					start = end;
				}

				inputIndex = index;
				inputEnd = start;
			} else {
				inputIndex = start;
				inputEnd = start;
			}

			end = input.Length - PadSize;

			try {
#if !NETFX_CORE
				bool buffered = !(Stream is NetworkStream);
#else
				bool buffered = true;
#endif

				if (buffered) {
					cancellationToken.ThrowIfCancellationRequested ();

					nread = Stream.Read (input, start, end - start);
				} else {
					Poll (SelectMode.SelectRead, cancellationToken);

					nread = Stream.Read (input, start, end - start);
				}

				if (nread > 0) {
					logger.LogServer (input, start, nread);
					inputEnd += nread;
				} else {
					throw new ImapProtocolException ("The IMAP server has unexpectedly disconnected.");
				}

				if (buffered)
					cancellationToken.ThrowIfCancellationRequested ();
			} catch {
				IsConnected = false;
				throw;
			}

			return inputEnd - inputIndex;
		}