Beispiel #1
0
            private static unsafe int?IndexOfCharacterThatNeedsEscaping(Utf8Span utf8Span)
            {
                int vectorCount = Vector <byte> .Count;
                int index       = 0;

                // If we can benefit from SIMD scan, use that approach
                if (Vector.IsHardwareAccelerated)
                {
                    // Ensure we stop the SIMD scan before the length of the vector would
                    // go past the end of the array
#pragma warning disable IDE0047 // Remove unnecessary parentheses
                    int lastVectorMultiple = (utf8Span.Length / vectorCount) * vectorCount;
#pragma warning restore IDE0047 // Remove unnecessary parentheses

                    for (; index < lastVectorMultiple; index += vectorCount)
                    {
                        Vector <byte> vector;
                        unsafe
                        {
                            fixed(byte *spanPtr = utf8Span.Span)
                            {
                                vector = Unsafe.Read <Vector <byte> >(spanPtr + index);
                            }
                        }

                        if (JsonTextWriter.HasCharacterThatNeedsEscaping(vector))
                        {
                            // The Vector contained a character that needed escaping
                            // Loop to find the exact character and index
                            for (; index < utf8Span.Length; ++index)
                            {
                                byte c = utf8Span.Span[index];

                                if (JsonTextWriter.NeedsEscaping(c))
                                {
                                    return(index);
                                }
                            }
                        }
                    }
                }

                // Unless the scan ended on a vectorCount multiple,
                // still need to check the last few characters
                for (; index < utf8Span.Length; ++index)
                {
                    byte c = utf8Span.Span[index];

                    if (JsonTextWriter.NeedsEscaping(c))
                    {
                        return(index);
                    }
                }

                return(null);
            }