< Summary

Line coverage
81%
Covered lines: 101
Uncovered lines: 23
Coverable lines: 124
Total lines: 223
Line coverage: 81.4%
Branch coverage
61%
Covered branches: 22
Total branches: 36
Branch coverage: 61.1%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Cyclomatic complexity NPath complexity Sequence coverage
.ctor(...)100%11100%
Dispose()100%22100%
ReleaseBuffer()100%22100%
Deflate(...)50%2268.18%
DeflatePrivate(...)71.42%141470%
UnsafeDeflate(...)50%44100%
UnsafeFlush(...)50%44100%
Deflate(...)37.5%8860%
CreateDeflater()100%1170%

File(s)

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/Compression/WebSocketDeflater.cs

#LineLine coverage
 1// Licensed to the .NET Foundation under one or more agreements.
 2// The .NET Foundation licenses this file to you under the MIT license.
 3
 4using System.Buffers;
 5using System.Diagnostics;
 6using static System.IO.Compression.ZLibNative;
 7
 8namespace System.Net.WebSockets.Compression
 9{
 10    /// <summary>
 11    /// Provides a wrapper around the ZLib compression API.
 12    /// </summary>
 13    internal sealed class WebSocketDeflater : IDisposable
 14    {
 15        private readonly int _windowBits;
 16        private ZLibStreamHandle? _stream;
 17        private readonly bool _persisted;
 18
 19        private byte[]? _buffer;
 20
 202521        internal WebSocketDeflater(int windowBits, bool persisted)
 202522        {
 202523            _windowBits = -windowBits; // Negative for raw deflate
 202524            _persisted = persisted;
 202525        }
 26
 27        public void Dispose()
 202528        {
 202529            _stream?.Dispose();
 202530        }
 31
 32        public void ReleaseBuffer()
 303833        {
 303834            if (_buffer is byte[] toReturn)
 3735            {
 3736                _buffer = null;
 3737                ArrayPool<byte>.Shared.Return(toReturn);
 3738            }
 303839        }
 40
 41        public ReadOnlySpan<byte> Deflate(ReadOnlySpan<byte> payload, bool endOfMessage)
 3742        {
 3743            Debug.Assert(_buffer is null, "Invalid state, ReleaseBuffer not called.");
 44
 45            // For small payloads there might actually be overhead in the compression and the resulting
 46            // output might be larger than the payload. This is why we rent at least 4KB initially.
 47            const int MinInitialBufferLength = 4 * 1024;
 48
 3749            _buffer = ArrayPool<byte>.Shared.Rent(Math.Max(payload.Length, MinInitialBufferLength));
 3750            int position = 0;
 51
 3752            while (true)
 3753            {
 3754                DeflatePrivate(payload, _buffer.AsSpan(position), endOfMessage,
 3755                    out int consumed, out int written, out bool needsMoreOutput);
 3756                position += written;
 57
 3758                if (!needsMoreOutput)
 3759                {
 3760                    Debug.Assert(consumed == payload.Length);
 3761                    break;
 62                }
 63
 064                payload = payload.Slice(consumed);
 65
 66                // Rent a 30% bigger buffer
 067                byte[] newBuffer = ArrayPool<byte>.Shared.Rent((int)(_buffer.Length * 1.3));
 068                _buffer.AsSpan(0, position).CopyTo(newBuffer);
 69
 070                byte[] toReturn = _buffer;
 071                _buffer = newBuffer;
 72
 073                ArrayPool<byte>.Shared.Return(toReturn);
 074            }
 75
 3776            return new ReadOnlySpan<byte>(_buffer, 0, position);
 3777        }
 78
 79        private void DeflatePrivate(ReadOnlySpan<byte> payload, Span<byte> output, bool endOfMessage,
 80            out int consumed, out int written, out bool needsMoreOutput)
 3781        {
 3782            _stream ??= CreateDeflater();
 83
 3784            if (payload.Length == 0)
 1885            {
 1886                consumed = 0;
 1887                written = 0;
 1888            }
 89            else
 1990            {
 1991                UnsafeDeflate(payload, output, out consumed, out written, out needsMoreOutput);
 92
 1993                if (needsMoreOutput)
 094                {
 095                    Debug.Assert(written == output.Length);
 096                    return;
 97                }
 1998            }
 99
 37100            written += UnsafeFlush(output.Slice(written), out needsMoreOutput);
 101
 37102            if (needsMoreOutput)
 0103            {
 0104                return;
 105            }
 37106            Debug.Assert(output.Slice(written - WebSocketInflater.FlushMarkerLength, WebSocketInflater.FlushMarkerLength
 37107                               .EndsWith(WebSocketInflater.FlushMarker), "The deflated block must always end with a flus
 108
 37109            if (endOfMessage)
 3110            {
 111                // As per RFC we need to remove the flush markers
 3112                written -= WebSocketInflater.FlushMarkerLength;
 3113            }
 114
 37115            if (endOfMessage && !_persisted)
 0116            {
 0117                _stream.Dispose();
 0118                _stream = null;
 0119            }
 37120        }
 121
 122        private unsafe void UnsafeDeflate(ReadOnlySpan<byte> input, Span<byte> output, out int consumed, out int written
 19123        {
 19124            Debug.Assert(_stream is not null);
 125
 19126            fixed (byte* fixedInput = input)
 19127            fixed (byte* fixedOutput = output)
 19128            {
 19129                _stream.NextIn = (IntPtr)fixedInput;
 19130                _stream.AvailIn = (uint)input.Length;
 131
 19132                _stream.NextOut = (IntPtr)fixedOutput;
 19133                _stream.AvailOut = (uint)output.Length;
 134
 135                // The flush is set to Z_NO_FLUSH, which allows deflate to decide
 136                // how much data to accumulate before producing output,
 137                // in order to maximize compression.
 19138                var errorCode = Deflate(_stream, FlushCode.NoFlush);
 139
 19140                consumed = input.Length - (int)_stream.AvailIn;
 19141                written = output.Length - (int)_stream.AvailOut;
 142
 143                // It is important here to also check that we haven't
 144                // exhausted the output buffer because after deflating we're
 145                // always going to issue a flush and a flush with empty output
 146                // is going to throw.
 19147                needsMoreBuffer = errorCode == ErrorCode.BufError
 19148                    || _stream.AvailIn > 0
 19149                    || written == output.Length;
 19150            }
 19151        }
 152
 153        private unsafe int UnsafeFlush(Span<byte> output, out bool needsMoreBuffer)
 37154        {
 37155            Debug.Assert(_stream is not null);
 37156            Debug.Assert(_stream.AvailIn == 0);
 37157            Debug.Assert(output.Length > 0);
 158
 37159            fixed (byte* fixedOutput = output)
 37160            {
 37161                _stream.NextIn = IntPtr.Zero;
 37162                _stream.AvailIn = 0;
 163
 37164                _stream.NextOut = (IntPtr)fixedOutput;
 37165                _stream.AvailOut = (uint)output.Length;
 166
 167                // We need to use Z_BLOCK_FLUSH to instruct the zlib to flush all outstanding
 168                // data but also not to emit a deflate block boundary. After we know that there is no
 169                // more data, we can safely proceed to instruct the library to emit the boundary markers.
 37170                ErrorCode errorCode = Deflate(_stream, FlushCode.Block);
 37171                Debug.Assert(errorCode is ErrorCode.Ok or ErrorCode.BufError);
 172
 173                // We need at least 6 bytes to guarantee that we can emit a deflate block boundary.
 37174                needsMoreBuffer = _stream.AvailOut < 6;
 175
 37176                if (!needsMoreBuffer)
 37177                {
 178                    // The flush is set to Z_SYNC_FLUSH, all pending output is flushed
 179                    // to the output buffer and the output is aligned on a byte boundary,
 180                    // so that the decompressor can get all input data available so far.
 181                    // This completes the current deflate block and follows it with an empty
 182                    // stored block that is three bits plus filler bits to the next byte,
 183                    // followed by four bytes (00 00 ff ff).
 37184                    errorCode = Deflate(_stream, FlushCode.SyncFlush);
 37185                    Debug.Assert(errorCode == ErrorCode.Ok);
 37186                }
 187
 37188                return output.Length - (int)_stream.AvailOut;
 189            }
 37190        }
 191
 192        private static ErrorCode Deflate(ZLibStreamHandle stream, FlushCode flushCode)
 93193        {
 93194            ErrorCode errorCode = stream.Deflate(flushCode);
 195
 93196            if (errorCode is ErrorCode.Ok or ErrorCode.StreamEnd or ErrorCode.BufError)
 93197            {
 93198                return errorCode;
 199            }
 200
 0201            string message = errorCode == ErrorCode.StreamError
 0202                ? SR.ZLibErrorInconsistentStream
 0203                : SR.Format(SR.ZLibErrorUnexpected, (int)errorCode);
 0204            throw new WebSocketException(message);
 93205        }
 206
 207        private ZLibStreamHandle CreateDeflater()
 37208        {
 209            try
 37210            {
 37211                return ZLibStreamHandle.CreateForDeflate(level: CompressionLevel.DefaultCompression,
 37212                    windowBits: _windowBits,
 37213                    memLevel: Deflate_DefaultMemLevel,
 37214                    strategy: CompressionStrategy.DefaultStrategy);
 215            }
 0216            catch (Exception ex)
 0217            {
 0218                throw new WebSocketException(ex.Message, ex.InnerException);
 219            }
 37220        }
 221    }
 222}
 223