public void Reset() { _messageBuffer = null; _headerBytes = 0; _packageLength = 0; }
/// <summary> /// Parses a stream chunking based on length-prefixed framing. Calls are re-entrant and hold state internally. /// </summary> /// <param name="bytes">A byte array of data to append</param> private void Parse(ArraySegment<byte> bytes) { byte[] data = bytes.Array; for (int i = bytes.Offset; i < bytes.Offset + bytes.Count; ) { if (_headerBytes < PrefixLength) { _packageLength |= (data[i] << (_headerBytes * 8)); // little-endian order ++_headerBytes; i += 1; if (_headerBytes == PrefixLength) { if (_packageLength <= 0 || _packageLength > _maxPackageSize) { Log.Error("FRAMING ERROR! Data:\n{0}", Utils.Helper.FormatBinaryDump(bytes)); throw new PackageFramingException(string.Format("Package size is out of bounds: {0} (max: {1}).", _packageLength, _maxPackageSize)); } _messageBuffer = new BufferPool(_bufferManager); } } else { int copyCnt = Math.Min(bytes.Count + bytes.Offset - i, _packageLength - _messageBuffer.Length); _messageBuffer.Append(bytes.Array, i, copyCnt); i += copyCnt; if (_messageBuffer.Length == _packageLength) { if (_receivedHandler != null) _receivedHandler(_messageBuffer); _messageBuffer = null; _headerBytes = 0; _packageLength = 0; } } } }
/// <summary> /// Initializes a new instance of the <see cref="BufferPoolStream"/> class. /// </summary> /// <param name="bufferPool">The buffer pool used as underlying storage.</param> public BufferPoolStream(BufferPool bufferPool) { if (bufferPool == null) throw new ArgumentNullException("bufferPool"); _bufferPool = bufferPool; }