public static ValueTask <Packet> ReadPacketAsync(BufferedByteReader bufferedByteReader, IByteHandler byteHandler, Func <int?> getNextSequenceNumber, ProtocolErrorBehavior protocolErrorBehavior, IOBehavior ioBehavior) { return(bufferedByteReader.ReadBytesAsync(byteHandler, 4, ioBehavior) .ContinueWith(headerBytes => { if (headerBytes.Count < 4) { return protocolErrorBehavior == ProtocolErrorBehavior.Throw ? ValueTaskExtensions.FromException <Packet>(new EndOfStreamException()) : default(ValueTask <Packet>); } var payloadLength = (int)SerializationUtility.ReadUInt32(headerBytes.Array, headerBytes.Offset, 3); int packetSequenceNumber = headerBytes.Array[headerBytes.Offset + 3]; var expectedSequenceNumber = getNextSequenceNumber() % 256; if (expectedSequenceNumber.HasValue && packetSequenceNumber != expectedSequenceNumber.Value) { if (protocolErrorBehavior == ProtocolErrorBehavior.Ignore) { return default(ValueTask <Packet>); } var exception = new InvalidOperationException("Packet received out-of-order. Expected {0}; got {1}.".FormatInvariant(expectedSequenceNumber.Value, packetSequenceNumber)); return ValueTaskExtensions.FromException <Packet>(exception); } return bufferedByteReader.ReadBytesAsync(byteHandler, payloadLength, ioBehavior) .ContinueWith(payloadBytes => { if (payloadBytes.Count < payloadLength) { return protocolErrorBehavior == ProtocolErrorBehavior.Throw ? ValueTaskExtensions.FromException <Packet>(new EndOfStreamException()) : default(ValueTask <Packet>); } return new ValueTask <Packet>(new Packet(packetSequenceNumber, payloadBytes)); }); })); }
public static ValueTask <ArraySegment <byte> > ReadPayloadAsync(BufferedByteReader bufferedByteReader, IByteHandler byteHandler, Func <int?> getNextSequenceNumber, ArraySegment <byte> previousPayloads, ProtocolErrorBehavior protocolErrorBehavior, IOBehavior ioBehavior) { return(ReadPacketAsync(bufferedByteReader, byteHandler, getNextSequenceNumber, protocolErrorBehavior, ioBehavior).ContinueWith(packet => ContinueRead(bufferedByteReader, byteHandler, getNextSequenceNumber, previousPayloads, packet, protocolErrorBehavior, ioBehavior))); }