< Summary

Information
Class: System.IO.Compression.Deflater
Assembly: System.IO.Compression
File(s): D:\runner\runtime\src\libraries\System.IO.Compression\src\System\IO\Compression\DeflateZLib\Deflater.cs
Line coverage
85%
Covered lines: 104
Uncovered lines: 18
Coverable lines: 122
Total lines: 234
Line coverage: 85.2%
Branch coverage
50%
Covered branches: 11
Total branches: 22
Branch coverage: 50%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Cyclomatic complexity NPath complexity Sequence coverage
.ctor(...)100%11100%
Finalize()100%110%
Dispose()100%11100%
Dispose(...)50%44100%
NeedsInput()100%11100%
SetInput(...)100%11100%
SetInput(...)100%11100%
GetDeflateOutput(...)100%22100%
ReadDeflateOutput(...)50%22100%
Finish(...)100%11100%
Flush(...)100%110%
UnsetInput()50%2266.66%
DeallocateInputBufferHandle(...)100%11100%
DeallocateInputBufferHandleCore(...)100%22100%
Deflate(...)25%8853.84%
CreateDeflater(...)50%22100%

File(s)

D:\runner\runtime\src\libraries\System.IO.Compression\src\System\IO\Compression\DeflateZLib\Deflater.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;
 6
 7using ZErrorCode = System.IO.Compression.ZLibNative.ErrorCode;
 8using ZFlushCode = System.IO.Compression.ZLibNative.FlushCode;
 9
 10namespace System.IO.Compression
 11{
 12    /// <summary>
 13    /// Provides a wrapper around the ZLib compression API.
 14    /// </summary>
 15    internal sealed class Deflater : IDisposable
 16    {
 17        private readonly ZLibNative.ZLibStreamHandle _zlibStream;
 18        private MemoryHandle _inputBufferHandle;
 19        private bool _isDisposed;
 20        private const int minWindowBits = -15;  // WindowBits must be between -8..-15 to write no header, 8..15 for a
 21        private const int maxWindowBits = 31;   // zlib header, or 24..31 for a GZip header
 22
 23        // Note, DeflateStream or the deflater do not try to be thread safe.
 24        // The lock is just used to make writing to unmanaged structures atomic to make sure
 25        // that they do not get inconsistent fields that may lead to an unmanaged memory violation.
 26        // To prevent *managed* buffer corruption or other weird behavior users need to synchronize
 27        // on the stream explicitly.
 109228        private object SyncLock => this;
 29
 18230        private Deflater(ZLibNative.ZLibStreamHandle zlibStream)
 18231        {
 18232            _zlibStream = zlibStream;
 18233        }
 34
 35        ~Deflater()
 036        {
 037            Dispose(false);
 038        }
 39
 40        public void Dispose()
 18241        {
 18242            Dispose(true);
 18243            GC.SuppressFinalize(this);
 18244        }
 45
 46        private void Dispose(bool disposing)
 18247        {
 18248            if (!_isDisposed)
 18249            {
 18250                if (disposing)
 18251                {
 18252                    _zlibStream.Dispose();
 18253                }
 54
 55                // Unpin the input buffer, but avoid modifying the ZLibStreamHandle (which may have been disposed of).
 18256                DeallocateInputBufferHandle(resetStreamHandle: false);
 18257                _isDisposed = true;
 18258            }
 18259        }
 60
 127461        public bool NeedsInput() => 0 == _zlibStream.AvailIn;
 62
 63        internal unsafe void SetInput(ReadOnlyMemory<byte> inputBuffer)
 9164        {
 9165            Debug.Assert(NeedsInput(), "We have something left in previous input!");
 9166            Debug.Assert(!inputBuffer.IsEmpty);
 67
 9168            lock (SyncLock)
 9169            {
 9170                _inputBufferHandle = inputBuffer.Pin();
 71
 9172                _zlibStream.NextIn = (IntPtr)_inputBufferHandle.Pointer;
 9173                _zlibStream.AvailIn = (uint)inputBuffer.Length;
 9174            }
 9175        }
 76
 77        internal unsafe void SetInput(byte* inputBufferPtr, int count)
 9178        {
 9179            Debug.Assert(NeedsInput(), "We have something left in previous input!");
 9180            Debug.Assert(inputBufferPtr != null);
 9181            Debug.Assert(count > 0);
 82
 9183            lock (SyncLock)
 9184            {
 9185                _zlibStream.NextIn = (IntPtr)inputBufferPtr;
 9186                _zlibStream.AvailIn = (uint)count;
 9187            }
 9188        }
 89
 90        internal int GetDeflateOutput(byte[] outputBuffer)
 18291        {
 18292            Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!");
 18293            Debug.Assert(!NeedsInput(), "GetDeflateOutput should only be called after providing input");
 94
 95            try
 18296            {
 97                int bytesRead;
 18298                ReadDeflateOutput(outputBuffer, ZFlushCode.NoFlush, out bytesRead);
 18299                return bytesRead;
 100            }
 101            finally
 182102            {
 103                // Before returning, make sure to release input buffer if necessary:
 182104                if (0 == _zlibStream.AvailIn)
 182105                {
 182106                    DeallocateInputBufferHandle(resetStreamHandle: true);
 182107                }
 182108            }
 182109        }
 110
 111        private unsafe ZErrorCode ReadDeflateOutput(byte[] outputBuffer, ZFlushCode flushCode, out int bytesRead)
 364112        {
 364113            Debug.Assert(outputBuffer?.Length > 0);
 114
 364115            lock (SyncLock)
 364116            {
 364117                fixed (byte* bufPtr = &outputBuffer[0])
 364118                {
 364119                    _zlibStream.NextOut = (IntPtr)bufPtr;
 364120                    _zlibStream.AvailOut = (uint)outputBuffer.Length;
 121
 364122                    ZErrorCode errC = Deflate(flushCode);
 364123                    bytesRead = outputBuffer.Length - (int)_zlibStream.AvailOut;
 124
 364125                    return errC;
 126                }
 127            }
 364128        }
 129
 130        internal bool Finish(byte[] outputBuffer, out int bytesRead)
 182131        {
 182132            Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!");
 182133            Debug.Assert(outputBuffer.Length > 0, "Can't pass in an empty output buffer!");
 134
 182135            ZErrorCode errC = ReadDeflateOutput(outputBuffer, ZFlushCode.Finish, out bytesRead);
 182136            return errC == ZErrorCode.StreamEnd;
 182137        }
 138
 139        /// <summary>
 140        /// Returns true if there was something to flush. Otherwise False.
 141        /// </summary>
 142        internal bool Flush(byte[] outputBuffer, out int bytesRead)
 0143        {
 0144            Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!");
 0145            Debug.Assert(outputBuffer.Length > 0, "Can't pass in an empty output buffer!");
 0146            Debug.Assert(NeedsInput(), "We have something left in previous input!");
 147
 148
 149            // Note: we require that NeedsInput() == true, i.e. that 0 == _zlibStream.AvailIn.
 150            // If there is still input left we should never be getting here; instead we
 151            // should be calling GetDeflateOutput.
 152
 0153            return ReadDeflateOutput(outputBuffer, ZFlushCode.SyncFlush, out bytesRead) == ZErrorCode.Ok;
 0154        }
 155
 156        /// <summary>
 157        /// Discards any unconsumed input previously set via SetInput, releasing the pinned reference (if any).
 158        /// Must be called if an in-progress operation is abandoned (e.g. due to an exception or cancellation) so
 159        /// the deflater doesn't retain a dangling reference to a buffer the caller may have since reused or freed.
 160        /// </summary>
 161        internal void UnsetInput()
 182162        {
 182163            lock (SyncLock)
 182164            {
 165                // On the common success path all input has already been consumed (NeedsInput() is true),
 166                // so there is nothing to abandon and no cleanup is necessary. Only when an operation is
 167                // abandoned mid-input do we need to reset state and release any pinned reference. This check
 168                // must happen under the lock so it can't race with a concurrent SetInput/Dispose call.
 182169                if (!NeedsInput())
 0170                {
 0171                    DeallocateInputBufferHandleCore(resetStreamHandle: true);
 0172                }
 182173            }
 182174        }
 175
 176        private void DeallocateInputBufferHandle(bool resetStreamHandle)
 364177        {
 364178            lock (SyncLock)
 364179            {
 364180                DeallocateInputBufferHandleCore(resetStreamHandle);
 364181            }
 364182        }
 183
 184        // Must be called while holding SyncLock.
 185        private void DeallocateInputBufferHandleCore(bool resetStreamHandle)
 364186        {
 364187            if (resetStreamHandle)
 182188            {
 182189                _zlibStream.AvailIn = 0;
 182190                _zlibStream.NextIn = ZLibNative.ZNullPtr;
 182191            }
 192
 364193            _inputBufferHandle.Dispose();
 364194        }
 195
 196        private ZErrorCode Deflate(ZFlushCode flushCode)
 364197        {
 198            ZErrorCode errC;
 199            try
 364200            {
 364201                errC = _zlibStream.Deflate(flushCode);
 364202            }
 0203            catch (Exception cause)
 0204            {
 0205                throw new ZLibException(SR.ZLibErrorDLLLoadError, cause);
 206            }
 207
 364208            switch (errC)
 209            {
 210                case ZErrorCode.Ok:
 211                case ZErrorCode.StreamEnd:
 364212                    return errC;
 213
 214                case ZErrorCode.BufError:
 0215                    return errC;  // This is a recoverable error
 216
 217                case ZErrorCode.StreamError:
 0218                    throw new ZLibException(SR.ZLibErrorInconsistentStream, "deflate", (int)errC, _zlibStream.GetErrorMe
 219
 220                default:
 0221                    throw new ZLibException(SR.ZLibErrorUnexpected, "deflate", (int)errC, _zlibStream.GetErrorMessage())
 222            }
 364223        }
 224
 225        public static Deflater CreateDeflater(ZLibNative.CompressionLevel compressionLevel, ZLibNative.CompressionStrate
 182226        {
 182227            Debug.Assert(windowBits >= minWindowBits && windowBits <= maxWindowBits);
 228
 182229            ZLibNative.ZLibStreamHandle zlibStream = ZLibNative.ZLibStreamHandle.CreateForDeflate(compressionLevel, wind
 230
 182231            return new Deflater(zlibStream);
 182232        }
 233    }
 234}