public void Flush()
{
/*
If we found a newline, send anything up until that.
If we're forcing a send, send all we got
If we found no newline in the stream, the message is malformed according to RFC2821 (max 1000 chars per line).
*/
byte[] bytesToScanForNewline;
if (_buffer.Length > MaxLineLength && !_transmissionEnded)
{
bytesToScanForNewline = new byte[MaxLineLength];
_buffer.Seek(-MaxLineLength, SeekOrigin.End);
_buffer.Read(bytesToScanForNewline, (int) (_buffer.Length - MaxLineLength), MaxLineLength);
}
else
{
bytesToScanForNewline = new byte[_buffer.Length];
_buffer.Seek(0, SeekOrigin.Begin);
_buffer.Read(bytesToScanForNewline, 0, (int) _buffer.Length);
}
int flushPosition = (int) _buffer.Length;
for (int i = bytesToScanForNewline.Length - 1; i >= 0; i--)
{
if (bytesToScanForNewline[i] == '\n')
{
// Send all up until this position.
int skippedBytes = bytesToScanForNewline.Length - i;
// include the newline character in the flushed data
flushPosition = (int) _buffer.Length - skippedBytes + 1;
break;
}
}
_buffer.Seek(0, SeekOrigin.Begin);
int flushPositionRemovingTransmissionEndIndicator = _transmissionEnded ? flushPosition - 3 : flushPosition;
TransmissionPeriodRemover.Process(_buffer, _target, flushPositionRemovingTransmissionEndIndicator);
var oldBufferData = _buffer.ToArray();
int remainingBytes = oldBufferData.Length - flushPosition;
_buffer.Dispose();
_buffer = new MemoryStream();
_buffer.Write(oldBufferData, flushPosition, remainingBytes);
if (_transmissionEnded)
{
_target.Seek(0, SeekOrigin.Begin);
}
}
}