public MqttPacketBuffer Encode(MqttPacket packet) { if (packet == null) { throw new ArgumentNullException(nameof(packet)); } // Leave enough head space for max header size (fixed + 4 variable remaining length = 5 bytes) _bufferWriter.Reset(5); _bufferWriter.Seek(5); var fixedHeader = EncodePacket(packet, _bufferWriter); var remainingLength = (uint)(_bufferWriter.Length - 5); var publishPacket = packet as MqttPublishPacket; if (publishPacket?.Payload != null) { remainingLength += (uint)publishPacket.Payload.Length; } var remainingLengthSize = MqttBufferWriter.GetLengthOfVariableInteger(remainingLength); var headerSize = FixedHeaderSize + remainingLengthSize; var headerOffset = 5 - headerSize; // Position cursor on correct offset on beginning of array (has leading 0x0) _bufferWriter.Seek(headerOffset); _bufferWriter.WriteByte(fixedHeader); _bufferWriter.WriteVariableByteInteger(remainingLength); var buffer = _bufferWriter.GetBuffer(); var firstSegment = new ArraySegment <byte>(buffer, headerOffset, _bufferWriter.Length - headerOffset); if (publishPacket?.Payload != null) { var payloadSegment = new ArraySegment <byte>(publishPacket.Payload, 0, publishPacket.Payload.Length); return(new MqttPacketBuffer(firstSegment, payloadSegment)); } return(new MqttPacketBuffer(firstSegment)); }