Пример #1
0
        public static async Task <UncompressedPacket> DeserializeAsync(Stream stream, IBufferPoolScope <byte> bufferPool, UncompressedPacket packet = null)
        {
            packet = packet ?? new UncompressedPacket();
            int packetIdLen;

            using (var br = new BinaryReader(stream, Encoding.UTF8, true))
            {
                packet.Length   = br.ReadAsVarInt(out _);
                packet.PacketId = br.ReadAsVarInt(out packetIdLen);
            }

            packet.Data = bufferPool.Rent((int)(packet.Length - packetIdLen));
            await stream.ReadExactAsync(packet.Data.Array, packet.Data.Offset, packet.Data.Count);

            return(packet);
        }
Пример #2
0
        public static UncompressedPacket Decompress(CompressedPacket packet, IBufferPoolScope <byte> bufferPool, uint threshold, UncompressedPacket targetPacket = null)
        {
            if (packet.DataLength != 0 && packet.DataLength < threshold)
            {
                throw new InvalidDataException("Uncompressed data length is lower than threshold.");
            }
            bool useCompression = packet.DataLength != 0;
            var  dataLength     = useCompression ? packet.DataLength : (uint)packet.CompressedData.Length;

            targetPacket = targetPacket ?? new UncompressedPacket();
            using (var stream = new MemoryStream(packet.CompressedData))
                using (var br = new BinaryReader(useCompression ? (Stream) new ZlibStream(stream, CompressionMode.Decompress, CompressionLevel.BestSpeed) : stream))
                {
                    targetPacket.PacketId = br.ReadAsVarInt(out var packetIdLen);

                    targetPacket.Data = bufferPool.Rent((int)(dataLength - packetIdLen));
                    br.Read(targetPacket.Data.Array, targetPacket.Data.Offset, targetPacket.Data.Count);
                }

            targetPacket.Length = packet.DataLength;
            return(targetPacket);
        }