Пример #1
0
        public readonly ReadOnlyMemory <byte> SerializeToFrames(ushort channelNumber, uint frameMax)
        {
            int maxBodyPayloadBytes = (int)(frameMax == 0 ? int.MaxValue : frameMax - Framing.BaseFrameSize);
            int size = Method.GetRequiredBufferSize() +
                       _header.GetRequiredPayloadBufferSize() +
                       Framing.BodySegment.FrameSize * (maxBodyPayloadBytes == int.MaxValue ? 1 : (_body.Length + maxBodyPayloadBytes - 1) / maxBodyPayloadBytes) + _body.Length
                       + Framing.Method.FrameSize + Framing.Header.FrameSize;

            // Will be returned by SocketFrameWriter.WriteLoop
            byte[] rentedArray = ArrayPool <byte> .Shared.Rent(size);

            int offset             = Framing.Method.WriteTo(rentedArray, channelNumber, Method);
            int remainingBodyBytes = _body.Length;

            offset += Framing.Header.WriteTo(rentedArray.AsSpan(offset), channelNumber, _header, remainingBodyBytes);
            if (remainingBodyBytes > 0)
            {
                ReadOnlySpan <byte> bodySpan = _body.Span;
                while (remainingBodyBytes > 0)
                {
                    int frameSize = remainingBodyBytes > maxBodyPayloadBytes ? maxBodyPayloadBytes : remainingBodyBytes;
                    offset             += Framing.BodySegment.WriteTo(rentedArray.AsSpan(offset), channelNumber, bodySpan.Slice(bodySpan.Length - remainingBodyBytes, frameSize));
                    remainingBodyBytes -= frameSize;
                }
            }

            System.Diagnostics.Debug.Assert(offset == size, $"Serialized to wrong size, expect {size}, offset {offset}");
            return(new ReadOnlyMemory <byte>(rentedArray, 0, size));
        }
Пример #2
0
        private int GetMaxSize(int maxPayloadBytes)
        {
            if (!Method.HasContent)
            {
                return(Framing.Method.FrameSize + Method.GetRequiredBufferSize());
            }

            return(Framing.Method.FrameSize + Method.GetRequiredBufferSize() +
                   Framing.Header.FrameSize + Header.GetRequiredPayloadBufferSize() +
                   Framing.BodySegment.FrameSize * GetBodyFrameCount(maxPayloadBytes) + Body.Length);
        }