< Summary

Line coverage
85%
Covered lines: 104
Uncovered lines: 18
Coverable lines: 122
Total lines: 235
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)

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/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.
 262828        private object SyncLock => this;
 29
 43830        private Deflater(ZLibNative.ZLibStreamHandle zlibStream)
 43831        {
 43832            _zlibStream = zlibStream;
 43833        }
 34
 35        ~Deflater()
 036        {
 037            Dispose(false);
 038        }
 39
 40        public void Dispose()
 43841        {
 43842            Dispose(true);
 43843            GC.SuppressFinalize(this);
 43844        }
 45
 46        private void Dispose(bool disposing)
 43847        {
 43848            if (!_isDisposed)
 43849            {
 43850                if (disposing)
 43851                {
 43852                    _zlibStream.Dispose();
 43853                }
 54
 55                // Unpin the input buffer, but avoid modifying the ZLibStreamHandle (which may have been disposed of).
 43856                DeallocateInputBufferHandle(resetStreamHandle: false);
 43857                _isDisposed = true;
 43858            }
 43859        }
 60
 306661        public bool NeedsInput() => 0 == _zlibStream.AvailIn;
 62
 63        internal unsafe void SetInput(ReadOnlyMemory<byte> inputBuffer)
 21964        {
 21965            Debug.Assert(NeedsInput(), "We have something left in previous input!");
 21966            Debug.Assert(!inputBuffer.IsEmpty);
 67
 21968            lock (SyncLock)
 21969            {
 21970                _inputBufferHandle = inputBuffer.Pin();
 71
 21972                _zlibStream.NextIn = (IntPtr)_inputBufferHandle.Pointer;
 21973                _zlibStream.AvailIn = (uint)inputBuffer.Length;
 21974            }
 21975        }
 76
 77        internal unsafe void SetInput(byte* inputBufferPtr, int count)
 21978        {
 21979            Debug.Assert(NeedsInput(), "We have something left in previous input!");
 21980            Debug.Assert(inputBufferPtr != null);
 21981            Debug.Assert(count > 0);
 82
 21983            lock (SyncLock)
 21984            {
 21985                _zlibStream.NextIn = (IntPtr)inputBufferPtr;
 21986                _zlibStream.AvailIn = (uint)count;
 21987            }
 21988        }
 89
 90        internal int GetDeflateOutput(byte[] outputBuffer)
 43891        {
 43892            Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!");
 43893            Debug.Assert(!NeedsInput(), "GetDeflateOutput should only be called after providing input");
 94
 95            try
 43896            {
 97                int bytesRead;
 43898                ReadDeflateOutput(outputBuffer, ZFlushCode.NoFlush, out bytesRead);
 43899                return bytesRead;
 100            }
 101            finally
 438102            {
 103                // Before returning, make sure to release input buffer if necessary:
 438104                if (0 == _zlibStream.AvailIn)
 438105                {
 438106                    DeallocateInputBufferHandle(resetStreamHandle: true);
 438107                }
 438108            }
 438109        }
 110
 111        private unsafe ZErrorCode ReadDeflateOutput(byte[] outputBuffer, ZFlushCode flushCode, out int bytesRead)
 876112        {
 876113            Debug.Assert(outputBuffer?.Length > 0);
 114
 876115            lock (SyncLock)
 876116            {
 876117                fixed (byte* bufPtr = &outputBuffer[0])
 876118                {
 876119                    _zlibStream.NextOut = (IntPtr)bufPtr;
 876120                    _zlibStream.AvailOut = (uint)outputBuffer.Length;
 121
 876122                    ZErrorCode errC = Deflate(flushCode);
 876123                    bytesRead = outputBuffer.Length - (int)_zlibStream.AvailOut;
 124
 876125                    return errC;
 126                }
 127            }
 876128        }
 129
 130        internal bool Finish(byte[] outputBuffer, out int bytesRead)
 438131        {
 438132            Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!");
 438133            Debug.Assert(outputBuffer.Length > 0, "Can't pass in an empty output buffer!");
 134
 438135            ZErrorCode errC = ReadDeflateOutput(outputBuffer, ZFlushCode.Finish, out bytesRead);
 438136            return errC == ZErrorCode.StreamEnd;
 438137        }
 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()
 438162        {
 438163            lock (SyncLock)
 438164            {
 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.
 438169                if (!NeedsInput())
 0170                {
 0171                    DeallocateInputBufferHandleCore(resetStreamHandle: true);
 0172                }
 438173            }
 438174        }
 175
 176        private void DeallocateInputBufferHandle(bool resetStreamHandle)
 876177        {
 876178            lock (SyncLock)
 876179            {
 876180                DeallocateInputBufferHandleCore(resetStreamHandle);
 876181            }
 876182        }
 183
 184        // Must be called while holding SyncLock.
 185        private void DeallocateInputBufferHandleCore(bool resetStreamHandle)
 876186        {
 876187            if (resetStreamHandle)
 438188            {
 438189                _zlibStream.AvailIn = 0;
 438190                _zlibStream.NextIn = ZLibNative.ZNullPtr;
 438191            }
 192
 876193            _inputBufferHandle.Dispose();
 876194        }
 195
 196        private ZErrorCode Deflate(ZFlushCode flushCode)
 876197        {
 198            ZErrorCode errC;
 199            try
 876200            {
 876201                errC = _zlibStream.Deflate(flushCode);
 876202            }
 0203            catch (Exception cause)
 0204            {
 0205                throw new ZLibException(SR.ZLibErrorDLLLoadError, cause);
 206            }
 207
 876208            switch (errC)
 209            {
 210                case ZErrorCode.Ok:
 211                case ZErrorCode.StreamEnd:
 876212                    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            }
 876223        }
 224
 225        public static Deflater CreateDeflater(ZLibNative.CompressionLevel compressionLevel, ZLibNative.CompressionStrate
 438226        {
 438227            Debug.Assert(windowBits >= minWindowBits && windowBits <= maxWindowBits);
 228
 438229            ZLibNative.ZLibStreamHandle zlibStream = ZLibNative.ZLibStreamHandle.CreateForDeflate(compressionLevel, wind
 230
 438231            return new Deflater(zlibStream);
 438232        }
 233    }
 234}
 235