|
| 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 | +// See the LICENSE file in the project root for more information. |
| 4 | + |
| 5 | +using System.Buffers; |
| 6 | +using System.Diagnostics; |
| 7 | +using System.IO; |
| 8 | +using System.Runtime.CompilerServices; |
| 9 | + |
| 10 | +namespace System.Text.Unicode |
| 11 | +{ |
| 12 | + internal static class Utf8Utility |
| 13 | + { |
| 14 | + /// <summary> |
| 15 | + /// The maximum number of bytes that can result from UTF-8 transcoding |
| 16 | + /// any Unicode scalar value. |
| 17 | + /// </summary> |
| 18 | + internal const int MaxBytesPerScalar = 4; |
| 19 | + |
| 20 | + /// <summary> |
| 21 | + /// The UTF-8 representation of <see cref="UnicodeUtility.ReplacementChar"/>. |
| 22 | + /// </summary> |
| 23 | + private static ReadOnlySpan<byte> ReplacementCharSequence => new byte[] { 0xEF, 0xBF, 0xBD }; |
| 24 | + |
| 25 | + /// <summary> |
| 26 | + /// Returns the byte index in <paramref name="utf8Data"/> where the first invalid UTF-8 sequence begins, |
| 27 | + /// or -1 if the buffer contains no invalid sequences. Also outs the <paramref name="isAscii"/> parameter |
| 28 | + /// stating whether all data observed (up to the first invalid sequence or the end of the buffer, whichever |
| 29 | + /// comes first) is ASCII. |
| 30 | + /// </summary> |
| 31 | + [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| 32 | + public static int GetIndexOfFirstInvalidUtf8Sequence(ReadOnlySpan<byte> utf8Data, out bool isAscii) |
| 33 | + { |
| 34 | + // TODO_UTF8STRING: Replace this with the faster drop-in replacement when it's available (coreclr #21948). |
| 35 | + |
| 36 | + bool tempIsAscii = true; |
| 37 | + int originalDataLength = utf8Data.Length; |
| 38 | + |
| 39 | + while (!utf8Data.IsEmpty) |
| 40 | + { |
| 41 | + if (Rune.DecodeFromUtf8(utf8Data, out Rune result, out int bytesConsumed) != OperationStatus.Done) |
| 42 | + { |
| 43 | + break; |
| 44 | + } |
| 45 | + |
| 46 | + tempIsAscii &= result.IsAscii; |
| 47 | + utf8Data = utf8Data.Slice(bytesConsumed); |
| 48 | + } |
| 49 | + |
| 50 | + isAscii = tempIsAscii; |
| 51 | + return (utf8Data.IsEmpty) ? -1 : (originalDataLength - utf8Data.Length); |
| 52 | + } |
| 53 | + |
| 54 | +#if FEATURE_UTF8STRING |
| 55 | + /// <summary> |
| 56 | + /// Returns <paramref name="value"/> if it is null or contains only well-formed UTF-8 data; |
| 57 | + /// otherwises allocates a new <see cref="Utf8String"/> instance containing the same data as |
| 58 | + /// <paramref name="value"/> but where all invalid UTF-8 sequences have been replaced |
| 59 | + /// with U+FFD. |
| 60 | + /// </summary> |
| 61 | + public static Utf8String ValidateAndFixupUtf8String(Utf8String value) |
| 62 | + { |
| 63 | + if (Utf8String.IsNullOrEmpty(value)) |
| 64 | + { |
| 65 | + return value; |
| 66 | + } |
| 67 | + |
| 68 | + ReadOnlySpan<byte> valueAsBytes = value.AsBytes(); |
| 69 | + |
| 70 | + int idxOfFirstInvalidData = GetIndexOfFirstInvalidUtf8Sequence(valueAsBytes, out _); |
| 71 | + if (idxOfFirstInvalidData < 0) |
| 72 | + { |
| 73 | + return value; |
| 74 | + } |
| 75 | + |
| 76 | + // TODO_UTF8STRING: Replace this with the faster implementation once it's available. |
| 77 | + // (The faster implementation is in the dev/utf8string_bak branch currently.) |
| 78 | + |
| 79 | + MemoryStream memStream = new MemoryStream(); |
| 80 | + memStream.Write(valueAsBytes.Slice(0, idxOfFirstInvalidData)); |
| 81 | + |
| 82 | + valueAsBytes = valueAsBytes.Slice(idxOfFirstInvalidData); |
| 83 | + do |
| 84 | + { |
| 85 | + if (Rune.DecodeFromUtf8(valueAsBytes, out _, out int bytesConsumed) == OperationStatus.Done) |
| 86 | + { |
| 87 | + // Valid scalar value - copy data as-is to MemoryStream |
| 88 | + memStream.Write(valueAsBytes.Slice(0, bytesConsumed)); |
| 89 | + } |
| 90 | + else |
| 91 | + { |
| 92 | + // Invalid scalar value - copy U+FFFD to MemoryStream |
| 93 | + memStream.Write(ReplacementCharSequence); |
| 94 | + } |
| 95 | + |
| 96 | + valueAsBytes = valueAsBytes.Slice(bytesConsumed); |
| 97 | + } while (!valueAsBytes.IsEmpty); |
| 98 | + |
| 99 | + bool success = memStream.TryGetBuffer(out ArraySegment<byte> memStreamBuffer); |
| 100 | + Debug.Assert(success, "Couldn't get underlying MemoryStream buffer."); |
| 101 | + |
| 102 | + return Utf8String.DangerousCreateWithoutValidation(memStreamBuffer, assumeWellFormed: true); |
| 103 | + } |
| 104 | +#endif // FEATURE_UTF8STRING |
| 105 | + } |
| 106 | +} |
0 commit comments