< Summary

Line coverage
0%
Covered lines: 0
Uncovered lines: 91
Coverable lines: 91
Total lines: 313
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 38
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Cyclomatic complexity NPath complexity Sequence coverage
.ctor()100%110%
Reset()0%220%
GetCharCount(...)100%110%
GetCharCount(...)0%220%
GetCharCount(...)100%110%
GetChars(...)100%110%
GetChars(...)0%660%
GetChars(...)100%110%
Convert(...)0%12120%
Convert(...)0%880%
Convert(...)100%110%

File(s)

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Private.CoreLib/src/System/Text/Decoder.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.Diagnostics;
 5using System.Diagnostics.CodeAnalysis;
 6using System.Runtime.InteropServices;
 7
 8namespace System.Text
 9{
 10    // A Decoder is used to decode a sequence of blocks of bytes into a
 11    // sequence of blocks of characters. Following instantiation of a decoder,
 12    // sequential blocks of bytes are converted into blocks of characters through
 13    // calls to the GetChars method. The decoder maintains state between the
 14    // conversions, allowing it to correctly decode byte sequences that span
 15    // adjacent blocks.
 16    //
 17    // Instances of specific implementations of the Decoder abstract base
 18    // class are typically obtained through calls to the GetDecoder method
 19    // of Encoding objects.
 20    //
 21    public abstract class Decoder
 22    {
 23        internal DecoderFallback? _fallback;
 24
 25        internal DecoderFallbackBuffer? _fallbackBuffer;
 26
 027        protected Decoder()
 28        {
 29            // We don't call default reset because default reset probably isn't good if we aren't initialized.
 030        }
 31
 32        public DecoderFallback? Fallback
 33        {
 034            get => _fallback;
 35            set
 36            {
 037                ArgumentNullException.ThrowIfNull(value);
 38
 39                // Can't change fallback if buffer is wrong
 040                if (_fallbackBuffer is not null && _fallbackBuffer.Remaining > 0)
 041                    throw new ArgumentException(
 042                      SR.Argument_FallbackBufferNotEmpty, nameof(value));
 43
 044                _fallback = value;
 045                _fallbackBuffer = null;
 046            }
 47        }
 48
 49        // Note: we don't test for threading here because async access to Encoders and Decoders
 50        // doesn't work anyway.
 51        public DecoderFallbackBuffer FallbackBuffer
 52        {
 53            get
 54            {
 055                _fallbackBuffer ??= _fallback is not null ?
 056                    _fallback.CreateFallbackBuffer() :
 057                    DecoderFallback.ReplacementFallback.CreateFallbackBuffer();
 58
 059                return _fallbackBuffer;
 60            }
 61        }
 62
 063        internal bool InternalHasFallbackBuffer => _fallbackBuffer is not null;
 64
 65        // Reset the Decoder
 66        //
 67        // Normally if we call GetChars() and an error is thrown we don't change the state of the Decoder.  This
 68        // would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.)
 69        //
 70        // If the caller doesn't want to try again after GetChars() throws an error, then they need to call Reset().
 71        //
 72        // Virtual implementation has to call GetChars with flush and a big enough buffer to clear a 0 byte string
 73        // We avoid GetMaxCharCount() because a) we can't call the base encoder and b) it might be really big.
 74        public virtual void Reset()
 75        {
 076            byte[] byteTemp = [];
 077            char[] charTemp = new char[GetCharCount(byteTemp, 0, 0, true)];
 078            GetChars(byteTemp, 0, 0, charTemp, 0, true);
 079            _fallbackBuffer?.Reset();
 080        }
 81
 82        // Returns the number of characters the next call to GetChars will
 83        // produce if presented with the given range of bytes. The returned value
 84        // takes into account the state in which the decoder was left following the
 85        // last call to GetChars. The state of the decoder is not affected
 86        // by a call to this method.
 87        //
 88        public abstract int GetCharCount(byte[] bytes, int index, int count);
 89
 90        public virtual int GetCharCount(byte[] bytes, int index, int count, bool flush)
 91        {
 092            return GetCharCount(bytes, index, count);
 93        }
 94
 95        // We expect this to be the workhorse for NLS Encodings, but for existing
 96        // ones we need a working (if slow) default implementation)
 97        [CLSCompliant(false)]
 98        public virtual unsafe int GetCharCount(byte* bytes, int count, bool flush)
 99        {
 0100            ArgumentNullException.ThrowIfNull(bytes);
 0101            ArgumentOutOfRangeException.ThrowIfNegative(count);
 102
 0103            byte[] arrbyte = new byte[count];
 104
 0105            for (int index = 0; index < count; index++)
 0106                arrbyte[index] = bytes[index];
 107
 0108            return GetCharCount(arrbyte, 0, count);
 109        }
 110
 111        public virtual unsafe int GetCharCount(ReadOnlySpan<byte> bytes, bool flush)
 0112        {
 0113            fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes))
 114            {
 0115                return GetCharCount(bytesPtr, bytes.Length, flush);
 116            }
 117        }
 118
 119        // Decodes a range of bytes in a byte array into a range of characters
 120        // in a character array. The method decodes byteCount bytes from
 121        // bytes starting at index byteIndex, storing the resulting
 122        // characters in chars starting at index charIndex. The
 123        // decoding takes into account the state in which the decoder was left
 124        // following the last call to this method.
 125        //
 126        // An exception occurs if the character array is not large enough to
 127        // hold the complete decoding of the bytes. The GetCharCount method
 128        // can be used to determine the exact number of characters that will be
 129        // produced for a given range of bytes. Alternatively, the
 130        // GetMaxCharCount method of the Encoding that produced this
 131        // decoder can be used to determine the maximum number of characters that
 132        // will be produced for a given number of bytes, regardless of the actual
 133        // byte values.
 134        //
 135        public abstract int GetChars(byte[] bytes, int byteIndex, int byteCount,
 136                                        char[] chars, int charIndex);
 137
 138        public virtual int GetChars(byte[] bytes, int byteIndex, int byteCount,
 139                                       char[] chars, int charIndex, bool flush)
 140        {
 0141            return GetChars(bytes, byteIndex, byteCount, chars, charIndex);
 142        }
 143
 144        // We expect this to be the workhorse for NLS Encodings, but for existing
 145        // ones we need a working (if slow) default implementation)
 146        //
 147        // WARNING: If this breaks it could be a security threat.  Obviously we
 148        // call this internally, so you need to make sure that your pointers, counts
 149        // and indexes are correct when you call this method.
 150        //
 151        // In addition, we have internal code, which will be marked as "safe" calling
 152        // this code.  However this code is dependent upon the implementation of an
 153        // external GetChars() method, which could be overridden by a third party and
 154        // the results of which cannot be guaranteed.  We use that result to copy
 155        // the char[] to our char* output buffer.  If the result count was wrong, we
 156        // could easily overflow our output buffer.  Therefore we do an extra test
 157        // when we copy the buffer so that we don't overflow charCount either.
 158        [CLSCompliant(false)]
 159        public virtual unsafe int GetChars(byte* bytes, int byteCount,
 160                                           char* chars, int charCount, bool flush)
 161        {
 0162            ArgumentNullException.ThrowIfNull(bytes);
 0163            ArgumentNullException.ThrowIfNull(chars);
 0164            ArgumentOutOfRangeException.ThrowIfNegative(byteCount);
 0165            ArgumentOutOfRangeException.ThrowIfNegative(charCount);
 166
 167            // Get the byte array to convert
 0168            byte[] arrByte = new byte[byteCount];
 169
 0170            for (int index = 0; index < byteCount; index++)
 0171                arrByte[index] = bytes[index];
 172
 173            // Get the char array to fill
 0174            char[] arrChar = new char[charCount];
 175
 176            // Do the work
 0177            int result = GetChars(arrByte, 0, byteCount, arrChar, 0, flush);
 178
 0179            Debug.Assert(result <= charCount, "Returned more chars than we have space for");
 180
 181            // Copy the char array
 182            // WARNING: We MUST make sure that we don't copy too many chars.  We can't
 183            // rely on result because it could be a 3rd party implementation.  We need
 184            // to make sure we never copy more than charCount chars no matter the value
 185            // of result
 0186            if (result < charCount)
 0187                charCount = result;
 188
 189            // We check both result and charCount so that we don't accidentally overrun
 190            // our pointer buffer just because of an issue in GetChars
 0191            for (int index = 0; index < charCount; index++)
 0192                chars[index] = arrChar[index];
 193
 0194            return charCount;
 195        }
 196
 197        public virtual unsafe int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars, bool flush)
 0198        {
 0199            fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes))
 0200            fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars))
 201            {
 0202                return GetChars(bytesPtr, bytes.Length, charsPtr, chars.Length, flush);
 203            }
 204        }
 205
 206        // This method is used when the output buffer might not be large enough.
 207        // It will decode until it runs out of bytes, and then it will return
 208        // true if it the entire input was converted.  In either case it
 209        // will also return the number of converted bytes and output characters used.
 210        // It will only throw a buffer overflow exception if the entire length of chars[] is
 211        // too small to store the next char. (like 0 or maybe 1 or 4 for some encodings)
 212        // We're done processing this buffer only if completed returns true.
 213        //
 214        // Might consider checking Max...Count to avoid the extra counting step.
 215        //
 216        // Note that if all of the input bytes are not consumed, then we'll do a /2, which means
 217        // that its likely that we didn't consume as many bytes as we could have.  For some
 218        // applications this could be slow.  (Like trying to exactly fill an output buffer from a bigger stream)
 219        public virtual void Convert(byte[] bytes, int byteIndex, int byteCount,
 220                                    char[] chars, int charIndex, int charCount, bool flush,
 221                                    out int bytesUsed, out int charsUsed, out bool completed)
 222        {
 0223            ArgumentNullException.ThrowIfNull(bytes);
 0224            ArgumentNullException.ThrowIfNull(chars);
 225
 0226            ArgumentOutOfRangeException.ThrowIfNegative(byteIndex);
 0227            ArgumentOutOfRangeException.ThrowIfNegative(byteCount);
 0228            ArgumentOutOfRangeException.ThrowIfNegative(charIndex);
 0229            ArgumentOutOfRangeException.ThrowIfNegative(charCount);
 230
 0231            if (bytes.Length - byteIndex < byteCount)
 0232                throw new ArgumentOutOfRangeException(nameof(bytes),
 0233                      SR.ArgumentOutOfRange_IndexCountBuffer);
 234
 0235            if (chars.Length - charIndex < charCount)
 0236                throw new ArgumentOutOfRangeException(nameof(chars),
 0237                      SR.ArgumentOutOfRange_IndexCountBuffer);
 238
 0239            bytesUsed = byteCount;
 240
 241            // Its easy to do if it won't overrun our buffer.
 0242            while (bytesUsed > 0)
 243            {
 0244                if (GetCharCount(bytes, byteIndex, bytesUsed, flush) <= charCount)
 245                {
 0246                    charsUsed = GetChars(bytes, byteIndex, bytesUsed, chars, charIndex, flush);
 0247                    completed = (bytesUsed == byteCount &&
 0248                        (_fallbackBuffer is null || _fallbackBuffer.Remaining == 0));
 0249                    return;
 250                }
 251
 252                // Try again with 1/2 the count, won't flush then 'cause won't read it all
 0253                flush = false;
 0254                bytesUsed /= 2;
 255            }
 256
 257            // Oops, we didn't have anything, we'll have to throw an overflow
 0258            throw new ArgumentException(SR.Argument_ConversionOverflow);
 259        }
 260
 261        // This is the version that uses *.
 262        // We're done processing this buffer only if completed returns true.
 263        //
 264        // Might consider checking Max...Count to avoid the extra counting step.
 265        //
 266        // Note that if all of the input bytes are not consumed, then we'll do a /2, which means
 267        // that its likely that we didn't consume as many bytes as we could have.  For some
 268        // applications this could be slow.  (Like trying to exactly fill an output buffer from a bigger stream)
 269        [CLSCompliant(false)]
 270        public virtual unsafe void Convert(byte* bytes, int byteCount,
 271                                           char* chars, int charCount, bool flush,
 272                                           out int bytesUsed, out int charsUsed, out bool completed)
 273        {
 0274            ArgumentNullException.ThrowIfNull(bytes);
 0275            ArgumentNullException.ThrowIfNull(chars);
 276
 0277            ArgumentOutOfRangeException.ThrowIfNegative(byteCount);
 0278            ArgumentOutOfRangeException.ThrowIfNegative(charCount);
 279
 280            // Get ready to do it
 0281            bytesUsed = byteCount;
 282
 283            // Its easy to do if it won't overrun our buffer.
 0284            while (bytesUsed > 0)
 285            {
 0286                if (GetCharCount(bytes, bytesUsed, flush) <= charCount)
 287                {
 0288                    charsUsed = GetChars(bytes, bytesUsed, chars, charCount, flush);
 0289                    completed = (bytesUsed == byteCount &&
 0290                        (_fallbackBuffer is null || _fallbackBuffer.Remaining == 0));
 0291                    return;
 292                }
 293
 294                // Try again with 1/2 the count, won't flush then 'cause won't read it all
 0295                flush = false;
 0296                bytesUsed /= 2;
 297            }
 298
 299            // Oops, we didn't have anything, we'll have to throw an overflow
 0300            throw new ArgumentException(SR.Argument_ConversionOverflow);
 301        }
 302
 303        public virtual unsafe void Convert(ReadOnlySpan<byte> bytes, Span<char> chars, bool flush, out int bytesUsed, ou
 0304        {
 0305            fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes))
 0306            fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars))
 307            {
 0308                Convert(bytesPtr, bytes.Length, charsPtr, chars.Length, flush, out bytesUsed, out charsUsed, out complet
 309            }
 0310        }
 311    }
 312}
 313