< Summary

Line coverage
6%
Covered lines: 6
Uncovered lines: 83
Coverable lines: 89
Total lines: 312
Line coverage: 6.7%
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%11100%
Reset()0%220%
GetByteCount(...)0%220%
GetByteCount(...)100%110%
GetBytes(...)0%660%
GetBytes(...)100%11100%
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/Encoder.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    // An Encoder is used to encode a sequence of blocks of characters into
 11    // a sequence of blocks of bytes. Following instantiation of an encoder,
 12    // sequential blocks of characters are converted into blocks of bytes through
 13    // calls to the GetBytes method. The encoder maintains state between the
 14    // conversions, allowing it to correctly encode character sequences that span
 15    // adjacent blocks.
 16    //
 17    // Instances of specific implementations of the Encoder abstract base
 18    // class are typically obtained through calls to the GetEncoder method
 19    // of Encoding objects.
 20    //
 21    public abstract class Encoder
 22    {
 23        internal EncoderFallback? _fallback;
 24
 25        internal EncoderFallbackBuffer? _fallbackBuffer;
 26
 127        protected Encoder()
 28        {
 29            // We don't call default reset because default reset probably isn't good if we aren't initialized.
 130        }
 31
 32        public EncoderFallback? 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 EncoderFallbackBuffer FallbackBuffer
 52        {
 53            get
 54            {
 055                _fallbackBuffer ??= _fallback is not null ?
 056                    _fallback.CreateFallbackBuffer() :
 057                    EncoderFallback.ReplacementFallback.CreateFallbackBuffer();
 58
 059                return _fallbackBuffer;
 60            }
 61        }
 62
 063        internal bool InternalHasFallbackBuffer => _fallbackBuffer is not null;
 64
 65        // Reset the Encoder
 66        //
 67        // Normally if we call GetBytes() and an error is thrown we don't change the state of the encoder.  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 GetBytes() throws an error, then they need to call Reset().
 71        //
 72        // Virtual implementation has to call GetBytes with flush and a big enough buffer to clear a 0 char string
 73        // We avoid GetMaxByteCount() because a) we can't call the base encoder and b) it might be really big.
 74        public virtual void Reset()
 75        {
 076            char[] charTemp = [];
 077            byte[] byteTemp = new byte[GetByteCount(charTemp, 0, 0, true)];
 078            GetBytes(charTemp, 0, 0, byteTemp, 0, true);
 079            _fallbackBuffer?.Reset();
 080        }
 81
 82        // Returns the number of bytes the next call to GetBytes will
 83        // produce if presented with the given range of characters and the given
 84        // value of the flush parameter. The returned value takes into
 85        // account the state in which the encoder was left following the last call
 86        // to GetBytes. The state of the encoder is not affected by a call
 87        // to this method.
 88        //
 89        public abstract int GetByteCount(char[] chars, int index, int count, bool flush);
 90
 91        // We expect this to be the workhorse for NLS encodings
 92        // unfortunately for existing overrides, it has to call the [] version,
 93        // which is really slow, so avoid this method if you might be calling external encodings.
 94        [CLSCompliant(false)]
 95        public virtual unsafe int GetByteCount(char* chars, int count, bool flush)
 96        {
 097            ArgumentNullException.ThrowIfNull(chars);
 98
 099            ArgumentOutOfRangeException.ThrowIfNegative(count);
 100
 0101            char[] arrChar = new char[count];
 102
 0103            for (int index = 0; index < count; index++)
 0104                arrChar[index] = chars[index];
 105
 0106            return GetByteCount(arrChar, 0, count, flush);
 107        }
 108
 109        public virtual unsafe int GetByteCount(ReadOnlySpan<char> chars, bool flush)
 0110        {
 0111            fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars))
 112            {
 0113                return GetByteCount(charsPtr, chars.Length, flush);
 114            }
 115        }
 116
 117        // Encodes a range of characters in a character array into a range of bytes
 118        // in a byte array. The method encodes charCount characters from
 119        // chars starting at index charIndex, storing the resulting
 120        // bytes in bytes starting at index byteIndex. The encoding
 121        // takes into account the state in which the encoder was left following the
 122        // last call to this method. The flush parameter indicates whether
 123        // the encoder should flush any shift-states and partial characters at the
 124        // end of the conversion. To ensure correct termination of a sequence of
 125        // blocks of encoded bytes, the last call to GetBytes should specify
 126        // a value of true for the flush parameter.
 127        //
 128        // An exception occurs if the byte array is not large enough to hold the
 129        // complete encoding of the characters. The GetByteCount method can
 130        // be used to determine the exact number of bytes that will be produced for
 131        // a given range of characters. Alternatively, the GetMaxByteCount
 132        // method of the Encoding that produced this encoder can be used to
 133        // determine the maximum number of bytes that will be produced for a given
 134        // number of characters, regardless of the actual character values.
 135        //
 136        public abstract int GetBytes(char[] chars, int charIndex, int charCount,
 137                                        byte[] bytes, int byteIndex, bool flush);
 138
 139        // We expect this to be the workhorse for NLS Encodings, but for existing
 140        // ones we need a working (if slow) default implementation)
 141        //
 142        // WARNING WARNING WARNING
 143        //
 144        // WARNING: If this breaks it could be a security threat.  Obviously we
 145        // call this internally, so you need to make sure that your pointers, counts
 146        // and indexes are correct when you call this method.
 147        //
 148        // In addition, we have internal code, which will be marked as "safe" calling
 149        // this code.  However this code is dependent upon the implementation of an
 150        // external GetBytes() method, which could be overridden by a third party and
 151        // the results of which cannot be guaranteed.  We use that result to copy
 152        // the byte[] to our byte* output buffer.  If the result count was wrong, we
 153        // could easily overflow our output buffer.  Therefore we do an extra test
 154        // when we copy the buffer so that we don't overflow byteCount either.
 155        [CLSCompliant(false)]
 156        public virtual unsafe int GetBytes(char* chars, int charCount,
 157                                           byte* bytes, int byteCount, bool flush)
 158        {
 0159            ArgumentNullException.ThrowIfNull(chars);
 0160            ArgumentNullException.ThrowIfNull(bytes);
 161
 0162            ArgumentOutOfRangeException.ThrowIfNegative(charCount);
 0163            ArgumentOutOfRangeException.ThrowIfNegative(byteCount);
 164
 165            // Get the char array to convert
 0166            char[] arrChar = new char[charCount];
 167
 0168            for (int index = 0; index < charCount; index++)
 0169                arrChar[index] = chars[index];
 170
 171            // Get the byte array to fill
 0172            byte[] arrByte = new byte[byteCount];
 173
 174            // Do the work
 0175            int result = GetBytes(arrChar, 0, charCount, arrByte, 0, flush);
 176
 0177            Debug.Assert(result <= byteCount, "Returned more bytes than we have space for");
 178
 179            // Copy the byte array
 180            // WARNING: We MUST make sure that we don't copy too many bytes.  We can't
 181            // rely on result because it could be a 3rd party implementation.  We need
 182            // to make sure we never copy more than byteCount bytes no matter the value
 183            // of result
 0184            if (result < byteCount)
 0185                byteCount = result;
 186
 187            // Don't copy too many bytes!
 0188            for (int index = 0; index < byteCount; index++)
 0189                bytes[index] = arrByte[index];
 190
 0191            return byteCount;
 192        }
 193
 194        public virtual unsafe int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes, bool flush)
 3195        {
 3196            fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars))
 3197            fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes))
 198            {
 3199                return GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length, flush);
 200            }
 201        }
 202
 203        // This method is used to avoid running out of output buffer space.
 204        // It will encode until it runs out of chars, and then it will return
 205        // true if it the entire input was converted.  In either case it
 206        // will also return the number of converted chars and output bytes used.
 207        // It will only throw a buffer overflow exception if the entire length of bytes[] is
 208        // too small to store the next byte. (like 0 or maybe 1 or 4 for some encodings)
 209        // We're done processing this buffer only if completed returns true.
 210        //
 211        // Might consider checking Max...Count to avoid the extra counting step.
 212        //
 213        // Note that if all of the input chars are not consumed, then we'll do a /2, which means
 214        // that its likely that we didn't consume as many chars as we could have.  For some
 215        // applications this could be slow.  (Like trying to exactly fill an output buffer from a bigger stream)
 216        public virtual void Convert(char[] chars, int charIndex, int charCount,
 217                                    byte[] bytes, int byteIndex, int byteCount, bool flush,
 218                                    out int charsUsed, out int bytesUsed, out bool completed)
 219        {
 0220            ArgumentNullException.ThrowIfNull(chars);
 0221            ArgumentNullException.ThrowIfNull(bytes);
 222
 0223            ArgumentOutOfRangeException.ThrowIfNegative(charIndex);
 0224            ArgumentOutOfRangeException.ThrowIfNegative(charCount);
 225
 0226            ArgumentOutOfRangeException.ThrowIfNegative(byteIndex);
 0227            ArgumentOutOfRangeException.ThrowIfNegative(byteCount);
 228
 0229            if (chars.Length - charIndex < charCount)
 0230                throw new ArgumentOutOfRangeException(nameof(chars),
 0231                      SR.ArgumentOutOfRange_IndexCountBuffer);
 232
 0233            if (bytes.Length - byteIndex < byteCount)
 0234                throw new ArgumentOutOfRangeException(nameof(bytes),
 0235                      SR.ArgumentOutOfRange_IndexCountBuffer);
 236
 0237            charsUsed = charCount;
 238
 239            // Its easy to do if it won't overrun our buffer.
 240            // Note: We don't want to call unsafe version because that might be an untrusted version
 241            // which could be really unsafe and we don't want to mix it up.
 0242            while (charsUsed > 0)
 243            {
 0244                if (GetByteCount(chars, charIndex, charsUsed, flush) <= byteCount)
 245                {
 0246                    bytesUsed = GetBytes(chars, charIndex, charsUsed, bytes, byteIndex, flush);
 0247                    completed = (charsUsed == charCount &&
 0248                        (_fallbackBuffer == 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                charsUsed /= 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        // Same thing, but using pointers
 262        //
 263        // Might consider checking Max...Count to avoid the extra counting step.
 264        //
 265        // Note that if all of the input chars are not consumed, then we'll do a /2, which means
 266        // that its likely that we didn't consume as many chars as we could have.  For some
 267        // applications this could be slow.  (Like trying to exactly fill an output buffer from a bigger stream)
 268        [CLSCompliant(false)]
 269        public virtual unsafe void Convert(char* chars, int charCount,
 270                                           byte* bytes, int byteCount, bool flush,
 271                                           out int charsUsed, out int bytesUsed, out bool completed)
 272        {
 0273            ArgumentNullException.ThrowIfNull(chars);
 0274            ArgumentNullException.ThrowIfNull(bytes);
 275
 0276            ArgumentOutOfRangeException.ThrowIfNegative(charCount);
 0277            ArgumentOutOfRangeException.ThrowIfNegative(byteCount);
 278
 279            // Get ready to do it
 0280            charsUsed = charCount;
 281
 282            // Its easy to do if it won't overrun our buffer.
 0283            while (charsUsed > 0)
 284            {
 0285                if (GetByteCount(chars, charsUsed, flush) <= byteCount)
 286                {
 0287                    bytesUsed = GetBytes(chars, charsUsed, bytes, byteCount, flush);
 0288                    completed = (charsUsed == charCount &&
 0289                        (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0));
 0290                    return;
 291                }
 292
 293                // Try again with 1/2 the count, won't flush then 'cause won't read it all
 0294                flush = false;
 0295                charsUsed /= 2;
 296            }
 297
 298            // Oops, we didn't have anything, we'll have to throw an overflow
 0299            throw new ArgumentException(SR.Argument_ConversionOverflow);
 300        }
 301
 302        public virtual unsafe void Convert(ReadOnlySpan<char> chars, Span<byte> bytes, bool flush, out int charsUsed, ou
 0303        {
 0304            fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars))
 0305            fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes))
 306            {
 0307                Convert(charsPtr, chars.Length, bytesPtr, bytes.Length, flush, out charsUsed, out bytesUsed, out complet
 308            }
 0309        }
 310    }
 311}
 312