Example #1
0
        private static bool TryFetchPacket(RingQueue <IncomingPacket> packetQueue, out IncomingPacket packet)
        {
            if (packetQueue.Count <= 0)
            {
                packet = null; return(false);
            }

            int  take     = 0;
            int  takeLen  = 0;
            bool hasStart = false;
            bool hasEnd   = false;

            for (int i = 0; i < packetQueue.Count; i++)
            {
                IncomingPacket peekPacket;
                if (packetQueue.TryPeekStart(i, out peekPacket))
                {
                    take++;
                    takeLen += peekPacket.Size;
                    if (peekPacket.FragmentedFlag)
                    {
                        if (!hasStart)
                        {
                            hasStart = true;
                        }
                        else if (!hasEnd)
                        {
                            hasEnd = true; break;
                        }
                    }
                    else
                    {
                        if (!hasStart)
                        {
                            hasStart = true; hasEnd = true; break;
                        }
                    }
                }
                else
                {
                    break;
                }
            }

            if (!hasStart || !hasEnd)
            {
                packet = null; return(false);
            }

            // GET
            if (!packetQueue.TryDequeue(out packet))
            {
                throw new InvalidOperationException("Packet in queue got missing (?)");
            }

            if (take > 1)             // MERGE
            {
                var preFinalArray = new byte[takeLen];

                // for loop at 0th element
                int curCopyPos = packet.Size;
                Array.Copy(packet.Data, 0, preFinalArray, 0, packet.Size);

                for (int i = 1; i < take; i++)
                {
                    IncomingPacket nextPacket = null;
                    if (!packetQueue.TryDequeue(out nextPacket))
                    {
                        throw new InvalidOperationException("Packet in queue got missing (?)");
                    }

                    Array.Copy(nextPacket.Data, 0, preFinalArray, curCopyPos, nextPacket.Size);
                    curCopyPos += nextPacket.Size;
                }
                packet.Data = preFinalArray;
            }

            // DECOMPRESS
            if (packet.CompressedFlag)
            {
                if (QuickLZ.SizeDecompressed(packet.Data) > MaxDecompressedSize)
                {
                    throw new InvalidOperationException("Compressed packet is too large");
                }
                packet.Data = QuickLZ.Decompress(packet.Data);
            }
            return(true);
        }