< Summary

Line coverage
10%
Covered lines: 114
Uncovered lines: 1002
Coverable lines: 1116
Total lines: 3406
Line coverage: 10.2%
Branch coverage
5%
Covered branches: 32
Total branches: 582
Branch coverage: 5.4%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Cyclomatic complexity NPath complexity Sequence coverage
File 1: GetReplaceBufferCapacity(...)0%220%
File 1: ReplaceBufferInternal(...)0%220%
File 1: ReplaceBufferUtf8Internal(...)0%220%
File 1: ReplaceBufferAnsiInternal(...)0%660%
File 1: InternalCopy(...)100%110%
File 2: .ctor()100%11100%
File 2: .ctor(...)100%110%
File 2: .ctor(...)100%110%
File 2: .ctor(...)0%220%
File 2: .ctor(...)0%660%
File 2: .ctor(...)0%440%
File 2: .ctor(...)0%20200%
File 2: System.Runtime.Serialization.ISerializable.GetObjectData(...)100%110%
File 2: AssertInvariants()100%22100%
File 2: EnsureCapacity(...)0%220%
File 2: ToString()60%101088.88%
File 2: ToString(...)0%440%
File 2: Clear()100%110%
File 2: MoveChunks(...)100%110%
File 2: GetChunks()100%110%
File 2: GetEnumerator()100%110%
File 2: MoveNext()0%660%
File 2: .ctor(...)0%220%
File 2: ChunkCount(...)0%220%
File 2: MoveNext(...)0%220%
File 2: .ctor(...)0%220%
File 2: EnumerateRunes()100%110%
File 2: Append(...)0%440%
File 2: AppendWithExpansion(...)0%440%
File 2: Append(...)0%10100%
File 2: Append(...)50%22100%
File 2: Append(...)40%101063.63%
File 2: Append(...)0%440%
File 2: Append(...)0%10100%
File 2: AppendCore(...)0%10100%
File 2: AppendLine()100%110%
File 2: AppendLine(...)100%110%
File 2: CopyTo(...)0%220%
File 2: CopyTo(...)0%10100%
File 2: Insert(...)100%110%
File 2: Insert(...)0%10100%
File 2: Remove(...)0%880%
File 2: Append(...)100%110%
File 2: Append(...)100%22100%
File 2: AppendWithExpansion(...)100%11100%
File 2: Append(...)100%110%
File 2: Append(...)100%110%
File 2: Append(...)100%110%
File 2: Append(...)100%110%
File 2: Append(...)100%11100%
File 2: Append(...)100%110%
File 2: Append(...)100%110%
File 2: Append(...)100%110%
File 2: Append(...)100%110%
File 2: Append(...)100%110%
File 2: Append(...)100%110%
File 2: Append(...)100%110%
File 2: AppendSpanFormattable(...)75%44100%
File 2: Append(...)0%220%
File 2: Append(...)0%220%
File 2: Append(...)100%110%
File 2: Append(...)100%110%
File 2: Append(...)100%110%
File 2: Append(...)100%110%
File 2: AppendLine(...)100%110%
File 2: AppendLine(...)100%110%
File 2: AppendJoin(...)0%440%
File 2: AppendJoin(...)0%220%
File 2: AppendJoin(...)0%440%
File 2: AppendJoin(...)0%440%
File 2: AppendJoin(...)0%220%
File 2: AppendJoin(...)0%220%
File 2: AppendJoin(...)100%110%
File 2: AppendJoin(...)0%220%
File 2: AppendJoin(...)0%220%
File 2: AppendJoin(...)100%110%
File 2: AppendJoinCore(...)0%880%
File 2: AppendJoinCore(...)0%880%
File 2: Insert(...)0%440%
File 2: Insert(...)100%110%
File 2: Insert(...)100%110%
File 2: Insert(...)100%110%
File 2: Insert(...)100%110%
File 2: Insert(...)0%220%
File 2: Insert(...)100%110%
File 2: Insert(...)0%440%
File 2: Insert(...)0%12120%
File 2: Insert(...)100%110%
File 2: Insert(...)100%110%
File 2: Insert(...)100%110%
File 2: Insert(...)100%110%
File 2: Insert(...)100%110%
File 2: Insert(...)100%110%
File 2: Insert(...)100%110%
File 2: Insert(...)100%110%
File 2: Insert(...)0%220%
File 2: Insert(...)0%440%
File 2: InsertSpanFormattable(...)0%440%
File 2: AppendFormat(...)100%110%
File 2: AppendFormat(...)100%110%
File 2: AppendFormat(...)100%110%
File 2: AppendFormat(...)0%440%
File 2: AppendFormat(...)100%110%
File 2: AppendFormat(...)100%110%
File 2: AppendFormat(...)100%110%
File 2: AppendFormat(...)100%110%
File 2: AppendFormat(...)0%440%
File 2: AppendFormat(...)0%78780%
File 2: MoveNext(System.String,System.Int32&)0%220%
File 2: AppendFormat(...)100%110%
File 2: AppendFormat(...)100%110%
File 2: AppendFormat(...)100%110%
File 2: AppendFormat(...)100%110%
File 2: AppendFormat(...)0%440%
File 2: AppendFormat(...)0%880%
File 2: Replace(...)100%110%
File 2: Replace(...)100%110%
File 2: Equals(...)0%22220%
File 2: Equals(...)0%660%
File 2: Replace(...)100%110%
File 2: Replace(...)0%32320%
File 2: Replace(...)100%110%
File 2: Replace(...)0%10100%
File 2: Replace(...)100%110%
File 2: Replace(...)100%110%
File 2: Append(...)100%110%
File 2: Append(...)87.5%88100%
File 2: AppendWithExpansion(...)66.66%6692.85%
File 2: Insert(...)0%220%
File 2: ReplaceAllInChunk(...)0%10100%
File 2: StartsWith(...)0%10100%
File 2: ReplaceInPlaceAtChunk(...)0%660%
File 2: FindChunkForIndex(...)0%440%
File 2: Next(...)0%220%
File 2: ExpandByABlock(...)50%6686.66%
File 2: .ctor(...)100%11100%
File 2: MakeRoom(...)0%20200%
File 2: .ctor(...)0%220%
File 2: Remove(...)0%14140%
File 2: GetRuneAt(...)0%220%
File 2: TryGetRuneAt(...)0%440%
File 2: .ctor(...)100%110%
File 2: .ctor(...)0%220%
File 2: AppendLiteral(...)100%110%
File 2: AppendFormatted(...)0%16160%
File 2: AppendFormatted(...)0%16160%
File 2: AppendFormatted(...)100%110%
File 2: AppendFormatted(...)0%660%
File 2: AppendFormattedWithTempSpace(...)100%110%
File 2: AppendFormatted(...)100%110%
File 2: AppendFormatted(...)0%880%
File 2: AppendFormatted(...)0%220%
File 2: AppendFormatted(...)100%110%
File 2: AppendFormatted(...)100%110%
File 2: AppendCustomFormatter(...)0%220%

File(s)

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/coreclr/System.Private.CoreLib/src/System/Text/StringBuilder.CoreCLR.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    public partial class StringBuilder
 11    {
 12        private int GetReplaceBufferCapacity(int requiredCapacity)
 13        {
 14            // This function assumes that required capacity will be less
 15            // than the max capacity of the StringBuilder
 016            Debug.Assert(requiredCapacity <= m_MaxCapacity);
 17
 018            int newCapacity = Capacity;
 19            // Round the current capacity to the nearest multiple of 2
 20            // that is larger than the required capacity.
 021            if (newCapacity < requiredCapacity)
 22            {
 023                newCapacity = (requiredCapacity + 1) & ~1;
 24            }
 025            return newCapacity;
 26        }
 27
 28        internal unsafe void ReplaceBufferInternal(char* newBuffer, int newLength)
 29        {
 030            ArgumentOutOfRangeException.ThrowIfGreaterThan(newLength, m_MaxCapacity, "capacity");
 31
 032            if (newLength > m_ChunkChars.Length)
 33            {
 034                m_ChunkChars = new char[GetReplaceBufferCapacity(newLength)];
 35            }
 36
 037            new Span<char>(newBuffer, newLength).CopyTo(m_ChunkChars);
 038            m_ChunkLength = newLength;
 039            m_ChunkPrevious = null;
 040            m_ChunkOffset = 0;
 041        }
 42
 43        internal void ReplaceBufferUtf8Internal(ReadOnlySpan<byte> source)
 44        {
 045            ArgumentOutOfRangeException.ThrowIfGreaterThan(source.Length, m_MaxCapacity, "capacity");
 46
 047            int numChars = Encoding.UTF8.GetCharCount(source);
 048            if (numChars > m_ChunkChars.Length)
 49            {
 050                m_ChunkChars = new char[GetReplaceBufferCapacity(numChars)];
 51            }
 52
 053            m_ChunkLength = Encoding.UTF8.GetChars(source, m_ChunkChars);
 054            m_ChunkPrevious = null;
 055            m_ChunkOffset = 0;
 056        }
 57
 58        internal unsafe void ReplaceBufferAnsiInternal(sbyte* newBuffer, int newLength)
 59        {
 060            ArgumentOutOfRangeException.ThrowIfGreaterThan(newLength, m_MaxCapacity, "capacity");
 61
 062            if (newLength > m_ChunkChars.Length)
 63            {
 064                m_ChunkChars = new char[GetReplaceBufferCapacity(newLength)];
 65            }
 66
 67            int convertedChars;
 68
 069            fixed (char* pChunkChars = m_ChunkChars)
 70            {
 71                // The incoming string buffer is supposed to have been populated by the
 72                // P/Invoke-called native function but there's no way to know if that really
 73                // happened, the native function might populate the buffer only in certain
 74                // circumstances (e.g. only if the function succeeds).
 75                //
 76                // As such, the buffer might contain bogus characters that cannot be converted
 77                // to Unicode and in that case conversion should not result in exceptions that
 78                // the managed caller does not expect. Instead, the caller is expected to know
 79                // when the resulting string is not valid and not use it.
 80                //
 81                // Both MultiByteToWideChar and the UTF8Encoding instance used on Unix-like
 82                // platforms default to replacing invalid characters with the Unicode replacement
 83                // character U+FFFD.
 84#if TARGET_WINDOWS
 085                convertedChars = Interop.Kernel32.MultiByteToWideChar(
 086                    Interop.Kernel32.CP_ACP,
 087                    Interop.Kernel32.MB_PRECOMPOSED,
 088                    (byte*)newBuffer,
 089                    newLength,
 090                    pChunkChars,
 091                    newLength);
 92#else
 93                convertedChars = Encoding.UTF8.GetChars((byte*)newBuffer, newLength, pChunkChars, newLength);
 94#endif
 95            }
 96
 097            m_ChunkOffset = 0;
 098            m_ChunkLength = convertedChars;
 099            m_ChunkPrevious = null;
 0100        }
 101
 102        /// <summary>
 103        /// Copies the contents of this builder to the specified buffer.
 104        /// </summary>
 105        /// <param name="dest">The destination buffer.</param>
 106        /// <param name="charLen">The number of chars in the destination buffer.</param>
 107        internal unsafe void InternalCopy(IntPtr dest, int charLen) =>
 0108            CopyTo(0, new Span<char>((char*)dest, charLen), charLen);
 109    }
 110}
 111

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.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.Collections;
 6using System.Collections.Generic;
 7using System.ComponentModel;
 8using System.Diagnostics;
 9using System.Diagnostics.CodeAnalysis;
 10using System.Runtime.CompilerServices;
 11using System.Runtime.InteropServices;
 12using System.Runtime.Serialization;
 13
 14namespace System.Text
 15{
 16    // This class represents a mutable string.  It is convenient for situations in
 17    // which it is desirable to modify a string, perhaps by removing, replacing, or
 18    // inserting characters, without creating a new String subsequent to
 19    // each modification.
 20    //
 21    // The methods contained within this class do not return a new StringBuilder
 22    // object unless specified otherwise.  This class may be used in conjunction with the String
 23    // class to carry out modifications upon strings.
 24    [Serializable]
 25    [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
 26    public sealed partial class StringBuilder : ISerializable
 27    {
 28        // A StringBuilder is internally represented as a linked list of blocks each of which holds
 29        // a chunk of the string.  It turns out string as a whole can also be represented as just a chunk,
 30        // so that is what we do.
 31
 32        /// <summary>
 33        /// The character buffer for this chunk.
 34        /// </summary>
 35        internal char[] m_ChunkChars;
 36
 37        /// <summary>
 38        /// The chunk that logically precedes this chunk.
 39        /// </summary>
 40        internal StringBuilder? m_ChunkPrevious;
 41
 42        /// <summary>
 43        /// The number of characters in this chunk.
 44        /// This is the number of elements in <see cref="m_ChunkChars"/> that are in use, from the start of the buffer.
 45        /// </summary>
 46        internal int m_ChunkLength;
 47
 48        /// <summary>
 49        /// The logical offset of this chunk's characters in the string it is a part of.
 50        /// This is the sum of the number of characters in preceding blocks.
 51        /// </summary>
 52        internal int m_ChunkOffset;
 53
 54        /// <summary>
 55        /// The maximum capacity this builder is allowed to have.
 56        /// </summary>
 57        internal int m_MaxCapacity;
 58
 59        /// <summary>
 60        /// The default capacity of a <see cref="StringBuilder"/>.
 61        /// </summary>
 62        internal const int DefaultCapacity = 16;
 63
 64        private const string CapacityField = "Capacity"; // Do not rename (binary serialization)
 65        private const string MaxCapacityField = "m_MaxCapacity"; // Do not rename (binary serialization)
 66        private const string StringValueField = "m_StringValue"; // Do not rename (binary serialization)
 67        private const string ThreadIDField = "m_currentThread"; // Do not rename (binary serialization)
 68
 69        // We want to keep chunk arrays out of large object heap (< 85K bytes ~ 40K chars) to be sure.
 70        // Making the maximum chunk size big means less allocation code called, but also more waste
 71        // in unused characters and slower inserts / replaces (since you do need to slide characters over
 72        // within a buffer).
 73        internal const int MaxChunkSize = 8000;
 74
 75        /// <summary>
 76        /// Initializes a new instance of the <see cref="StringBuilder"/> class.
 77        /// </summary>
 1678        public StringBuilder()
 79        {
 1680            m_MaxCapacity = int.MaxValue;
 1681            m_ChunkChars = new char[DefaultCapacity];
 1682        }
 83
 84        /// <summary>
 85        /// Initializes a new instance of the <see cref="StringBuilder"/> class.
 86        /// </summary>
 87        /// <param name="capacity">The initial capacity of this builder.</param>
 88        public StringBuilder(int capacity)
 089            : this(capacity, int.MaxValue)
 90        {
 091        }
 92
 93        /// <summary>
 94        /// Initializes a new instance of the <see cref="StringBuilder"/> class.
 95        /// </summary>
 96        /// <param name="value">The initial contents of this builder.</param>
 97        public StringBuilder(string? value)
 098            : this(value, DefaultCapacity)
 99        {
 0100        }
 101
 102        /// <summary>
 103        /// Initializes a new instance of the <see cref="StringBuilder"/> class.
 104        /// </summary>
 105        /// <param name="value">The initial contents of this builder.</param>
 106        /// <param name="capacity">The initial capacity of this builder.</param>
 107        public StringBuilder(string? value, int capacity)
 0108            : this(value, 0, value?.Length ?? 0, capacity)
 109        {
 0110        }
 111
 112        /// <summary>
 113        /// Initializes a new instance of the <see cref="StringBuilder"/> class.
 114        /// </summary>
 115        /// <param name="value">The initial contents of this builder.</param>
 116        /// <param name="startIndex">The index to start in <paramref name="value"/>.</param>
 117        /// <param name="length">The number of characters to read in <paramref name="value"/>.</param>
 118        /// <param name="capacity">The initial capacity of this builder.</param>
 0119        public StringBuilder(string? value, int startIndex, int length, int capacity)
 120        {
 0121            ArgumentOutOfRangeException.ThrowIfNegative(capacity);
 0122            ArgumentOutOfRangeException.ThrowIfNegative(length);
 0123            ArgumentOutOfRangeException.ThrowIfNegative(startIndex);
 124
 0125            value ??= string.Empty;
 126
 0127            if (startIndex > value.Length - length)
 128            {
 0129                throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexLength);
 130            }
 131
 0132            m_MaxCapacity = int.MaxValue;
 0133            if (capacity == 0)
 134            {
 0135                capacity = DefaultCapacity;
 136            }
 0137            capacity = Math.Max(capacity, length);
 138
 0139            m_ChunkChars = GC.AllocateUninitializedArray<char>(capacity);
 0140            m_ChunkLength = length;
 141
 0142            value.AsSpan(startIndex, length).CopyTo(m_ChunkChars);
 0143        }
 144
 145        /// <summary>
 146        /// Initializes a new instance of the <see cref="StringBuilder"/> class.
 147        /// </summary>
 148        /// <param name="capacity">The initial capacity of this builder.</param>
 149        /// <param name="maxCapacity">The maximum capacity of this builder.</param>
 0150        public StringBuilder(int capacity, int maxCapacity)
 151        {
 0152            if (capacity > maxCapacity)
 153            {
 0154                throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_Capacity);
 155            }
 0156            ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxCapacity);
 0157            ArgumentOutOfRangeException.ThrowIfNegative(capacity);
 158
 0159            if (capacity == 0)
 160            {
 0161                capacity = Math.Min(DefaultCapacity, maxCapacity);
 162            }
 163
 0164            m_MaxCapacity = maxCapacity;
 0165            m_ChunkChars = GC.AllocateUninitializedArray<char>(capacity);
 0166        }
 167
 0168        private StringBuilder(SerializationInfo info, StreamingContext context)
 169        {
 0170            ArgumentNullException.ThrowIfNull(info);
 171
 0172            int persistedCapacity = 0;
 0173            string? persistedString = null;
 0174            int persistedMaxCapacity = int.MaxValue;
 0175            bool capacityPresent = false;
 176
 177            // Get the data
 0178            SerializationInfoEnumerator enumerator = info.GetEnumerator();
 0179            while (enumerator.MoveNext())
 180            {
 0181                switch (enumerator.Name)
 182                {
 183                    case MaxCapacityField:
 0184                        persistedMaxCapacity = info.GetInt32(MaxCapacityField);
 0185                        break;
 186                    case StringValueField:
 0187                        persistedString = info.GetString(StringValueField);
 0188                        break;
 189                    case CapacityField:
 0190                        persistedCapacity = info.GetInt32(CapacityField);
 0191                        capacityPresent = true;
 192                        break;
 193                    default:
 194                        // Ignore other fields for forwards-compatibility.
 195                        break;
 196                }
 197            }
 198
 199            // Check values and set defaults
 0200            persistedString ??= string.Empty;
 0201            if (persistedMaxCapacity < 1 || persistedString.Length > persistedMaxCapacity)
 202            {
 0203                throw new SerializationException(SR.Serialization_StringBuilderMaxCapacity);
 204            }
 205
 0206            if (!capacityPresent)
 207            {
 208                // StringBuilder in V1.X did not persist the Capacity, so this is a valid legacy code path.
 0209                persistedCapacity = Math.Min(Math.Max(DefaultCapacity, persistedString.Length), persistedMaxCapacity);
 210            }
 211
 0212            if (persistedCapacity < 0 || persistedCapacity < persistedString.Length || persistedCapacity > persistedMaxC
 213            {
 0214                throw new SerializationException(SR.Serialization_StringBuilderCapacity);
 215            }
 216
 217            // Assign
 0218            m_MaxCapacity = persistedMaxCapacity;
 0219            m_ChunkChars = GC.AllocateUninitializedArray<char>(persistedCapacity);
 0220            persistedString.CopyTo(0, m_ChunkChars, 0, persistedString.Length);
 0221            m_ChunkLength = persistedString.Length;
 0222            AssertInvariants();
 0223        }
 224
 225        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
 226        {
 0227            ArgumentNullException.ThrowIfNull(info);
 228
 0229            AssertInvariants();
 0230            info.AddValue(MaxCapacityField, m_MaxCapacity);
 0231            info.AddValue(CapacityField, Capacity);
 0232            info.AddValue(StringValueField, ToString());
 233            // Note: persist "m_currentThread" to be compatible with old versions
 0234            info.AddValue(ThreadIDField, 0);
 0235        }
 236
 237        [Conditional("DEBUG")]
 238        private void AssertInvariants()
 239        {
 161240            Debug.Assert(m_ChunkOffset + m_ChunkChars.Length >= m_ChunkOffset, "The length of the string is greater than
 241
 161242            StringBuilder currentBlock = this;
 161243            int maxCapacity = this.m_MaxCapacity;
 235244            while (true)
 245            {
 246                // All blocks have the same max capacity.
 396247                Debug.Assert(currentBlock.m_MaxCapacity == maxCapacity);
 396248                Debug.Assert(currentBlock.m_ChunkChars != null);
 249
 396250                Debug.Assert(currentBlock.m_ChunkLength <= currentBlock.m_ChunkChars.Length);
 396251                Debug.Assert(currentBlock.m_ChunkLength >= 0);
 396252                Debug.Assert(currentBlock.m_ChunkOffset >= 0);
 253
 396254                StringBuilder? prevBlock = currentBlock.m_ChunkPrevious;
 396255                if (prevBlock == null)
 256                {
 161257                    Debug.Assert(currentBlock.m_ChunkOffset == 0);
 161258                    break;
 259                }
 260                // There are no gaps in the blocks.
 235261                Debug.Assert(currentBlock.m_ChunkOffset == prevBlock.m_ChunkOffset + prevBlock.m_ChunkLength);
 235262                currentBlock = prevBlock;
 263            }
 264        }
 265
 266        public int Capacity
 267        {
 37268            get => m_ChunkChars.Length + m_ChunkOffset;
 269            set
 270            {
 0271                ArgumentOutOfRangeException.ThrowIfNegative(value);
 0272                if (value > MaxCapacity)
 273                {
 0274                    throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_Capacity);
 275                }
 0276                if (value < Length)
 277                {
 0278                    throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity);
 279                }
 280
 0281                if (Capacity != value)
 282                {
 0283                    int newLen = value - m_ChunkOffset;
 0284                    char[] newArray = GC.AllocateUninitializedArray<char>(newLen);
 0285                    Array.Copy(m_ChunkChars, newArray, m_ChunkLength);
 0286                    m_ChunkChars = newArray;
 287                }
 0288            }
 289        }
 290
 291        /// <summary>
 292        /// Gets the maximum capacity this builder is allowed to have.
 293        /// </summary>
 0294        public int MaxCapacity => m_MaxCapacity;
 295
 296        /// <summary>
 297        /// Ensures that the capacity of this builder is at least the specified value.
 298        /// </summary>
 299        /// <param name="capacity">The new capacity for this builder.</param>
 300        /// <remarks>
 301        /// If <paramref name="capacity"/> is less than or equal to the current capacity of
 302        /// this builder, the capacity remains unchanged.
 303        /// </remarks>
 304        public int EnsureCapacity(int capacity)
 305        {
 0306            ArgumentOutOfRangeException.ThrowIfNegative(capacity);
 307
 0308            if (Capacity < capacity)
 309            {
 0310                Capacity = capacity;
 311            }
 0312            return Capacity;
 313        }
 314
 315        public override string ToString()
 316        {
 16317            AssertInvariants();
 318
 16319            if (Length == 0)
 320            {
 0321                return string.Empty;
 322            }
 323
 16324            string result = string.FastAllocateString(Length);
 16325            StringBuilder? chunk = this;
 326            do
 327            {
 53328                if (chunk.m_ChunkLength > 0)
 329                {
 330                    // Copy these into local variables so that they are stable even in the presence of race conditions
 53331                    char[] sourceArray = chunk.m_ChunkChars;
 53332                    int chunkOffset = chunk.m_ChunkOffset;
 53333                    int chunkLength = chunk.m_ChunkLength;
 334
 335                    // Check that we will not overrun our boundaries.
 53336                    if ((uint)(chunkLength + chunkOffset) > (uint)result.Length || (uint)chunkLength > (uint)sourceArray
 337                    {
 0338                        throw new ArgumentOutOfRangeException(null, SR.InvalidOperation_ConcurrentOperationsNotSupported
 339                    }
 340
 53341                    Buffer.Memmove(
 53342                        ref Unsafe.Add(ref result.GetRawStringData(), chunkOffset),
 53343                        ref MemoryMarshal.GetArrayDataReference(sourceArray),
 53344                        (nuint)chunkLength);
 345                }
 53346                chunk = chunk.m_ChunkPrevious;
 347            }
 53348            while (chunk != null);
 349
 16350            return result;
 351        }
 352
 353        /// <summary>
 354        /// Creates a string from a substring of this builder.
 355        /// </summary>
 356        /// <param name="startIndex">The index to start in this builder.</param>
 357        /// <param name="length">The number of characters to read in this builder.</param>
 358        public string ToString(int startIndex, int length)
 359        {
 0360            int currentLength = this.Length;
 0361            ArgumentOutOfRangeException.ThrowIfNegative(startIndex);
 0362            if (startIndex > currentLength)
 363            {
 0364                throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndexLargerThanLeng
 365            }
 0366            ArgumentOutOfRangeException.ThrowIfNegative(length);
 0367            if (startIndex > currentLength - length)
 368            {
 0369                throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexLength);
 370            }
 371
 0372            AssertInvariants();
 0373            string result = string.FastAllocateString(length);
 0374            CopyTo(startIndex, new Span<char>(ref result.GetRawStringData(), result.Length), result.Length);
 0375            return result;
 376        }
 377
 378        public StringBuilder Clear()
 379        {
 0380            this.Length = 0;
 0381            return this;
 382        }
 383
 384        /// <summary>
 385        /// Creates a new <see cref="StringBuilder"/> instance initialized to the same state as
 386        /// <paramref name="source"/>, and resets <paramref name="source"/> to an empty, usable state
 387        /// with no allocated buffers.
 388        /// </summary>
 389        /// <param name="source">The <see cref="StringBuilder"/> whose chunks should be moved to the
 390        /// returned instance.</param>
 391        /// <returns>A new <see cref="StringBuilder"/> instance that owns the chunks previously held
 392        /// by <paramref name="source"/>.</returns>
 393        /// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/>.</exception>
 394        /// <remarks>
 395        /// <para>
 396        /// In contrast to <see cref="Clear"/>, which retains the existing internal buffer,
 397        /// this method releases all internal buffers from <paramref name="source"/>. Ownership of
 398        /// the chunks is transferred in O(1) to the returned <see cref="StringBuilder"/>; the
 399        /// underlying character data is not copied.
 400        /// </para>
 401        /// <para>
 402        /// After the call, <paramref name="source"/> has <see cref="Length"/> and
 403        /// <see cref="Capacity"/> of zero but retains its original <see cref="MaxCapacity"/>.
 404        /// It remains fully usable; subsequent append or insert operations will allocate new
 405        /// buffers as needed.
 406        /// </para>
 407        /// </remarks>
 408        public static StringBuilder MoveChunks(StringBuilder source)
 409        {
 0410            ArgumentNullException.ThrowIfNull(source);
 411
 0412            StringBuilder destination = new StringBuilder(source);
 413
 0414            source.m_ChunkChars = [];
 0415            source.m_ChunkPrevious = null;
 0416            source.m_ChunkLength = 0;
 0417            source.m_ChunkOffset = 0;
 418
 0419            return destination;
 420        }
 421
 422        /// <summary>
 423        /// Gets or sets the length of this builder.
 424        /// </summary>
 425        public int Length
 426        {
 214427            get => m_ChunkOffset + m_ChunkLength;
 428            set
 429            {
 430                // If the new length is less than 0 or greater than our Maximum capacity, bail.
 0431                ArgumentOutOfRangeException.ThrowIfNegative(value);
 432
 0433                if (value > MaxCapacity)
 434                {
 0435                    throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity);
 436                }
 437
 0438                if (value == 0 && m_ChunkPrevious == null)
 439                {
 0440                    m_ChunkLength = 0;
 0441                    m_ChunkOffset = 0;
 0442                    return;
 443                }
 444
 0445                int delta = value - Length;
 0446                if (delta > 0)
 447                {
 448                    // Pad ourselves with null characters.
 0449                    Append('\0', delta);
 450                }
 451                else
 452                {
 0453                    StringBuilder chunk = FindChunkForIndex(value);
 0454                    if (chunk != this)
 455                    {
 456                        // Avoid possible infinite capacity growth.  See https://github.com/dotnet/coreclr/pull/16926
 0457                        int capacityToPreserve = Math.Min(Capacity, Math.Max(Length * 6 / 5, m_ChunkChars.Length));
 0458                        int newLen = capacityToPreserve - chunk.m_ChunkOffset;
 0459                        if (newLen > chunk.m_ChunkChars.Length)
 460                        {
 461                            // We crossed a chunk boundary when reducing the Length. We must replace this middle-chunk w
 462                            // to ensure the capacity we want is preserved.
 0463                            char[] newArray = GC.AllocateUninitializedArray<char>(newLen);
 0464                            Array.Copy(chunk.m_ChunkChars, newArray, chunk.m_ChunkLength);
 0465                            m_ChunkChars = newArray;
 466                        }
 467                        else
 468                        {
 469                            // Special case where the capacity we want to keep corresponds exactly to the size of the co
 470                            // Just take ownership of the array.
 0471                            Debug.Assert(newLen == chunk.m_ChunkChars.Length, "The new chunk should be larger or equal t
 0472                            m_ChunkChars = chunk.m_ChunkChars;
 473                        }
 474
 0475                        m_ChunkPrevious = chunk.m_ChunkPrevious;
 0476                        m_ChunkOffset = chunk.m_ChunkOffset;
 477                    }
 0478                    m_ChunkLength = value - chunk.m_ChunkOffset;
 0479                    AssertInvariants();
 480                }
 0481                Debug.Assert(Length == value, "Something went wrong setting Length.");
 0482            }
 483        }
 484
 485        [IndexerName("Chars")]
 486        public char this[int index]
 487        {
 488            get
 489            {
 0490                if ((uint)index >= (uint)Length)
 491                {
 0492                    ThrowHelper.ThrowIndexOutOfRangeException();
 493                }
 494
 0495                StringBuilder chunk = FindChunkForIndex(index);
 0496                return chunk.m_ChunkChars[index - chunk.m_ChunkOffset];
 497            }
 498            set
 499            {
 0500                if ((uint)index >= (uint)Length)
 501                {
 0502                    ThrowHelper.ThrowArgumentOutOfRange_IndexMustBeLessException();
 503                }
 504
 0505                StringBuilder chunk = FindChunkForIndex(index);
 0506                chunk.m_ChunkChars[index - chunk.m_ChunkOffset] = value;
 0507            }
 508        }
 509
 510        /// <summary>
 511        /// GetChunks returns ChunkEnumerator that follows the IEnumerable pattern and
 512        /// thus can be used in a C# 'foreach' statements to retrieve the data in the StringBuilder
 513        /// as chunks (ReadOnlyMemory) of characters.  An example use is:
 514        ///
 515        ///      foreach (ReadOnlyMemory&lt;char&gt; chunk in sb.GetChunks())
 516        ///         foreach (char c in chunk.Span)
 517        ///             { /* operation on c }
 518        ///
 519        /// It is undefined what happens if the StringBuilder is modified while the chunk
 520        /// enumeration is incomplete.  StringBuilder is also not thread-safe, so operating
 521        /// on it with concurrent threads is illegal.  Finally the ReadOnlyMemory chunks returned
 522        /// are NOT guaranteed to remain unchanged if the StringBuilder is modified, so do
 523        /// not cache them for later use either.  This API's purpose is efficiently extracting
 524        /// the data of a CONSTANT StringBuilder.
 525        ///
 526        /// Creating a ReadOnlySpan from a ReadOnlyMemory  (the .Span property) is expensive
 527        /// compared to the fetching of the character, so create a local variable for the SPAN
 528        /// if you need to use it in a nested for statement.  For example
 529        ///
 530        ///    foreach (ReadOnlyMemory&lt;char&gt; chunk in sb.GetChunks())
 531        ///    {
 532        ///         var span = chunk.Span;
 533        ///         for (int i = 0; i &lt; span.Length; i++)
 534        ///             { /* operation on span[i] */ }
 535        ///    }
 536        /// </summary>
 0537        public ChunkEnumerator GetChunks() => new ChunkEnumerator(this);
 538
 539        /// <summary>
 540        /// ChunkEnumerator supports both the IEnumerable and IEnumerator pattern so foreach
 541        /// works (see GetChunks).  It needs to be public (so the compiler can use it
 542        /// when building a foreach statement) but users typically don't use it explicitly.
 543        /// (which is why it is a nested type).
 544        /// </summary>
 545        public struct ChunkEnumerator
 546        {
 547            private readonly StringBuilder _firstChunk; // The first Stringbuilder chunk (which is the end of the logica
 548            private StringBuilder? _currentChunk;        // The chunk that this enumerator is currently returning (Curre
 549            private readonly ManyChunkInfo? _manyChunks; // Only used for long string builders with many chunks (see con
 550
 551            /// <summary>
 552            /// Implement IEnumerable.GetEnumerator() to return  'this' as the IEnumerator
 553            /// </summary>
 554            [EditorBrowsable(EditorBrowsableState.Never)] // Only here to make foreach work
 0555            public ChunkEnumerator GetEnumerator() { return this; }
 556
 557            /// <summary>
 558            /// Implements the IEnumerator pattern.
 559            /// </summary>
 560            public bool MoveNext()
 561            {
 0562                if (_currentChunk == _firstChunk)
 563                {
 0564                    return false;
 565                }
 566
 567
 0568                if (_manyChunks != null)
 569                {
 0570                    return _manyChunks.MoveNext(ref _currentChunk);
 571                }
 572
 0573                StringBuilder next = _firstChunk;
 0574                while (next.m_ChunkPrevious != _currentChunk)
 575                {
 0576                    Debug.Assert(next.m_ChunkPrevious != null);
 0577                    next = next.m_ChunkPrevious;
 578                }
 0579                _currentChunk = next;
 0580                return true;
 581            }
 582
 583            /// <summary>
 584            /// Implements the IEnumerator pattern.
 585            /// </summary>
 586            public ReadOnlyMemory<char> Current
 587            {
 588                get
 589                {
 0590                    if (_currentChunk == null)
 591                    {
 0592                        ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
 593                    }
 594
 0595                    return new ReadOnlyMemory<char>(_currentChunk.m_ChunkChars, 0, _currentChunk.m_ChunkLength);
 596                }
 597            }
 598
 599            #region private
 600            internal ChunkEnumerator(StringBuilder stringBuilder)
 601            {
 0602                Debug.Assert(stringBuilder != null);
 0603                _firstChunk = stringBuilder;
 0604                _currentChunk = null;   // MoveNext will find the last chunk if we do this.
 0605                _manyChunks = null;
 606
 607                // There is a performance-vs-allocation tradeoff.   Because the chunks
 608                // are a linked list with each chunk pointing to its PREDECESSOR, walking
 609                // the list FORWARD is not efficient.   If there are few chunks (< 8) we
 610                // simply scan from the start each time, and tolerate the N*N behavior.
 611                // However above this size, we allocate an array to hold reference to all
 612                // the chunks and we can be efficient for large N.
 0613                int chunkCount = ChunkCount(stringBuilder);
 0614                if (8 < chunkCount)
 615                {
 0616                    _manyChunks = new ManyChunkInfo(stringBuilder, chunkCount);
 617                }
 0618            }
 619
 620            private static int ChunkCount(StringBuilder? stringBuilder)
 621            {
 0622                int ret = 0;
 0623                while (stringBuilder != null)
 624                {
 0625                    ret++;
 0626                    stringBuilder = stringBuilder.m_ChunkPrevious;
 627                }
 0628                return ret;
 629            }
 630
 631            /// <summary>
 632            /// Used to hold all the chunks indexes when you have many chunks.
 633            /// </summary>
 634            private sealed class ManyChunkInfo
 635            {
 636                private readonly StringBuilder[] _chunks;    // These are in normal order (first chunk first)
 637                private int _chunkPos;
 638
 639                public bool MoveNext(ref StringBuilder? current)
 640                {
 0641                    int pos = ++_chunkPos;
 0642                    if (_chunks.Length <= pos)
 643                    {
 0644                        return false;
 645                    }
 0646                    current = _chunks[pos];
 0647                    return true;
 648                }
 649
 0650                public ManyChunkInfo(StringBuilder? stringBuilder, int chunkCount)
 651                {
 0652                    _chunks = new StringBuilder[chunkCount];
 0653                    while (0 <= --chunkCount)
 654                    {
 0655                        Debug.Assert(stringBuilder != null);
 0656                        _chunks[chunkCount] = stringBuilder;
 0657                        stringBuilder = stringBuilder.m_ChunkPrevious;
 658                    }
 0659                    _chunkPos = -1;
 0660                }
 661            }
 662#endregion
 663        }
 664
 665        /// <summary>
 666        /// Returns an enumeration of <see cref="Rune"/> from this builder.
 667        /// </summary>
 668        /// <remarks>
 669        /// Invalid sequences will be represented in the enumeration by <see cref="Rune.ReplacementChar"/>.
 670        /// </remarks>
 0671        public StringBuilderRuneEnumerator EnumerateRunes() => new StringBuilderRuneEnumerator(this);
 672
 673        /// <summary>
 674        /// Appends a character 0 or more times to the end of this builder.
 675        /// </summary>
 676        /// <param name="value">The character to append.</param>
 677        /// <param name="repeatCount">The number of times to append <paramref name="value"/>.</param>
 678        public StringBuilder Append(char value, int repeatCount)
 679        {
 0680            ArgumentOutOfRangeException.ThrowIfNegative(repeatCount);
 681
 0682            if (repeatCount == 0)
 683            {
 0684                return this;
 685            }
 686
 0687            char[] chunkChars = m_ChunkChars;
 0688            int chunkLength = m_ChunkLength;
 689
 690            // Try to fit the whole repeatCount in the current chunk
 691            // Use the same check as Span<T>.Slice for 64-bit so it can be folded
 692            // Since repeatCount can't be negative, there's no risk for it to overflow on 32 bit
 0693            if (((nuint)(uint)chunkLength + (nuint)(uint)repeatCount) <= (nuint)(uint)chunkChars.Length)
 694            {
 0695                chunkChars.AsSpan(chunkLength, repeatCount).Fill(value);
 0696                m_ChunkLength += repeatCount;
 697            }
 698            else
 699            {
 0700                AppendWithExpansion(value, repeatCount);
 701            }
 702
 0703            AssertInvariants();
 0704            return this;
 705        }
 706
 707        private void AppendWithExpansion(char value, int repeatCount)
 708        {
 0709            Debug.Assert(repeatCount > 0, "Invalid length; should have been validated by caller.");
 710
 711            // Check if the repeatCount will put us over m_MaxCapacity
 0712            if ((uint)(repeatCount + Length) > (uint)m_MaxCapacity)
 713            {
 0714                throw new ArgumentOutOfRangeException(nameof(repeatCount), SR.ArgumentOutOfRange_LengthGreaterThanCapaci
 715            }
 716
 0717            char[] chunkChars = m_ChunkChars;
 0718            int chunkLength = m_ChunkLength;
 719
 720            // Fill the rest of the current chunk
 0721            int firstLength = chunkChars.Length - chunkLength;
 0722            if (firstLength > 0)
 723            {
 0724                chunkChars.AsSpan(chunkLength, firstLength).Fill(value);
 0725                m_ChunkLength = chunkChars.Length;
 726            }
 727
 728            // Expand the builder to add another chunk
 0729            int restLength = repeatCount - firstLength;
 0730            ExpandByABlock(restLength);
 0731            Debug.Assert(m_ChunkLength == 0, "A new block was not created.");
 732
 733            // Fill the new chunk with the remaining part of repeatCount
 0734            m_ChunkChars.AsSpan(0, restLength).Fill(value);
 0735            m_ChunkLength = restLength;
 0736        }
 737
 738        /// <summary>
 739        /// Appends a range of characters to the end of this builder.
 740        /// </summary>
 741        /// <param name="value">The characters to append.</param>
 742        /// <param name="startIndex">The index to start in <paramref name="value"/>.</param>
 743        /// <param name="charCount">The number of characters to read in <paramref name="value"/>.</param>
 744        public StringBuilder Append(char[]? value, int startIndex, int charCount)
 745        {
 0746            ArgumentOutOfRangeException.ThrowIfNegative(startIndex);
 0747            ArgumentOutOfRangeException.ThrowIfNegative(charCount);
 748
 0749            if (value == null)
 750            {
 0751                if (startIndex == 0 && charCount == 0)
 752                {
 0753                    return this;
 754                }
 755
 0756                ArgumentNullException.Throw(nameof(value));
 757            }
 0758            if (charCount > value.Length - startIndex)
 759            {
 0760                throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
 761            }
 762
 0763            if (charCount != 0)
 764            {
 0765                Append(ref value[startIndex], charCount);
 766            }
 767
 0768            return this;
 769        }
 770
 771        /// <summary>
 772        /// Appends a string to the end of this builder.
 773        /// </summary>
 774        /// <param name="value">The string to append.</param>
 775        public StringBuilder Append(string? value)
 776        {
 43777            if (value is not null)
 778            {
 43779                Append(ref value.GetRawStringData(), value.Length);
 780            }
 781
 43782            return this;
 783        }
 784
 785        /// <summary>
 786        /// Appends part of a string to the end of this builder.
 787        /// </summary>
 788        /// <param name="value">The string to append.</param>
 789        /// <param name="startIndex">The index to start in <paramref name="value"/>.</param>
 790        /// <param name="count">The number of characters to read in <paramref name="value"/>.</param>
 791        public StringBuilder Append(string? value, int startIndex, int count)
 792        {
 116793            ArgumentOutOfRangeException.ThrowIfNegative(startIndex);
 116794            ArgumentOutOfRangeException.ThrowIfNegative(count);
 795
 116796            if (value == null)
 797            {
 0798                if (startIndex == 0 && count == 0)
 799                {
 0800                    return this;
 801                }
 0802                ArgumentNullException.Throw(nameof(value));
 803            }
 804
 116805            if (count != 0)
 806            {
 99807                if (startIndex > value.Length - count)
 808                {
 0809                    throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqu
 810                }
 811
 99812                Append(ref Unsafe.Add(ref value.GetRawStringData(), startIndex), count);
 813            }
 814
 116815            return this;
 816        }
 817
 818        public StringBuilder Append(StringBuilder? value)
 819        {
 0820            if (value != null && value.Length != 0)
 821            {
 0822                return AppendCore(value, 0, value.Length);
 823            }
 0824            return this;
 825        }
 826
 827        public StringBuilder Append(StringBuilder? value, int startIndex, int count)
 828        {
 0829            ArgumentOutOfRangeException.ThrowIfNegative(startIndex);
 0830            ArgumentOutOfRangeException.ThrowIfNegative(count);
 831
 0832            if (value == null)
 833            {
 0834                if (startIndex == 0 && count == 0)
 835                {
 0836                    return this;
 837                }
 0838                ArgumentNullException.Throw(nameof(value));
 839            }
 840
 0841            if (count == 0)
 842            {
 0843                return this;
 844            }
 845
 0846            if (count > value.Length - startIndex)
 847            {
 0848                throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
 849            }
 850
 0851            return AppendCore(value, startIndex, count);
 852        }
 853
 854        private StringBuilder AppendCore(StringBuilder value, int startIndex, int count)
 855        {
 0856            if (value == this)
 857            {
 0858                return Append(value.ToString(startIndex, count));
 859            }
 860
 0861            int newLength = Length + count;
 862
 0863            if ((uint)newLength > (uint)m_MaxCapacity)
 864            {
 0865                throw new ArgumentOutOfRangeException(nameof(Capacity), SR.ArgumentOutOfRange_Capacity);
 866            }
 867
 0868            while (count > 0)
 869            {
 0870                int length = Math.Min(m_ChunkChars.Length - m_ChunkLength, count);
 0871                if (length == 0)
 872                {
 0873                    ExpandByABlock(count);
 0874                    Debug.Assert(m_ChunkLength == 0 && m_ChunkChars.Length >= count);
 0875                    length = count;
 876                }
 0877                value.CopyTo(startIndex, new Span<char>(m_ChunkChars, m_ChunkLength, length), length);
 878
 0879                m_ChunkLength += length;
 0880                startIndex += length;
 0881                count -= length;
 882            }
 883
 0884            return this;
 885        }
 886
 0887        public StringBuilder AppendLine() => Append(Environment.NewLine);
 888
 889        public StringBuilder AppendLine(string? value)
 890        {
 0891            Append(value);
 0892            return Append(Environment.NewLine);
 893        }
 894
 895        public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
 896        {
 0897            ArgumentNullException.ThrowIfNull(destination);
 898
 0899            ArgumentOutOfRangeException.ThrowIfNegative(destinationIndex);
 900
 0901            if (destinationIndex > destination.Length - count)
 902            {
 0903                throw new ArgumentException(SR.ArgumentOutOfRange_OffsetOut);
 904            }
 905
 0906            CopyTo(sourceIndex, new Span<char>(destination).Slice(destinationIndex), count);
 0907        }
 908
 909        public void CopyTo(int sourceIndex, Span<char> destination, int count)
 910        {
 0911            ArgumentOutOfRangeException.ThrowIfNegative(count);
 912
 0913            if ((uint)sourceIndex > (uint)Length)
 914            {
 0915                throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual)
 916            }
 917
 0918            if (sourceIndex > Length - count)
 919            {
 0920                throw new ArgumentException(SR.Arg_LongerThanSrcString);
 921            }
 922
 0923            AssertInvariants();
 924
 0925            StringBuilder? chunk = this;
 0926            int sourceEndIndex = sourceIndex + count;
 0927            int curDestIndex = count;
 0928            while (count > 0)
 929            {
 0930                Debug.Assert(chunk != null);
 0931                int chunkEndIndex = sourceEndIndex - chunk.m_ChunkOffset;
 0932                if (chunkEndIndex >= 0)
 933                {
 0934                    chunkEndIndex = Math.Min(chunkEndIndex, chunk.m_ChunkLength);
 935
 0936                    int chunkCount = count;
 0937                    int chunkStartIndex = chunkEndIndex - count;
 0938                    if (chunkStartIndex < 0)
 939                    {
 0940                        chunkCount += chunkStartIndex;
 0941                        chunkStartIndex = 0;
 942                    }
 0943                    curDestIndex -= chunkCount;
 0944                    count -= chunkCount;
 945
 0946                    new ReadOnlySpan<char>(chunk.m_ChunkChars, chunkStartIndex, chunkCount).CopyTo(destination.Slice(cur
 947                }
 0948                chunk = chunk.m_ChunkPrevious;
 949            }
 0950        }
 951
 952        /// <summary>
 953        /// Inserts a string 0 or more times into this builder at the specified position.
 954        /// </summary>
 955        /// <param name="index">The index to insert in this builder.</param>
 956        /// <param name="value">The string to insert.</param>
 957        /// <param name="count">The number of times to insert the string.</param>
 0958        public StringBuilder Insert(int index, string? value, int count) => Insert(index, value.AsSpan(), count);
 959
 960        private StringBuilder Insert(int index, ReadOnlySpan<char> value, int count)
 961        {
 0962            ArgumentOutOfRangeException.ThrowIfNegative(count);
 963
 0964            int currentLength = Length;
 0965            if ((uint)index > (uint)currentLength)
 966            {
 0967                throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
 968            }
 969
 0970            if (value.IsEmpty || count == 0)
 971            {
 0972                return this;
 973            }
 974
 975            // Ensure we don't insert more chars than we can hold, and we don't
 976            // have any integer overflow in our new length.
 0977            long insertingChars = (long)value.Length * count;
 0978            if (insertingChars > MaxCapacity - this.Length)
 979            {
 0980                throw new OutOfMemoryException();
 981            }
 0982            Debug.Assert(insertingChars + this.Length < int.MaxValue);
 983
 0984            MakeRoom(index, (int)insertingChars, out StringBuilder chunk, out int indexInChunk, false);
 985
 0986            while (count > 0)
 987            {
 0988                ReplaceInPlaceAtChunk(ref chunk!, ref indexInChunk, ref MemoryMarshal.GetReference(value), value.Length)
 0989                --count;
 990            }
 991
 0992            return this;
 993        }
 994
 995        /// <summary>
 996        /// Removes a range of characters from this builder.
 997        /// </summary>
 998        /// <remarks>
 999        /// This method does not reduce the capacity of this builder.
 1000        /// </remarks>
 1001        public StringBuilder Remove(int startIndex, int length)
 1002        {
 01003            ArgumentOutOfRangeException.ThrowIfNegative(length);
 01004            ArgumentOutOfRangeException.ThrowIfNegative(startIndex);
 01005            if (length > Length - startIndex)
 1006            {
 01007                throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
 1008            }
 1009
 01010            if (Length == length && startIndex == 0)
 1011            {
 01012                Length = 0;
 01013                return this;
 1014            }
 1015
 01016            if (length > 0)
 1017            {
 01018                Remove(startIndex, length, out _, out _);
 1019            }
 1020
 01021            return this;
 1022        }
 1023
 1024#pragma warning disable CA1830 // Prefer strongly-typed Append and Insert method overloads on StringBuilder. No need to 
 01025        public StringBuilder Append(bool value) => Append(value.ToString());
 1026#pragma warning restore CA1830
 1027
 1028        public StringBuilder Append(char value)
 1029        {
 581030            int nextCharIndex = m_ChunkLength;
 581031            char[] chars = m_ChunkChars;
 1032
 581033            if ((uint)chars.Length > (uint)nextCharIndex)
 1034            {
 551035                chars[nextCharIndex] = value;
 551036                m_ChunkLength++;
 1037            }
 1038            else
 1039            {
 31040                AppendWithExpansion(value);
 1041            }
 1042
 581043            return this;
 1044        }
 1045
 1046        [MethodImpl(MethodImplOptions.NoInlining)]
 1047        private void AppendWithExpansion(char value)
 1048        {
 31049            ExpandByABlock(1);
 31050            Debug.Assert(m_ChunkLength == 0, "A new block was not created.");
 31051            m_ChunkChars[0] = value;
 31052            m_ChunkLength++;
 31053        }
 1054
 1055        /// <summary>
 1056        /// Appends the string representation of a specified <see cref="Rune"/> to this instance.
 1057        /// </summary>
 1058        /// <param name="value">The UTF-32-encoded code unit to append.</param>
 1059        /// <returns>A reference to this instance after the append operation has completed.</returns>
 1060        public unsafe StringBuilder Append(Rune value)
 1061        {
 1062            // Convert value to span
 01063            ReadOnlySpan<char> valueChars = value.AsSpan(stackalloc char[Rune.MaxUtf16CharsPerRune]);
 1064
 1065            // Append span
 01066            return Append(valueChars);
 1067        }
 1068
 1069        [CLSCompliant(false)]
 01070        public StringBuilder Append(sbyte value) => AppendSpanFormattable(value);
 1071
 01072        public StringBuilder Append(byte value) => AppendSpanFormattable(value);
 1073
 01074        public StringBuilder Append(short value) => AppendSpanFormattable(value);
 1075
 581076        public StringBuilder Append(int value) => AppendSpanFormattable(value);
 1077
 01078        public StringBuilder Append(long value) => AppendSpanFormattable(value);
 1079
 01080        public StringBuilder Append(float value) => AppendSpanFormattable(value);
 1081
 01082        public StringBuilder Append(double value) => AppendSpanFormattable(value);
 1083
 01084        public StringBuilder Append(decimal value) => AppendSpanFormattable(value);
 1085
 1086        [CLSCompliant(false)]
 01087        public StringBuilder Append(ushort value) => AppendSpanFormattable(value);
 1088
 1089        [CLSCompliant(false)]
 01090        public StringBuilder Append(uint value) => AppendSpanFormattable(value);
 1091
 1092        [CLSCompliant(false)]
 01093        public StringBuilder Append(ulong value) => AppendSpanFormattable(value);
 1094
 1095        private StringBuilder AppendSpanFormattable<T>(T value) where T : ISpanFormattable
 1096        {
 581097            Debug.Assert(typeof(T).Assembly.Equals(typeof(object).Assembly), "Implementation trusts the results of TryFo
 1098
 581099            if (value.TryFormat(RemainingCurrentChunk, out int charsWritten, format: default, provider: null))
 1100            {
 571101                m_ChunkLength += charsWritten;
 571102                return this;
 1103            }
 1104
 11105            return Append(value.ToString());
 1106        }
 1107
 1108        internal StringBuilder AppendSpanFormattable<T>(T value, string? format, IFormatProvider? provider) where T : IS
 1109        {
 1110            Debug.Assert(typeof(T).Assembly.Equals(typeof(object).Assembly), "Implementation trusts the results of TryFo
 1111
 1112            if (value.TryFormat(RemainingCurrentChunk, out int charsWritten, format, provider))
 1113            {
 1114                m_ChunkLength += charsWritten;
 1115                return this;
 1116            }
 1117
 1118            return Append(value.ToString(format, provider));
 1119        }
 1120
 01121        public StringBuilder Append(object? value) => (value == null) ? this : Append(value.ToString());
 1122
 1123        public StringBuilder Append(char[]? value)
 1124        {
 01125            if (value is not null)
 1126            {
 01127                Append(ref MemoryMarshal.GetArrayDataReference(value), value.Length);
 1128            }
 1129
 01130            return this;
 1131        }
 1132
 1133        public StringBuilder Append(ReadOnlySpan<char> value)
 1134        {
 01135            Append(ref MemoryMarshal.GetReference(value), value.Length);
 01136            return this;
 1137        }
 1138
 01139        public StringBuilder Append(ReadOnlyMemory<char> value) => Append(value.Span);
 1140
 1141        /// <summary>Appends the specified interpolated string to this instance.</summary>
 1142        /// <param name="handler">The interpolated string to append.</param>
 1143        /// <returns>A reference to this instance after the append operation has completed.</returns>
 01144        public StringBuilder Append([InterpolatedStringHandlerArgument("")] ref AppendInterpolatedStringHandler handler)
 1145
 1146        /// <summary>Appends the specified interpolated string to this instance.</summary>
 1147        /// <param name="provider">An object that supplies culture-specific formatting information.</param>
 1148        /// <param name="handler">The interpolated string to append.</param>
 1149        /// <returns>A reference to this instance after the append operation has completed.</returns>
 01150        public StringBuilder Append(IFormatProvider? provider, [InterpolatedStringHandlerArgument("", nameof(provider))]
 1151
 1152        /// <summary>Appends the specified interpolated string followed by the default line terminator to the end of the
 1153        /// <param name="handler">The interpolated string to append.</param>
 1154        /// <returns>A reference to this instance after the append operation has completed.</returns>
 01155        public StringBuilder AppendLine([InterpolatedStringHandlerArgument("")] ref AppendInterpolatedStringHandler hand
 1156
 1157        /// <summary>Appends the specified interpolated string followed by the default line terminator to the end of the
 1158        /// <param name="provider">An object that supplies culture-specific formatting information.</param>
 1159        /// <param name="handler">The interpolated string to append.</param>
 1160        /// <returns>A reference to this instance after the append operation has completed.</returns>
 01161        public StringBuilder AppendLine(IFormatProvider? provider, [InterpolatedStringHandlerArgument("", nameof(provide
 1162
 1163        #region AppendJoin
 1164
 1165        public StringBuilder AppendJoin(string? separator, params object?[] values)
 1166        {
 01167            if (values is null)
 1168            {
 01169                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values);
 1170            }
 1171
 01172            separator ??= string.Empty;
 01173            return AppendJoinCore(ref separator.GetRawStringData(), separator.Length, values);
 1174        }
 1175
 1176        /// <summary>
 1177        /// Concatenates the string representations of the elements in the provided span of objects, using the specified
 1178        /// then appends the result to the current instance of the string builder.
 1179        /// </summary>
 1180        /// <param name="separator">The string to use as a separator. <paramref name="separator"/> is included in the jo
 1181        /// <param name="values">A span that contains the strings to concatenate and append to the current instance of t
 1182        /// <returns>A reference to this instance after the append operation has completed.</returns>
 1183        public StringBuilder AppendJoin(string? separator, params ReadOnlySpan<object?> values)
 1184        {
 01185            separator ??= string.Empty;
 01186            return AppendJoinCore(ref separator.GetRawStringData(), separator.Length, values);
 1187        }
 1188
 1189        public StringBuilder AppendJoin<T>(string? separator, IEnumerable<T> values)
 1190        {
 01191            if (values is null)
 1192            {
 01193                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values);
 1194            }
 1195
 01196            separator ??= string.Empty;
 01197            return AppendJoinCore(ref separator.GetRawStringData(), separator.Length, values);
 1198        }
 1199
 1200        public StringBuilder AppendJoin(string? separator, params string?[] values)
 1201        {
 01202            if (values is null)
 1203            {
 01204                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values);
 1205            }
 1206
 01207            separator ??= string.Empty;
 01208            return AppendJoinCore(ref separator.GetRawStringData(), separator.Length, values);
 1209        }
 1210
 1211        /// <summary>
 1212        /// Concatenates the strings of the provided span, using the specified separator between each string,
 1213        /// then appends the result to the current instance of the string builder.
 1214        /// </summary>
 1215        /// <param name="separator">The string to use as a separator. <paramref name="separator"/> is included in the jo
 1216        /// <param name="values">A span that contains the strings to concatenate and append to the current instance of t
 1217        /// <returns>A reference to this instance after the append operation has completed.</returns>
 1218        public StringBuilder AppendJoin(string? separator, params ReadOnlySpan<string?> values)
 1219        {
 01220            separator ??= string.Empty;
 01221            return AppendJoinCore(ref separator.GetRawStringData(), separator.Length, values);
 1222        }
 1223
 1224        public StringBuilder AppendJoin(char separator, params object?[] values)
 1225        {
 01226            if (values is null)
 1227            {
 01228                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values);
 1229            }
 1230
 01231            return AppendJoinCore(ref separator, 1, (ReadOnlySpan<object?>)values);
 1232        }
 1233
 1234        /// <summary>
 1235        /// Concatenates the string representations of the elements in the provided span of objects, using the specified
 1236        /// then appends the result to the current instance of the string builder.
 1237        /// </summary>
 1238        /// <param name="separator">The character to use as a separator. <paramref name="separator"/> is included in the
 1239        /// <param name="values">A span that contains the strings to concatenate and append to the current instance of t
 1240        /// <returns>A reference to this instance after the append operation has completed.</returns>
 1241        public StringBuilder AppendJoin(char separator, params ReadOnlySpan<object?> values) =>
 01242            AppendJoinCore(ref separator, 1, values);
 1243
 1244        public StringBuilder AppendJoin<T>(char separator, IEnumerable<T> values)
 1245        {
 01246            if (values is null)
 1247            {
 01248                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values);
 1249            }
 1250
 01251            return AppendJoinCore(ref separator, 1, values);
 1252        }
 1253
 1254        public StringBuilder AppendJoin(char separator, params string?[] values)
 1255        {
 01256            if (values is null)
 1257            {
 01258                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values);
 1259            }
 1260
 01261            return AppendJoinCore(ref separator, 1, (ReadOnlySpan<string?>)values);
 1262        }
 1263
 1264        /// <summary>
 1265        /// Concatenates the strings of the provided span, using the specified char separator between each string,
 1266        /// then appends the result to the current instance of the string builder.
 1267        /// </summary>
 1268        /// <param name="separator">The character to use as a separator. <paramref name="separator"/> is included in the
 1269        /// <param name="values">A span that contains the strings to concatenate and append to the current instance of t
 1270        /// <returns>A reference to this instance after the append operation has completed.</returns>
 1271        public StringBuilder AppendJoin(char separator, params ReadOnlySpan<string?> values) =>
 01272            AppendJoinCore(ref separator, 1, values);
 1273
 1274        private StringBuilder AppendJoinCore<T>(ref char separator, int separatorLength, IEnumerable<T> values)
 1275        {
 01276            Debug.Assert(values != null);
 01277            Debug.Assert(!Unsafe.IsNullRef(ref separator));
 01278            Debug.Assert(separatorLength >= 0);
 1279
 01280            using (IEnumerator<T> en = values.GetEnumerator())
 1281            {
 01282                if (!en.MoveNext())
 1283                {
 01284                    return this;
 1285                }
 1286
 01287                T value = en.Current;
 01288                if (value != null)
 1289                {
 01290                    Append(value.ToString());
 1291                }
 1292
 01293                while (en.MoveNext())
 1294                {
 01295                    Append(ref separator, separatorLength);
 01296                    value = en.Current;
 01297                    if (value != null)
 1298                    {
 01299                        Append(value.ToString());
 1300                    }
 1301                }
 01302            }
 01303            return this;
 01304        }
 1305
 1306        private StringBuilder AppendJoinCore<T>(ref char separator, int separatorLength, ReadOnlySpan<T> values)
 1307        {
 01308            if (values.IsEmpty)
 1309            {
 01310                return this;
 1311            }
 1312
 01313            if (values[0] != null)
 1314            {
 01315                Append(values[0]!.ToString());
 1316            }
 1317
 01318            for (int i = 1; i < values.Length; i++)
 1319            {
 01320                Append(ref separator, separatorLength);
 01321                if (values[i] != null)
 1322                {
 01323                    Append(values[i]!.ToString());
 1324                }
 1325            }
 01326            return this;
 1327        }
 1328
 1329        #endregion
 1330
 1331        public StringBuilder Insert(int index, string? value)
 1332        {
 01333            if ((uint)index > (uint)Length)
 1334            {
 01335                throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
 1336            }
 1337
 01338            if (value != null)
 1339            {
 01340                Insert(index, ref value.GetRawStringData(), value.Length);
 1341            }
 1342
 01343            return this;
 1344        }
 1345
 1346#pragma warning disable CA1830 // Prefer strongly-typed Append and Insert method overloads on StringBuilder. No need to 
 1347        // bool does not implement ISpanFormattable but its ToString override returns cached strings.
 01348        public StringBuilder Insert(int index, bool value) => Insert(index, value.ToString().AsSpan(), 1);
 1349#pragma warning restore CA1830
 1350
 1351        [CLSCompliant(false)]
 01352        public StringBuilder Insert(int index, sbyte value) => InsertSpanFormattable(index, value);
 1353
 01354        public StringBuilder Insert(int index, byte value) => InsertSpanFormattable(index, value);
 1355
 01356        public StringBuilder Insert(int index, short value) => InsertSpanFormattable(index, value);
 1357
 1358        public StringBuilder Insert(int index, char value)
 1359        {
 01360            if ((uint)index > (uint)Length)
 1361            {
 01362                throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
 1363            }
 1364
 01365            Insert(index, ref value, 1);
 01366            return this;
 1367        }
 1368
 1369        /// <summary>
 1370        /// Inserts the string representation of a specified Unicode rune into this instance at the specified character 
 1371        /// </summary>
 1372        /// <param name="index">The position in this instance where insertion begins.</param>
 1373        /// <param name="value">The value to insert.</param>
 1374        /// <returns>A reference to this instance after the insert operation has completed.</returns>
 1375        public unsafe StringBuilder Insert(int index, Rune value)
 1376        {
 1377            // Convert value to span
 01378            ReadOnlySpan<char> valueChars = value.AsSpan(stackalloc char[Rune.MaxUtf16CharsPerRune]);
 1379
 1380            // Insert span
 01381            return Insert(index, valueChars);
 1382        }
 1383
 1384        public StringBuilder Insert(int index, char[]? value)
 1385        {
 01386            if ((uint)index > (uint)Length)
 1387            {
 01388                throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
 1389            }
 1390
 01391            if (value != null)
 1392            {
 01393                Insert(index, ref MemoryMarshal.GetArrayDataReference(value), value.Length);
 1394            }
 01395            return this;
 1396        }
 1397
 1398        public StringBuilder Insert(int index, char[]? value, int startIndex, int charCount)
 1399        {
 01400            int currentLength = Length;
 01401            if ((uint)index > (uint)currentLength)
 1402            {
 01403                throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
 1404            }
 1405
 01406            if (value == null)
 1407            {
 01408                if (startIndex == 0 && charCount == 0)
 1409                {
 01410                    return this;
 1411                }
 01412                ArgumentNullException.Throw(nameof(value));
 1413            }
 1414
 01415            ArgumentOutOfRangeException.ThrowIfNegative(startIndex);
 01416            ArgumentOutOfRangeException.ThrowIfNegative(charCount);
 01417            if (startIndex > value.Length - charCount)
 1418            {
 01419                throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
 1420            }
 1421
 01422            if (charCount > 0)
 1423            {
 01424                Insert(index, ref value[startIndex], charCount);
 1425            }
 1426
 01427            return this;
 1428        }
 1429
 01430        public StringBuilder Insert(int index, int value) => InsertSpanFormattable(index, value);
 1431
 01432        public StringBuilder Insert(int index, long value) => InsertSpanFormattable(index, value);
 1433
 01434        public StringBuilder Insert(int index, float value) => InsertSpanFormattable(index, value);
 1435
 01436        public StringBuilder Insert(int index, double value) => InsertSpanFormattable(index, value);
 1437
 01438        public StringBuilder Insert(int index, decimal value) => InsertSpanFormattable(index, value);
 1439
 1440        [CLSCompliant(false)]
 01441        public StringBuilder Insert(int index, ushort value) => InsertSpanFormattable(index, value);
 1442
 1443        [CLSCompliant(false)]
 01444        public StringBuilder Insert(int index, uint value) => InsertSpanFormattable(index, value);
 1445
 1446        [CLSCompliant(false)]
 01447        public StringBuilder Insert(int index, ulong value) => InsertSpanFormattable(index, value);
 1448
 01449        public StringBuilder Insert(int index, object? value) => (value == null) ? this : Insert(index, value.ToString()
 1450
 1451        public StringBuilder Insert(int index, ReadOnlySpan<char> value)
 1452        {
 01453            if ((uint)index > (uint)Length)
 1454            {
 01455                throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
 1456            }
 1457
 01458            if (value.Length != 0)
 1459            {
 01460                Insert(index, ref MemoryMarshal.GetReference(value), value.Length);
 1461            }
 1462
 01463            return this;
 1464        }
 1465
 1466        private unsafe StringBuilder InsertSpanFormattable<T>(int index, T value) where T : ISpanFormattable
 1467        {
 01468            Debug.Assert(typeof(T).Assembly.Equals(typeof(object).Assembly), "Implementation trusts the results of TryFo
 1469
 01470            Span<char> buffer = stackalloc char[string.StackallocCharBufferSizeLimit];
 01471            if (value.TryFormat(buffer, out int charsWritten, format: default, provider: null))
 1472            {
 1473                // We don't use Insert(int, ReadOnlySpan<char>) for exception compatibility;
 1474                // we want exceeding the maximum capacity to throw an OutOfMemoryException.
 01475                return Insert(index, buffer.Slice(0, charsWritten), 1);
 1476            }
 1477
 01478            return Insert(index, value.ToString(), 1);
 1479        }
 1480
 1481        public StringBuilder AppendFormat([StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format, object? a
 1482        {
 01483            return AppendFormat(null, format, new ReadOnlySpan<object?>(in arg0));
 1484        }
 1485
 1486        public StringBuilder AppendFormat([StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format, object? a
 1487        {
 01488            return AppendFormat(null, format, [arg0, arg1]);
 1489        }
 1490
 1491        public StringBuilder AppendFormat([StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format, object? a
 1492        {
 01493            return AppendFormat(null, format, [arg0, arg1, arg2]);
 1494        }
 1495
 1496        public StringBuilder AppendFormat([StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format, params ob
 1497        {
 01498            if (args is null)
 1499            {
 1500                // To preserve the original exception behavior, throw an exception about format if both
 1501                // args and format are null. The actual null check for format is in AppendFormat(..., span).
 01502                ArgumentNullException.Throw(format is null ? nameof(format) : nameof(args));
 1503            }
 1504
 01505            return AppendFormat(null, format, args);
 1506        }
 1507
 1508        /// <summary>
 1509        /// Appends the string returned by processing a composite format string, which contains zero or more format item
 1510        /// Each format item is replaced by the string representation of a corresponding argument in a parameter span.
 1511        /// </summary>
 1512        /// <param name="format">A composite format string.</param>
 1513        /// <param name="args">A span of objects to format.</param>
 1514        /// <returns>A reference to this instance after the append operation has completed.</returns>
 1515        /// <exception cref="ArgumentNullException"><paramref name="format"/> is null.</exception>
 1516        /// <exception cref="ArgumentOutOfRangeException">The length of the expanded string would exceed <see cref="Stri
 1517        /// <exception cref="FormatException">
 1518        /// <paramref name="format"/> is invalid.
 1519        /// -or-
 1520        /// The index of a format item is less than 0 (zero), or greater than or equal to the length of the <paramref na
 1521        /// </exception>
 1522        public StringBuilder AppendFormat([StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format, params Re
 1523        {
 01524            return AppendFormat(null, format, args);
 1525        }
 1526
 1527        public StringBuilder AppendFormat(IFormatProvider? provider, [StringSyntax(StringSyntaxAttribute.CompositeFormat
 1528        {
 01529            return AppendFormat(provider, format, new ReadOnlySpan<object?>(in arg0));
 1530        }
 1531
 1532        public StringBuilder AppendFormat(IFormatProvider? provider, [StringSyntax(StringSyntaxAttribute.CompositeFormat
 1533        {
 01534            return AppendFormat(provider, format, [arg0, arg1]);
 1535        }
 1536
 1537        public StringBuilder AppendFormat(IFormatProvider? provider, [StringSyntax(StringSyntaxAttribute.CompositeFormat
 1538        {
 01539            return AppendFormat(provider, format, [arg0, arg1, arg2]);
 1540        }
 1541
 1542        public StringBuilder AppendFormat(IFormatProvider? provider, [StringSyntax(StringSyntaxAttribute.CompositeFormat
 1543        {
 01544            if (args is null)
 1545            {
 1546                // To preserve the original exception behavior, throw an exception about format if both
 1547                // args and format are null. The actual null check for format is in AppendFormat(..., span).
 01548                ArgumentNullException.Throw(format is null ? nameof(format) : nameof(args));
 1549            }
 1550
 01551            return AppendFormat(provider, format, (ReadOnlySpan<object?>)args);
 1552        }
 1553
 1554        /// <summary>
 1555        /// Appends the string returned by processing a composite format string, which contains zero or more format item
 1556        /// Each format item is replaced by the string representation of a corresponding argument in a parameter span us
 1557        /// </summary>
 1558        /// <param name="provider">An object that supplies culture-specific formatting information.</param>
 1559        /// <param name="format">A composite format string.</param>
 1560        /// <param name="args">A span of objects to format.</param>
 1561        /// <returns>A reference to this instance after the append operation has completed.</returns>
 1562        /// <exception cref="ArgumentNullException"><paramref name="format"/> is null.</exception>
 1563        /// <exception cref="ArgumentOutOfRangeException">The length of the expanded string would exceed <see cref="Stri
 1564        /// <exception cref="FormatException">
 1565        /// <paramref name="format"/> is invalid.
 1566        /// -or-
 1567        /// The index of a format item is less than 0 (zero), or greater than or equal to the length of the <paramref na
 1568        /// </exception>
 1569        public StringBuilder AppendFormat(IFormatProvider? provider, [StringSyntax(StringSyntaxAttribute.CompositeFormat
 1570        {
 01571            ArgumentNullException.ThrowIfNull(format);
 1572
 1573            // Undocumented exclusive limits on the range for Argument Hole Index and Argument Hole Alignment.
 1574            const int IndexLimit = 1_000_000; // Note:            0 <= ArgIndex < IndexLimit
 1575            const int WidthLimit = 1_000_000; // Note:  -WidthLimit <  ArgAlign < WidthLimit
 1576
 1577            // Query the provider (if one was supplied) for an ICustomFormatter.  If there is one,
 1578            // it needs to be used to transform all arguments.
 01579            ICustomFormatter? cf = (ICustomFormatter?)provider?.GetFormat(typeof(ICustomFormatter));
 1580
 1581            // Repeatedly find the next hole and process it.
 01582            int pos = 0;
 1583            char ch;
 01584            while (true)
 1585            {
 1586                // Skip until either the end of the input or the first unescaped opening brace, whichever comes first.
 1587                // Along the way we need to also unescape escaped closing braces.
 1588                while (true)
 1589                {
 1590                    // Find the next brace.  If there isn't one, the remainder of the input is text to be appended, and 
 01591                    if ((uint)pos >= (uint)format.Length)
 1592                    {
 01593                        return this;
 1594                    }
 1595
 01596                    ReadOnlySpan<char> remainder = format.AsSpan(pos);
 01597                    int countUntilNextBrace = remainder.IndexOfAny('{', '}');
 01598                    if (countUntilNextBrace < 0)
 1599                    {
 01600                        Append(remainder);
 01601                        return this;
 1602                    }
 1603
 1604                    // Append the text until the brace.
 01605                    Append(remainder.Slice(0, countUntilNextBrace));
 01606                    pos += countUntilNextBrace;
 1607
 1608                    // Get the brace.  It must be followed by another character, either a copy of itself in the case of 
 1609                    // escaped, or an arbitrary character that's part of the hole in the case of an opening brace.
 01610                    char brace = format[pos];
 01611                    ch = MoveNext(format, ref pos);
 01612                    if (brace == ch)
 1613                    {
 01614                        Append(ch);
 01615                        pos++;
 01616                        continue;
 1617                    }
 1618
 1619                    // This wasn't an escape, so it must be an opening brace.
 01620                    if (brace != '{')
 1621                    {
 01622                        ThrowHelper.ThrowFormatInvalidString(pos, ExceptionResource.Format_UnexpectedClosingBrace);
 1623                    }
 1624
 1625                    // Proceed to parse the hole.
 1626                    break;
 1627                }
 1628
 1629                // We're now positioned just after the opening brace of an argument hole, which consists of
 1630                // an opening brace, an index, an optional width preceded by a comma, and an optional format
 1631                // preceded by a colon, with arbitrary amounts of spaces throughout.
 01632                int width = 0;
 01633                bool leftJustify = false;
 01634                ReadOnlySpan<char> itemFormatSpan = default; // used if itemFormat is null
 1635
 1636                // First up is the index parameter, which is of the form:
 1637                //     at least on digit
 1638                //     optional any number of spaces
 1639                // We've already read the first digit into ch.
 01640                Debug.Assert(format[pos - 1] == '{');
 01641                Debug.Assert(ch != '{');
 01642                int index = ch - '0';
 01643                if ((uint)index >= 10u)
 1644                {
 01645                    ThrowHelper.ThrowFormatInvalidString(pos, ExceptionResource.Format_ExpectedAsciiDigit);
 1646                }
 1647
 1648                // Common case is a single digit index followed by a closing brace.  If it's not a closing brace,
 1649                // proceed to finish parsing the full hole format.
 01650                ch = MoveNext(format, ref pos);
 01651                if (ch != '}')
 1652                {
 1653                    // Continue consuming optional additional digits.
 01654                    while (char.IsAsciiDigit(ch) && index < IndexLimit)
 1655                    {
 01656                        index = index * 10 + ch - '0';
 01657                        ch = MoveNext(format, ref pos);
 1658                    }
 1659
 1660                    // Consume optional whitespace.
 01661                    while (ch == ' ')
 1662                    {
 01663                        ch = MoveNext(format, ref pos);
 1664                    }
 1665
 1666                    // Parse the optional alignment, which is of the form:
 1667                    //     comma
 1668                    //     optional any number of spaces
 1669                    //     optional -
 1670                    //     at least one digit
 1671                    //     optional any number of spaces
 01672                    if (ch == ',')
 1673                    {
 1674                        // Consume optional whitespace.
 1675                        do
 1676                        {
 01677                            ch = MoveNext(format, ref pos);
 1678                        }
 01679                        while (ch == ' ');
 1680
 1681                        // Consume an optional minus sign indicating left alignment.
 01682                        if (ch == '-')
 1683                        {
 01684                            leftJustify = true;
 01685                            ch = MoveNext(format, ref pos);
 1686                        }
 1687
 1688                        // Parse alignment digits. The read character must be a digit.
 01689                        width = ch - '0';
 01690                        if ((uint)width >= 10u)
 1691                        {
 01692                            ThrowHelper.ThrowFormatInvalidString(pos, ExceptionResource.Format_ExpectedAsciiDigit);
 1693                        }
 01694                        ch = MoveNext(format, ref pos);
 01695                        while (char.IsAsciiDigit(ch) && width < WidthLimit)
 1696                        {
 01697                            width = width * 10 + ch - '0';
 01698                            ch = MoveNext(format, ref pos);
 1699                        }
 1700
 1701                        // Consume optional whitespace
 01702                        while (ch == ' ')
 1703                        {
 01704                            ch = MoveNext(format, ref pos);
 1705                        }
 1706                    }
 1707
 1708                    // The next character needs to either be a closing brace for the end of the hole,
 1709                    // or a colon indicating the start of the format.
 01710                    if (ch != '}')
 1711                    {
 01712                        if (ch != ':')
 1713                        {
 1714                            // Unexpected character
 01715                            ThrowHelper.ThrowFormatInvalidString(pos, ExceptionResource.Format_UnclosedFormatItem);
 1716                        }
 1717
 1718                        // Search for the closing brace; everything in between is the format,
 1719                        // but opening braces aren't allowed.
 01720                        int startingPos = pos;
 1721                        while (true)
 1722                        {
 01723                            ch = MoveNext(format, ref pos);
 1724
 01725                            if (ch == '}')
 1726                            {
 1727                                // Argument hole closed
 1728                                break;
 1729                            }
 1730
 01731                            if (ch == '{')
 1732                            {
 1733                                // Braces inside the argument hole are not supported
 01734                                ThrowHelper.ThrowFormatInvalidString(pos, ExceptionResource.Format_UnclosedFormatItem);
 1735                            }
 1736                        }
 1737
 01738                        startingPos++;
 01739                        itemFormatSpan = format.AsSpan(startingPos, pos - startingPos);
 1740                    }
 1741                }
 1742
 1743                // Construct the output for this arg hole.
 01744                Debug.Assert(format[pos] == '}');
 01745                pos++;
 01746                string? s = null;
 01747                string? itemFormat = null;
 1748
 01749                if ((uint)index >= (uint)args.Length)
 1750                {
 01751                    ThrowHelper.ThrowFormatIndexOutOfRange();
 1752                }
 01753                object? arg = args[index];
 1754
 01755                if (cf != null)
 1756                {
 01757                    if (!itemFormatSpan.IsEmpty)
 1758                    {
 01759                        itemFormat = new string(itemFormatSpan);
 1760                    }
 1761
 01762                    s = cf.Format(itemFormat, arg, provider);
 1763                }
 1764
 01765                if (s == null)
 1766                {
 1767                    // If arg is ISpanFormattable and the beginning doesn't need padding,
 1768                    // try formatting it into the remaining current chunk.
 01769                    if ((leftJustify || width == 0) &&
 01770                        arg is ISpanFormattable spanFormattableArg &&
 01771                        spanFormattableArg.TryFormat(RemainingCurrentChunk, out int charsWritten, itemFormatSpan, provid
 1772                    {
 01773                        if ((uint)charsWritten > (uint)RemainingCurrentChunk.Length)
 1774                        {
 1775                            // Untrusted ISpanFormattable implementations might return an erroneous charsWritten value,
 1776                            // and m_ChunkLength might end up being used in Unsafe code, so fail if we get back an
 1777                            // out-of-range charsWritten value.
 01778                            ThrowHelper.ThrowFormatInvalidString();
 1779                        }
 1780
 01781                        m_ChunkLength += charsWritten;
 1782
 1783                        // Pad the end, if needed.
 01784                        if (leftJustify && width > charsWritten)
 1785                        {
 01786                            Append(' ', width - charsWritten);
 1787                        }
 1788
 1789                        // Continue to parse other characters.
 01790                        continue;
 1791                    }
 1792
 1793                    // Otherwise, fallback to trying IFormattable or calling ToString.
 01794                    if (arg is IFormattable formattableArg)
 1795                    {
 01796                        if (itemFormatSpan.Length != 0)
 1797                        {
 01798                            itemFormat ??= new string(itemFormatSpan);
 1799                        }
 01800                        s = formattableArg.ToString(itemFormat, provider);
 1801                    }
 1802                    else
 1803                    {
 01804                        s = arg?.ToString();
 1805                    }
 1806
 01807                    s ??= string.Empty;
 1808                }
 1809
 1810                // Append it to the final output of the Format String.
 01811                if (width <= s.Length)
 1812                {
 01813                    Append(s);
 1814                }
 01815                else if (leftJustify)
 1816                {
 01817                    Append(s);
 01818                    Append(' ', width - s.Length);
 1819                }
 1820                else
 1821                {
 01822                    Append(' ', width - s.Length);
 01823                    Append(s);
 1824                }
 1825
 1826                // Continue parsing the rest of the format string.
 1827            }
 1828
 1829            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1830            static char MoveNext(string format, ref int pos)
 1831            {
 01832                pos++;
 01833                if ((uint)pos >= (uint)format.Length)
 1834                {
 01835                    ThrowHelper.ThrowFormatInvalidString(pos, ExceptionResource.Format_UnclosedFormatItem);
 1836                }
 01837                return format[pos];
 1838            }
 1839        }
 1840
 1841        /// <summary>
 1842        /// Appends the string returned by processing a composite format string, which contains zero or more format item
 1843        /// Each format item is replaced by the string representation of any of the arguments using a specified format p
 1844        /// </summary>
 1845        /// <typeparam name="TArg0">The type of the first object to format.</typeparam>
 1846        /// <param name="provider">An object that supplies culture-specific formatting information.</param>
 1847        /// <param name="format">A <see cref="CompositeFormat"/>.</param>
 1848        /// <param name="arg0">The first object to format.</param>
 1849        /// <returns>A reference to this instance after the append operation has completed.</returns>
 1850        /// <exception cref="ArgumentNullException"><paramref name="format"/> is null.</exception>
 1851        /// <exception cref="FormatException">The index of a format item is greater than or equal to the number of suppl
 1852        public StringBuilder AppendFormat<TArg0>(IFormatProvider? provider, CompositeFormat format, TArg0 arg0)
 1853        {
 01854            ArgumentNullException.ThrowIfNull(format);
 01855            format.ValidateNumberOfArgs(1);
 01856            return AppendFormat(provider, format, arg0, 0, 0, default);
 1857        }
 1858
 1859        /// <summary>
 1860        /// Appends the string returned by processing a composite format string, which contains zero or more format item
 1861        /// Each format item is replaced by the string representation of any of the arguments using a specified format p
 1862        /// </summary>
 1863        /// <typeparam name="TArg0">The type of the first object to format.</typeparam>
 1864        /// <typeparam name="TArg1">The type of the second object to format.</typeparam>
 1865        /// <param name="provider">An object that supplies culture-specific formatting information.</param>
 1866        /// <param name="format">A <see cref="CompositeFormat"/>.</param>
 1867        /// <param name="arg0">The first object to format.</param>
 1868        /// <param name="arg1">The second object to format.</param>
 1869        /// <returns>A reference to this instance after the append operation has completed.</returns>
 1870        /// <exception cref="ArgumentNullException"><paramref name="format"/> is null.</exception>
 1871        /// <exception cref="FormatException">The index of a format item is greater than or equal to the number of suppl
 1872        public StringBuilder AppendFormat<TArg0, TArg1>(IFormatProvider? provider, CompositeFormat format, TArg0 arg0, T
 1873        {
 01874            ArgumentNullException.ThrowIfNull(format);
 01875            format.ValidateNumberOfArgs(2);
 01876            return AppendFormat(provider, format, arg0, arg1, 0, default);
 1877        }
 1878
 1879        /// <summary>
 1880        /// Appends the string returned by processing a composite format string, which contains zero or more format item
 1881        /// Each format item is replaced by the string representation of any of the arguments using a specified format p
 1882        /// </summary>
 1883        /// <typeparam name="TArg0">The type of the first object to format.</typeparam>
 1884        /// <typeparam name="TArg1">The type of the second object to format.</typeparam>
 1885        /// <typeparam name="TArg2">The type of the third object to format.</typeparam>
 1886        /// <param name="provider">An object that supplies culture-specific formatting information.</param>
 1887        /// <param name="format">A <see cref="CompositeFormat"/>.</param>
 1888        /// <param name="arg0">The first object to format.</param>
 1889        /// <param name="arg1">The second object to format.</param>
 1890        /// <param name="arg2">The third object to format.</param>
 1891        /// <returns>A reference to this instance after the append operation has completed.</returns>
 1892        /// <exception cref="ArgumentNullException"><paramref name="format"/> is null.</exception>
 1893        /// <exception cref="FormatException">The index of a format item is greater than or equal to the number of suppl
 1894        public StringBuilder AppendFormat<TArg0, TArg1, TArg2>(IFormatProvider? provider, CompositeFormat format, TArg0 
 1895        {
 01896            ArgumentNullException.ThrowIfNull(format);
 01897            format.ValidateNumberOfArgs(3);
 01898            return AppendFormat(provider, format, arg0, arg1, arg2, default);
 1899        }
 1900
 1901        /// <summary>
 1902        /// Appends the string returned by processing a composite format string, which contains zero or more format item
 1903        /// Each format item is replaced by the string representation of any of the arguments using a specified format p
 1904        /// </summary>
 1905        /// <param name="provider">An object that supplies culture-specific formatting information.</param>
 1906        /// <param name="format">A <see cref="CompositeFormat"/>.</param>
 1907        /// <param name="args">An array of objects to format.</param>
 1908        /// <returns>A reference to this instance after the append operation has completed.</returns>
 1909        /// <exception cref="ArgumentNullException"><paramref name="format"/> is null.</exception>
 1910        /// <exception cref="ArgumentNullException"><paramref name="args"/> is null.</exception>
 1911        /// <exception cref="FormatException">The index of a format item is greater than or equal to the number of suppl
 1912        public StringBuilder AppendFormat(IFormatProvider? provider, CompositeFormat format, params object?[] args)
 1913        {
 01914            ArgumentNullException.ThrowIfNull(format);
 01915            ArgumentNullException.ThrowIfNull(args);
 01916            return AppendFormat(provider, format, (ReadOnlySpan<object?>)args);
 1917        }
 1918
 1919        /// <summary>
 1920        /// Appends the string returned by processing a composite format string, which contains zero or more format item
 1921        /// Each format item is replaced by the string representation of any of the arguments using a specified format p
 1922        /// </summary>
 1923        /// <param name="provider">An object that supplies culture-specific formatting information.</param>
 1924        /// <param name="format">A <see cref="CompositeFormat"/>.</param>
 1925        /// <param name="args">A span of objects to format.</param>
 1926        /// <returns>A reference to this instance after the append operation has completed.</returns>
 1927        /// <exception cref="ArgumentNullException"><paramref name="format"/> is null.</exception>
 1928        /// <exception cref="FormatException">The index of a format item is greater than or equal to the number of suppl
 1929        public StringBuilder AppendFormat(IFormatProvider? provider, CompositeFormat format, params ReadOnlySpan<object?
 1930        {
 01931            ArgumentNullException.ThrowIfNull(format);
 01932            format.ValidateNumberOfArgs(args.Length);
 01933            return args.Length switch
 01934            {
 01935                0 => AppendFormat(provider, format, 0, 0, 0, args),
 01936                1 => AppendFormat(provider, format, args[0], 0, 0, args),
 01937                2 => AppendFormat(provider, format, args[0], args[1], 0, args),
 01938                _ => AppendFormat(provider, format, args[0], args[1], args[2], args),
 01939            };
 1940        }
 1941
 1942        private StringBuilder AppendFormat<TArg0, TArg1, TArg2>(IFormatProvider? provider, CompositeFormat format, TArg0
 1943        {
 1944            // Create the interpolated string handler.
 01945            var handler = new AppendInterpolatedStringHandler(format._literalLength, format._formattedCount, this, provi
 1946
 1947            // Append each segment.
 01948            foreach ((string? Literal, int ArgIndex, int Alignment, string? Format) segment in format._segments)
 1949            {
 01950                if (segment.Literal is string literal)
 1951                {
 01952                    handler.AppendLiteral(literal);
 1953                }
 1954                else
 1955                {
 01956                    int index = segment.ArgIndex;
 1957                    switch (index)
 1958                    {
 1959                        case 0:
 01960                            handler.AppendFormatted(arg0, segment.Alignment, segment.Format);
 01961                            break;
 1962
 1963                        case 1:
 01964                            handler.AppendFormatted(arg1, segment.Alignment, segment.Format);
 01965                            break;
 1966
 1967                        case 2:
 01968                            handler.AppendFormatted(arg2, segment.Alignment, segment.Format);
 01969                            break;
 1970
 1971                        default:
 01972                            Debug.Assert(index > 2);
 01973                            handler.AppendFormatted(args[index], segment.Alignment, segment.Format);
 1974                            break;
 1975                    }
 1976                }
 1977            }
 1978
 1979            // Complete the operation.
 01980            return Append(ref handler);
 1981        }
 1982
 1983        /// <summary>
 1984        /// Replaces all instances of one string with another in this builder.
 1985        /// </summary>
 1986        /// <param name="oldValue">The string to replace.</param>
 1987        /// <param name="newValue">The string to replace <paramref name="oldValue"/> with.</param>
 1988        /// <remarks>
 1989        /// If <paramref name="newValue"/> is <c>null</c>, instances of <paramref name="oldValue"/>
 1990        /// are removed from this builder.
 1991        /// </remarks>
 01992        public StringBuilder Replace(string oldValue, string? newValue) => Replace(oldValue, newValue, 0, Length);
 1993
 1994        /// <summary>
 1995        /// Replaces all instances of one read-only character span with another in this builder.
 1996        /// </summary>
 1997        /// <param name="oldValue">The read-only character span to replace.</param>
 1998        /// <param name="newValue">The read-only character span to replace <paramref name="oldValue"/> with.</param>
 1999        /// <remarks>
 2000        /// If <paramref name="newValue"/> is empty, instances of <paramref name="oldValue"/>
 2001        /// are removed from this builder.
 2002        /// </remarks>
 02003        public StringBuilder Replace(ReadOnlySpan<char> oldValue, ReadOnlySpan<char> newValue) => Replace(oldValue, newV
 2004
 2005        /// <summary>
 2006        /// Determines if the contents of this builder are equal to the contents of another builder.
 2007        /// </summary>
 2008        /// <param name="sb">The other builder.</param>
 2009        public bool Equals([NotNullWhen(true)] StringBuilder? sb)
 2010        {
 02011            if (sb == null)
 2012            {
 02013                return false;
 2014            }
 02015            if (Length != sb.Length)
 2016            {
 02017                return false;
 2018            }
 02019            if (sb == this)
 2020            {
 02021                return true;
 2022            }
 02023            StringBuilder? thisChunk = this;
 02024            int thisChunkIndex = thisChunk.m_ChunkLength;
 02025            StringBuilder? sbChunk = sb;
 02026            int sbChunkIndex = sbChunk.m_ChunkLength;
 2027            while (true)
 2028            {
 02029                --thisChunkIndex;
 02030                --sbChunkIndex;
 2031
 02032                while (thisChunkIndex < 0)
 2033                {
 02034                    thisChunk = thisChunk.m_ChunkPrevious;
 02035                    if (thisChunk == null)
 2036                    {
 2037                        break;
 2038                    }
 02039                    thisChunkIndex = thisChunk.m_ChunkLength + thisChunkIndex;
 2040                }
 2041
 02042                while (sbChunkIndex < 0)
 2043                {
 02044                    sbChunk = sbChunk.m_ChunkPrevious;
 02045                    if (sbChunk == null)
 2046                    {
 2047                        break;
 2048                    }
 02049                    sbChunkIndex = sbChunk.m_ChunkLength + sbChunkIndex;
 2050                }
 2051
 02052                if (thisChunkIndex < 0)
 2053                {
 02054                    return sbChunkIndex < 0;
 2055                }
 02056                if (sbChunkIndex < 0)
 2057                {
 02058                    return false;
 2059                }
 2060
 02061                Debug.Assert(thisChunk != null && sbChunk != null);
 02062                if (thisChunk.m_ChunkChars[thisChunkIndex] != sbChunk.m_ChunkChars[sbChunkIndex])
 2063                {
 02064                    return false;
 2065                }
 2066            }
 2067        }
 2068
 2069        /// <summary>
 2070        /// Determines if the contents of this builder are equal to the contents of <see cref="ReadOnlySpan{Char}"/>.
 2071        /// </summary>
 2072        /// <param name="span">The <see cref="ReadOnlySpan{Char}"/>.</param>
 2073        public bool Equals(ReadOnlySpan<char> span)
 2074        {
 02075            if (span.Length != Length)
 2076            {
 02077                return false;
 2078            }
 2079
 02080            StringBuilder? sbChunk = this;
 02081            int offset = 0;
 2082
 2083            do
 2084            {
 02085                int chunk_length = sbChunk.m_ChunkLength;
 02086                offset += chunk_length;
 2087
 02088                ReadOnlySpan<char> chunk = new ReadOnlySpan<char>(sbChunk.m_ChunkChars, 0, chunk_length);
 2089
 02090                if (!chunk.EqualsOrdinal(span.Slice(span.Length - offset, chunk_length)))
 2091                {
 02092                    return false;
 2093                }
 2094
 02095                sbChunk = sbChunk.m_ChunkPrevious;
 02096            } while (sbChunk != null);
 2097
 02098            Debug.Assert(offset == Length);
 02099            return true;
 2100        }
 2101
 2102        /// <summary>
 2103        /// Replaces all instances of one string with another in part of this builder.
 2104        /// </summary>
 2105        /// <param name="oldValue">The string to replace.</param>
 2106        /// <param name="newValue">The string to replace <paramref name="oldValue"/> with.</param>
 2107        /// <param name="startIndex">The index to start in this builder.</param>
 2108        /// <param name="count">The number of characters to read in this builder.</param>
 2109        /// <remarks>
 2110        /// If <paramref name="newValue"/> is <c>null</c>, instances of <paramref name="oldValue"/>
 2111        /// are removed from this builder.
 2112        /// </remarks>
 2113        public StringBuilder Replace(string oldValue, string? newValue, int startIndex, int count)
 2114        {
 02115            ArgumentException.ThrowIfNullOrEmpty(oldValue);
 02116            return Replace(oldValue.AsSpan(), newValue.AsSpan(), startIndex, count);
 2117        }
 2118
 2119        /// <summary>
 2120        /// Replaces all instances of one read-only character span with another in part of this builder.
 2121        /// </summary>
 2122        /// <param name="oldValue">The read-only character span to replace.</param>
 2123        /// <param name="newValue">The read-only character span to replace <paramref name="oldValue"/> with.</param>
 2124        /// <param name="startIndex">The index to start in this builder.</param>
 2125        /// <param name="count">The number of characters to read in this builder.</param>
 2126        /// <remarks>
 2127        /// If <paramref name="newValue"/> is empty, instances of <paramref name="oldValue"/>
 2128        /// are removed from this builder.
 2129        /// </remarks>
 2130        public unsafe StringBuilder Replace(ReadOnlySpan<char> oldValue, ReadOnlySpan<char> newValue, int startIndex, in
 2131        {
 02132            int currentLength = Length;
 02133            if ((uint)startIndex > (uint)currentLength)
 2134            {
 02135                throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
 2136            }
 02137            if (count < 0 || startIndex > currentLength - count)
 2138            {
 02139                throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
 2140            }
 02141            if (oldValue.Length == 0)
 2142            {
 02143                throw new ArgumentException(SR.Arg_EmptySpan, nameof(oldValue));
 2144            }
 2145
 02146            var replacements = new ValueListBuilder<int>(stackalloc int[128]); // A list of replacement positions in a c
 2147
 2148            // Find the chunk, indexInChunk for the starting point
 02149            StringBuilder chunk = FindChunkForIndex(startIndex);
 02150            int indexInChunk = startIndex - chunk.m_ChunkOffset;
 02151            while (count > 0)
 2152            {
 02153                Debug.Assert(chunk != null, "chunk was null in replace");
 2154
 2155                // While the remaining search space is at least as large as the old value being replaced,
 2156                // find all occurrences of it contained entirely within the chunk. We stop searching
 2157                // once we're within oldValue.Length from the end of the chunk (or count limit), at which point
 2158                // we need to consider a value that bridges between two chunks.
 02159                ReadOnlySpan<char> remainingChunk = chunk.m_ChunkChars.AsSpan(indexInChunk, Math.Min(chunk.m_ChunkLength
 02160                while (oldValue.Length <= remainingChunk.Length)
 2161                {
 2162                    // Find the next match.
 02163                    int foundPos = remainingChunk.IndexOf(oldValue);
 02164                    if (foundPos >= 0)
 2165                    {
 2166                        // We found one.  Add it as a location for the replacement.
 02167                        indexInChunk += foundPos;
 02168                        replacements.Append(indexInChunk);
 2169
 2170                        // Move ahead to the next location.
 02171                        remainingChunk = remainingChunk.Slice(foundPos + oldValue.Length);
 02172                        indexInChunk += oldValue.Length;
 02173                        count -= foundPos + oldValue.Length;
 2174
 2175                        // If after accounting for moving past the match our count has
 2176                        // gone to 0, break out to stop searching.
 02177                        Debug.Assert(count >= 0, "count should never go negative");
 02178                        if (count == 0)
 2179                        {
 02180                            break;
 2181                        }
 2182                    }
 2183                    else
 2184                    {
 2185                        // No match found. Reposition to one character beyond the last starting
 2186                        // location searched, which will be oldValue.Length - 1 from the end.
 2187                        // Then break out so that we can start the cross-chunk matching from that location.
 02188                        int move = remainingChunk.Length - (oldValue.Length - 1);
 02189                        indexInChunk += move;
 02190                        count -= move;
 02191                        break;
 2192                    }
 2193                }
 2194
 02195                Debug.Assert(oldValue.Length > Math.Min(count, chunk.m_ChunkLength - indexInChunk),
 02196                    $"oldValue.Length = {oldValue.Length}, chunk.m_ChunkLength - indexInChunk = {chunk.m_ChunkLength - i
 2197
 2198                // Now do the more complicated cross-chunk matching.
 02199                while (indexInChunk < chunk.m_ChunkLength && count > 0)
 2200                {
 02201                    if (StartsWith(chunk, indexInChunk, count, oldValue))
 2202                    {
 02203                        replacements.Append(indexInChunk);
 02204                        indexInChunk += oldValue.Length;
 02205                        count -= oldValue.Length;
 2206                    }
 2207                    else
 2208                    {
 02209                        indexInChunk++;
 02210                        --count;
 2211                    }
 2212                }
 2213
 2214                // We've either fully explored the chunk or we've reached our count limit.
 02215                Debug.Assert(indexInChunk >= chunk.m_ChunkLength || count == 0,
 02216                    $"indexInChunk = {indexInChunk}, chunk.m_ChunkLength == {chunk.m_ChunkLength}, count == {count}");
 2217
 2218                // Replacing mutates the blocks, so we need to convert to a logical index and back afterwards.
 02219                int index = indexInChunk + chunk.m_ChunkOffset;
 2220
 2221                // Apply any replacements we accumulated.
 02222                if (replacements.Length != 0)
 2223                {
 2224                    // Perform all replacements, and adjust the logical index if the new and old values
 2225                    // have different lengths, such that the replacements would have impacted it.
 02226                    ReplaceAllInChunk(replacements.AsSpan(), chunk, oldValue.Length, newValue);
 02227                    index += (newValue.Length - oldValue.Length) * replacements.Length;
 02228                    replacements.Length = 0;
 2229                }
 2230
 02231                chunk = FindChunkForIndex(index);
 02232                indexInChunk = index - chunk.m_ChunkOffset;
 02233                Debug.Assert(chunk != null || count == 0, "Chunks ended prematurely!");
 2234            }
 2235
 02236            replacements.Dispose();
 2237
 02238            AssertInvariants();
 02239            return this;
 2240        }
 2241
 2242        /// <summary>
 2243        /// Replaces all instances of one character with another in this builder.
 2244        /// </summary>
 2245        /// <param name="oldChar">The character to replace.</param>
 2246        /// <param name="newChar">The character to replace <paramref name="oldChar"/> with.</param>
 2247        public StringBuilder Replace(char oldChar, char newChar)
 2248        {
 02249            return Replace(oldChar, newChar, 0, Length);
 2250        }
 2251
 2252        /// <summary>
 2253        /// Replaces all instances of one character with another in this builder.
 2254        /// </summary>
 2255        /// <param name="oldChar">The character to replace.</param>
 2256        /// <param name="newChar">The character to replace <paramref name="oldChar"/> with.</param>
 2257        /// <param name="startIndex">The index to start in this builder.</param>
 2258        /// <param name="count">The number of characters to read in this builder.</param>
 2259        public StringBuilder Replace(char oldChar, char newChar, int startIndex, int count)
 2260        {
 02261            int currentLength = Length;
 02262            if ((uint)startIndex > (uint)currentLength)
 2263            {
 02264                throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
 2265            }
 2266
 02267            if (count < 0 || startIndex > currentLength - count)
 2268            {
 02269                throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
 2270            }
 2271
 02272            int endIndex = startIndex + count;
 02273            StringBuilder chunk = this;
 2274
 02275            while (true)
 2276            {
 02277                int endIndexInChunk = endIndex - chunk.m_ChunkOffset;
 02278                int startIndexInChunk = startIndex - chunk.m_ChunkOffset;
 02279                if (endIndexInChunk >= 0)
 2280                {
 02281                    int curInChunk = Math.Max(startIndexInChunk, 0);
 02282                    int endInChunk = Math.Min(chunk.m_ChunkLength, endIndexInChunk);
 2283
 02284                    Span<char> span = chunk.m_ChunkChars.AsSpan(curInChunk, endInChunk - curInChunk);
 02285                    span.Replace(oldChar, newChar);
 2286                }
 2287
 02288                if (startIndexInChunk >= 0)
 2289                {
 2290                    break;
 2291                }
 2292
 02293                Debug.Assert(chunk.m_ChunkPrevious != null);
 02294                chunk = chunk.m_ChunkPrevious;
 2295            }
 2296
 02297            AssertInvariants();
 02298            return this;
 2299        }
 2300
 2301        /// <summary>
 2302        /// Replaces all occurrences of a specified rune in this instance with another specified rune using an ordinal c
 2303        /// </summary>
 2304        /// <param name="oldRune">The rune to replace.</param>
 2305        /// <param name="newRune">The rune that replaces <paramref name="oldRune"/>.</param>
 2306        /// <returns>A reference to this instance with <paramref name="oldRune"/> replaced by <paramref name="newRune"/>
 2307        public StringBuilder Replace(Rune oldRune, Rune newRune)
 2308        {
 02309            return Replace(oldRune, newRune, 0, Length);
 2310        }
 2311
 2312        /// <summary>
 2313        /// Replaces, within a substring of this instance, all occurrences of a specified rune with another specified ru
 2314        /// </summary>
 2315        /// <param name="oldRune">The rune to replace.</param>
 2316        /// <param name="newRune">The rune that replaces <paramref name="oldRune"/>.</param>
 2317        /// <param name="startIndex">The position in this instance where the substring begins.</param>
 2318        /// <param name="count">The length of the substring.</param>
 2319        /// <returns>
 2320        /// A reference to this instance with <paramref name="oldRune"/> replaced by <paramref name="newRune"/> in the r
 2321        /// from <paramref name="startIndex"/> to <paramref name="startIndex"/> + <paramref name="count"/> - 1.
 2322        /// </returns>
 2323        public unsafe StringBuilder Replace(Rune oldRune, Rune newRune, int startIndex, int count)
 2324        {
 2325            // Convert oldRune to span
 02326            ReadOnlySpan<char> oldChars = oldRune.AsSpan(stackalloc char[Rune.MaxUtf16CharsPerRune]);
 2327
 2328            // Convert newRune to span
 02329            ReadOnlySpan<char> newChars = newRune.AsSpan(stackalloc char[Rune.MaxUtf16CharsPerRune]);
 2330
 2331            // Replace span with span
 02332            return Replace(oldChars, newChars, startIndex, count);
 2333        }
 2334
 2335        /// <summary>
 2336        /// Appends a character buffer to this builder.
 2337        /// </summary>
 2338        /// <param name="value">The pointer to the start of the buffer.</param>
 2339        /// <param name="valueCount">The number of characters in the buffer.</param>
 2340        [CLSCompliant(false)]
 2341        public unsafe StringBuilder Append(char* value, int valueCount)
 2342        {
 2343            // We don't check null value as this case will throw null reference exception anyway
 02344            ArgumentOutOfRangeException.ThrowIfNegative(valueCount);
 2345
 02346            Append(ref *value, valueCount);
 02347            return this;
 2348        }
 2349
 2350        /// <summary>Appends a specified number of chars starting from the specified reference.</summary>
 2351        private void Append(ref char value, int valueCount)
 2352        {
 1422353            Debug.Assert(valueCount >= 0, "Invalid length; should have been validated by caller.");
 1422354            if (valueCount != 0)
 2355            {
 1422356                char[] chunkChars = m_ChunkChars;
 1422357                int chunkLength = m_ChunkLength;
 2358
 1422359                if (((uint)chunkLength + (uint)valueCount) <= (uint)chunkChars.Length)
 2360                {
 1082361                    ref char destination = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(chunkChars), chunkLeng
 1082362                    if (valueCount <= 2)
 2363                    {
 812364                        destination = value;
 812365                        if (valueCount == 2)
 2366                        {
 412367                            Unsafe.Add(ref destination, 1) = Unsafe.Add(ref value, 1);
 2368                        }
 2369                    }
 2370                    else
 2371                    {
 272372                        Buffer.Memmove(ref destination, ref value, (nuint)valueCount);
 2373                    }
 2374
 1082375                    m_ChunkLength = chunkLength + valueCount;
 2376                }
 2377                else
 2378                {
 342379                    AppendWithExpansion(ref value, valueCount);
 2380                }
 2381            }
 342382        }
 2383
 2384        private void AppendWithExpansion(ref char value, int valueCount)
 2385        {
 2386            // Check if the valueCount will put us over m_MaxCapacity.
 2387            // Doing the check here prevents corruption of the StringBuilder.
 342388            int newLength = Length + valueCount;
 342389            if (newLength > m_MaxCapacity || newLength < valueCount)
 2390            {
 02391                throw new ArgumentOutOfRangeException(nameof(valueCount), SR.ArgumentOutOfRange_LengthGreaterThanCapacit
 2392            }
 2393
 2394            // Copy the first chunk
 342395            int firstLength = m_ChunkChars.Length - m_ChunkLength;
 342396            if (firstLength > 0)
 2397            {
 292398                new ReadOnlySpan<char>(ref value, firstLength).CopyTo(m_ChunkChars.AsSpan(m_ChunkLength));
 292399                m_ChunkLength = m_ChunkChars.Length;
 2400            }
 2401
 2402            // Expand the builder to add another chunk.
 342403            int restLength = valueCount - firstLength;
 342404            ExpandByABlock(restLength);
 342405            Debug.Assert(m_ChunkLength == 0, "A new block was not created.");
 2406
 2407            // Copy the second chunk
 342408            new ReadOnlySpan<char>(ref Unsafe.Add(ref value, firstLength), restLength).CopyTo(m_ChunkChars);
 342409            m_ChunkLength = restLength;
 2410
 342411            AssertInvariants();
 342412        }
 2413
 2414        /// <summary>
 2415        /// Inserts a character buffer into this builder at the specified position.
 2416        /// </summary>
 2417        /// <param name="index">The index to insert in this builder.</param>
 2418        /// <param name="value">The reference to the start of the buffer.</param>
 2419        /// <param name="valueCount">The number of characters in the buffer.</param>
 2420        private void Insert(int index, ref char value, int valueCount)
 2421        {
 02422            Debug.Assert((uint)index <= (uint)Length, "Callers should check that index is a legal value.");
 2423
 02424            if (valueCount > 0)
 2425            {
 02426                MakeRoom(index, valueCount, out StringBuilder chunk, out int indexInChunk, false);
 02427                ReplaceInPlaceAtChunk(ref chunk!, ref indexInChunk, ref value, valueCount);
 2428            }
 02429        }
 2430
 2431        /// <summary>
 2432        /// Replaces strings at specified indices with a new string in a chunk.
 2433        /// </summary>
 2434        /// <param name="replacements">The list of indices, relative to the beginning of the chunk, to remove at.</param
 2435        /// <param name="sourceChunk">The source chunk.</param>
 2436        /// <param name="removeCount">The number of characters to remove at each replacement.</param>
 2437        /// <param name="value">The string to insert at each replacement.</param>
 2438        /// <remarks>
 2439        /// This routine is very efficient because it does replacements in bulk.
 2440        /// </remarks>
 2441        private void ReplaceAllInChunk(ReadOnlySpan<int> replacements, StringBuilder sourceChunk, int removeCount, ReadO
 2442        {
 02443            Debug.Assert(!replacements.IsEmpty);
 2444
 2445            // calculate the total amount of extra space or space needed for all the replacements.
 02446            long longDelta = (value.Length - removeCount) * (long)replacements.Length;
 02447            int delta = (int)longDelta;
 02448            if (delta != longDelta)
 2449            {
 02450                throw new OutOfMemoryException();
 2451            }
 2452
 02453            StringBuilder targetChunk = sourceChunk;        // the target as we copy chars down
 02454            int targetIndexInChunk = replacements[0];
 2455
 2456            // Make the room needed for all the new characters if needed.
 02457            if (delta > 0)
 2458            {
 02459                MakeRoom(targetChunk.m_ChunkOffset + targetIndexInChunk, delta, out targetChunk, out targetIndexInChunk,
 2460            }
 2461
 2462            // We made certain that characters after the insertion point are not moved,
 02463            int i = 0;
 02464            while (true)
 2465            {
 2466                // Copy in the new string for the ith replacement
 02467                ReplaceInPlaceAtChunk(ref targetChunk!, ref targetIndexInChunk, ref MemoryMarshal.GetReference<char>(val
 02468                int gapStart = replacements[i] + removeCount;
 02469                i++;
 02470                if ((uint)i >= replacements.Length)
 2471                {
 2472                    break;
 2473                }
 2474
 02475                int gapEnd = replacements[i];
 02476                Debug.Assert(gapStart < sourceChunk.m_ChunkChars.Length, "gap starts at end of buffer.  Should not happe
 02477                Debug.Assert(gapStart <= gapEnd, "negative gap size");
 02478                Debug.Assert(gapEnd <= sourceChunk.m_ChunkLength, "gap too big");
 02479                if (delta != 0)     // can skip the sliding of gaps if source an target string are the same size.
 2480                {
 2481                    // Copy the gap data between the current replacement and the next replacement
 02482                    ReplaceInPlaceAtChunk(ref targetChunk!, ref targetIndexInChunk, ref sourceChunk.m_ChunkChars[gapStar
 2483                }
 2484                else
 2485                {
 02486                    targetIndexInChunk += gapEnd - gapStart;
 02487                    Debug.Assert(targetIndexInChunk <= targetChunk.m_ChunkLength, "gap not in chunk");
 2488                }
 2489            }
 2490
 2491            // Remove extra space if necessary.
 02492            if (delta < 0)
 2493            {
 02494                Remove(targetChunk.m_ChunkOffset + targetIndexInChunk, -delta, out targetChunk, out targetIndexInChunk);
 2495            }
 02496        }
 2497
 2498        /// <summary>
 2499        /// Returns a value indicating whether a substring of a builder starts with a specified prefix.
 2500        /// </summary>
 2501        /// <param name="chunk">The chunk in which the substring starts.</param>
 2502        /// <param name="indexInChunk">The index in <paramref name="chunk"/> at which the substring starts.</param>
 2503        /// <param name="count">The logical count of the substring.</param>
 2504        /// <param name="value">The prefix.</param>
 2505        private bool StartsWith(StringBuilder chunk, int indexInChunk, int count, ReadOnlySpan<char> value)
 2506        {
 02507            for (int i = 0; i < value.Length; i++)
 2508            {
 02509                if (count == 0)
 2510                {
 02511                    return false;
 2512                }
 2513
 02514                if (indexInChunk >= chunk.m_ChunkLength)
 2515                {
 02516                    chunk = Next(chunk)!;
 02517                    if (chunk == null)
 2518                    {
 02519                        return false;
 2520                    }
 02521                    indexInChunk = 0;
 2522                }
 2523
 02524                if (value[i] != chunk.m_ChunkChars[indexInChunk])
 2525                {
 02526                    return false;
 2527                }
 2528
 02529                indexInChunk++;
 02530                --count;
 2531            }
 2532
 02533            return true;
 2534        }
 2535
 2536        /// <summary>
 2537        /// Replaces characters at a specified location with the contents of a character buffer.
 2538        /// This function is the logical equivalent of memcpy.
 2539        /// </summary>
 2540        /// <param name="chunk">
 2541        /// The chunk in which to start replacing characters.
 2542        /// Receives the chunk in which character replacement ends.
 2543        /// </param>
 2544        /// <param name="indexInChunk">
 2545        /// The index in <paramref name="chunk"/> to start replacing characters at.
 2546        /// Receives the index at which character replacement ends.
 2547        /// </param>
 2548        /// <param name="value">The reference to the start of the character buffer.</param>
 2549        /// <param name="count">The number of characters in the buffer.</param>
 2550        private void ReplaceInPlaceAtChunk(ref StringBuilder? chunk, ref int indexInChunk, ref char value, int count)
 2551        {
 02552            if (count != 0)
 2553            {
 02554                while (true)
 2555                {
 02556                    Debug.Assert(chunk != null, "chunk should not be null at this point");
 02557                    int lengthInChunk = chunk.m_ChunkLength - indexInChunk;
 02558                    Debug.Assert(lengthInChunk >= 0, "Index isn't in the chunk.");
 2559
 02560                    int lengthToCopy = Math.Min(lengthInChunk, count);
 02561                    new ReadOnlySpan<char>(ref value, lengthToCopy).CopyTo(chunk.m_ChunkChars.AsSpan(indexInChunk));
 2562
 2563                    // Advance the index.
 02564                    indexInChunk += lengthToCopy;
 02565                    if (indexInChunk >= chunk.m_ChunkLength)
 2566                    {
 02567                        chunk = Next(chunk);
 02568                        indexInChunk = 0;
 2569                    }
 02570                    count -= lengthToCopy;
 02571                    if (count == 0)
 2572                    {
 2573                        break;
 2574                    }
 02575                    value = ref Unsafe.Add(ref value, lengthToCopy);
 2576                }
 2577            }
 02578        }
 2579
 2580        /// <summary>
 2581        /// Gets the chunk corresponding to the logical index in this builder.
 2582        /// </summary>
 2583        /// <param name="index">The logical index in this builder.</param>
 2584        /// <remarks>
 2585        /// After calling this method, you can obtain the actual index within the chunk by
 2586        /// subtracting <see cref="m_ChunkOffset"/> from <paramref name="index"/>.
 2587        /// </remarks>
 2588        private StringBuilder FindChunkForIndex(int index)
 2589        {
 02590            Debug.Assert(0 <= index && index <= Length);
 2591
 02592            StringBuilder result = this;
 02593            while (result.m_ChunkOffset > index)
 2594            {
 02595                Debug.Assert(result.m_ChunkPrevious != null);
 02596                result = result.m_ChunkPrevious;
 2597            }
 2598
 02599            Debug.Assert(result != null);
 02600            return result;
 2601        }
 2602
 2603        /// <summary>Gets a span representing the remaining space available in the current chunk.</summary>
 2604        private Span<char> RemainingCurrentChunk
 2605        {
 2606            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 582607            get => new Span<char>(m_ChunkChars, m_ChunkLength, m_ChunkChars.Length - m_ChunkLength);
 2608        }
 2609
 2610        /// <summary>
 2611        /// Finds the chunk that logically succeeds the specified chunk.
 2612        /// </summary>
 2613        /// <param name="chunk">The chunk whose successor should be found.</param>
 2614        /// <remarks>
 2615        /// Each chunk only stores the reference to its logical predecessor, so this routine has to start
 2616        /// from the 'this' reference (which is assumed to represent the whole StringBuilder) and work its
 2617        /// way down until it finds the specified chunk (which is O(n)). Thus, it is more expensive than
 2618        /// a field fetch.
 2619        /// </remarks>
 02620        private StringBuilder? Next(StringBuilder chunk) => chunk == this ? null : FindChunkForIndex(chunk.m_ChunkOffset
 2621
 2622        /// <summary>
 2623        /// Transfers the character buffer from this chunk to a new chunk, and allocates a new buffer with a minimum siz
 2624        /// </summary>
 2625        /// <param name="minBlockCharCount">The minimum size of the new buffer to be allocated for this chunk.</param>
 2626        /// <remarks>
 2627        /// This method requires that the current chunk is full. Otherwise, there's no point in shifting the characters 
 2628        /// It also assumes that 'this' is the last chunk in the linked list.
 2629        /// </remarks>
 2630        private void ExpandByABlock(int minBlockCharCount)
 2631        {
 372632            Debug.Assert(Capacity == Length, nameof(ExpandByABlock) + " should only be called when there is no space lef
 372633            Debug.Assert(minBlockCharCount > 0);
 2634
 372635            AssertInvariants();
 2636
 372637            if ((minBlockCharCount + Length) > m_MaxCapacity || minBlockCharCount + Length < minBlockCharCount)
 2638            {
 02639                throw new ArgumentOutOfRangeException("requiredLength", SR.ArgumentOutOfRange_SmallCapacity);
 2640            }
 2641
 2642            // - We always need to make the new chunk at least as big as was requested (`minBlockCharCount`).
 2643            // - We'd also prefer to make it at least at big as the current length (thus doubling capacity).
 2644            //   - But this is only up to a maximum, so we stay in the small object heap, and never allocate
 2645            //     really big chunks even if the string gets really big.
 372646            int newBlockLength = Math.Max(minBlockCharCount, Math.Min(Length, MaxChunkSize));
 2647
 2648            // Check for integer overflow (logical buffer size > int.MaxValue)
 372649            if (m_ChunkOffset + m_ChunkLength + newBlockLength < newBlockLength)
 2650            {
 02651                throw new OutOfMemoryException();
 2652            }
 2653
 2654            // Allocate the array before updating any state to avoid leaving inconsistent state behind in case of out of
 372655            char[] chunkChars = GC.AllocateUninitializedArray<char>(newBlockLength);
 2656
 2657            // Move all of the data from this chunk to a new one, via a few O(1) reference adjustments.
 2658            // Then, have this chunk point to the new one as its predecessor.
 372659            m_ChunkPrevious = new StringBuilder(this);
 372660            m_ChunkOffset += m_ChunkLength;
 372661            m_ChunkLength = 0;
 2662
 372663            m_ChunkChars = chunkChars;
 2664
 372665            AssertInvariants();
 372666        }
 2667
 2668        /// <summary>
 2669        /// Creates a new chunk with fields copied from an existing chunk.
 2670        /// </summary>
 2671        /// <param name="from">The chunk from which to copy fields.</param>
 2672        /// <remarks>
 2673        /// <para>
 2674        /// This method runs in O(1) time. It does not copy data within the character buffer
 2675        /// <paramref name="from"/> holds, but copies the reference to the character buffer itself
 2676        /// (plus a few other fields).
 2677        /// </para>
 2678        /// <para>
 2679        /// Callers are expected to update <paramref name="from"/> subsequently to point to this
 2680        /// chunk as its predecessor.
 2681        /// </para>
 2682        /// </remarks>
 372683        private StringBuilder(StringBuilder from)
 2684        {
 372685            m_ChunkLength = from.m_ChunkLength;
 372686            m_ChunkOffset = from.m_ChunkOffset;
 372687            m_ChunkChars = from.m_ChunkChars;
 372688            m_ChunkPrevious = from.m_ChunkPrevious;
 372689            m_MaxCapacity = from.m_MaxCapacity;
 2690
 372691            AssertInvariants();
 372692        }
 2693
 2694        /// <summary>
 2695        /// Creates a gap at a logical index with the specified count.
 2696        /// </summary>
 2697        /// <param name="index">The logical index in this builder.</param>
 2698        /// <param name="count">The number of characters in the gap.</param>
 2699        /// <param name="chunk">Receives the chunk containing the gap.</param>
 2700        /// <param name="indexInChunk">The index in <paramref name="chunk"/> that points to the gap.</param>
 2701        /// <param name="doNotMoveFollowingChars">
 2702        /// - If <c>true</c>, then room must be made by inserting a chunk before the current chunk.
 2703        /// - If <c>false</c>, then room can be made by shifting characters ahead of <paramref name="index"/>
 2704        ///   in this block forward by <paramref name="count"/> provided the characters will still fit in
 2705        ///   the current chunk after being shifted.
 2706        ///   - Providing <c>false</c> does not make a difference most of the time, but it can matter when someone
 2707        ///     inserts lots of small strings at a position in the buffer.
 2708        /// </param>
 2709        /// <remarks>
 2710        /// <para>
 2711        /// Since chunks do not contain references to their successors, it is not always possible for us to make room
 2712        /// by inserting space after <paramref name="index"/> in case this chunk runs out of space. Thus, we make room
 2713        /// by inserting space before the specified index, and having logical indices refer to new locations by the end
 2714        /// of this method.
 2715        /// </para>
 2716        /// <para>
 2717        /// <see cref="ReplaceInPlaceAtChunk"/> can be used in conjunction with this method to fill in the newly created
 2718        /// </para>
 2719        /// </remarks>
 2720        private void MakeRoom(int index, int count, out StringBuilder chunk, out int indexInChunk, bool doNotMoveFollowi
 2721        {
 02722            AssertInvariants();
 02723            Debug.Assert(count > 0);
 02724            Debug.Assert(index >= 0);
 2725
 02726            if (count + Length > m_MaxCapacity || count + Length < count)
 2727            {
 02728                throw new ArgumentOutOfRangeException("requiredLength", SR.ArgumentOutOfRange_SmallCapacity);
 2729            }
 2730
 02731            chunk = this;
 02732            while (chunk.m_ChunkOffset > index)
 2733            {
 02734                chunk.m_ChunkOffset += count;
 02735                Debug.Assert(chunk.m_ChunkPrevious != null);
 02736                chunk = chunk.m_ChunkPrevious;
 2737            }
 02738            indexInChunk = index - chunk.m_ChunkOffset;
 2739
 2740            // Cool, we have some space in this block, and we don't have to copy much to get at it, so go ahead and use 
 2741            // This typically happens when someone repeatedly inserts small strings at a spot (usually the absolute fron
 02742            if (!doNotMoveFollowingChars && chunk.m_ChunkLength <= DefaultCapacity * 2 && chunk.m_ChunkChars.Length - ch
 2743            {
 02744                for (int i = chunk.m_ChunkLength; i > indexInChunk;)
 2745                {
 02746                    --i;
 02747                    chunk.m_ChunkChars[i + count] = chunk.m_ChunkChars[i];
 2748                }
 02749                chunk.m_ChunkLength += count;
 02750                return;
 2751            }
 2752
 2753            // Allocate space for the new chunk, which will go before the current one.
 02754            StringBuilder newChunk = new StringBuilder(Math.Max(count, DefaultCapacity), chunk.m_MaxCapacity, chunk.m_Ch
 02755            newChunk.m_ChunkLength = count;
 2756
 2757            // Copy the head of the current buffer to the new buffer.
 02758            int copyCount1 = Math.Min(count, indexInChunk);
 02759            if (copyCount1 > 0)
 2760            {
 02761                new ReadOnlySpan<char>(chunk.m_ChunkChars, 0, copyCount1).CopyTo(newChunk.m_ChunkChars);
 2762
 2763                // Slide characters over in the current buffer to make room.
 02764                int copyCount2 = indexInChunk - copyCount1;
 02765                if (copyCount2 >= 0)
 2766                {
 02767                    new ReadOnlySpan<char>(chunk.m_ChunkChars, copyCount1, copyCount2).CopyTo(chunk.m_ChunkChars);
 02768                    indexInChunk = copyCount2;
 2769                }
 2770            }
 2771
 2772            // Wire in the new chunk.
 02773            chunk.m_ChunkPrevious = newChunk;
 02774            chunk.m_ChunkOffset += count;
 02775            if (copyCount1 < count)
 2776            {
 02777                chunk = newChunk;
 02778                indexInChunk = copyCount1;
 2779            }
 2780
 02781            AssertInvariants();
 02782        }
 2783
 2784        /// <summary>
 2785        /// Used by <see cref="MakeRoom"/> to allocate another chunk.
 2786        /// </summary>
 2787        /// <param name="size">The size of the character buffer for this chunk.</param>
 2788        /// <param name="maxCapacity">The maximum capacity, to be stored in this chunk.</param>
 2789        /// <param name="previousBlock">The predecessor of this chunk.</param>
 02790        private StringBuilder(int size, int maxCapacity, StringBuilder? previousBlock)
 2791        {
 02792            Debug.Assert(size > 0);
 02793            Debug.Assert(maxCapacity > 0);
 2794
 02795            m_ChunkChars = GC.AllocateUninitializedArray<char>(size);
 02796            m_MaxCapacity = maxCapacity;
 02797            m_ChunkPrevious = previousBlock;
 02798            if (previousBlock != null)
 2799            {
 02800                m_ChunkOffset = previousBlock.m_ChunkOffset + previousBlock.m_ChunkLength;
 2801            }
 2802
 02803            AssertInvariants();
 02804        }
 2805
 2806        /// <summary>
 2807        /// Removes a specified number of characters beginning at a logical index in this builder.
 2808        /// </summary>
 2809        /// <param name="startIndex">The logical index in this builder to start removing characters.</param>
 2810        /// <param name="count">The number of characters to remove.</param>
 2811        /// <param name="chunk">Receives the new chunk containing the logical index.</param>
 2812        /// <param name="indexInChunk">
 2813        /// Receives the new index in <paramref name="chunk"/> that is associated with the logical index.
 2814        /// </param>
 2815        private void Remove(int startIndex, int count, out StringBuilder chunk, out int indexInChunk)
 2816        {
 02817            AssertInvariants();
 02818            Debug.Assert(startIndex >= 0 && startIndex < Length);
 2819
 02820            int endIndex = startIndex + count;
 2821
 2822            // Find the chunks for the start and end of the block to delete.
 02823            chunk = this;
 02824            StringBuilder? endChunk = null;
 02825            int endIndexInChunk = 0;
 02826            while (true)
 2827            {
 02828                if (endIndex - chunk.m_ChunkOffset >= 0)
 2829                {
 02830                    if (endChunk == null)
 2831                    {
 02832                        endChunk = chunk;
 02833                        endIndexInChunk = endIndex - endChunk.m_ChunkOffset;
 2834                    }
 02835                    if (startIndex - chunk.m_ChunkOffset >= 0)
 2836                    {
 02837                        indexInChunk = startIndex - chunk.m_ChunkOffset;
 02838                        break;
 2839                    }
 2840                }
 2841                else
 2842                {
 02843                    chunk.m_ChunkOffset -= count;
 2844                }
 2845
 02846                Debug.Assert(chunk.m_ChunkPrevious != null);
 02847                chunk = chunk.m_ChunkPrevious;
 2848            }
 02849            Debug.Assert(chunk != null, "We fell off the beginning of the string!");
 2850
 02851            int copyTargetIndexInChunk = indexInChunk;
 02852            int copyCount = endChunk.m_ChunkLength - endIndexInChunk;
 02853            if (endChunk != chunk)
 2854            {
 02855                copyTargetIndexInChunk = 0;
 2856                // Remove the characters after `startIndex` to the end of the chunk.
 02857                chunk.m_ChunkLength = indexInChunk;
 2858
 2859                // Remove the characters in chunks between the start and the end chunk.
 02860                endChunk.m_ChunkPrevious = chunk;
 02861                endChunk.m_ChunkOffset = chunk.m_ChunkOffset + chunk.m_ChunkLength;
 2862
 2863                // If the start is 0, then we can throw away the whole start chunk.
 02864                if (indexInChunk == 0)
 2865                {
 02866                    endChunk.m_ChunkPrevious = chunk.m_ChunkPrevious;
 02867                    chunk = endChunk;
 2868                }
 2869            }
 02870            endChunk.m_ChunkLength -= (endIndexInChunk - copyTargetIndexInChunk);
 2871
 2872            // SafeCritical: We ensure that `endIndexInChunk + copyCount` is within range of `m_ChunkChars`, and
 2873            // also ensure that `copyTargetIndexInChunk + copyCount` is within the chunk.
 2874
 2875            // Remove any characters in the end chunk, by sliding the characters down.
 02876            if (copyTargetIndexInChunk != endIndexInChunk) // Sometimes no move is necessary
 2877            {
 02878                new ReadOnlySpan<char>(endChunk.m_ChunkChars, endIndexInChunk, copyCount).CopyTo(endChunk.m_ChunkChars.A
 2879            }
 2880
 02881            Debug.Assert(chunk != null, "We fell off the beginning of the string!");
 02882            AssertInvariants();
 02883        }
 2884
 2885        /// <summary>
 2886        /// Gets the <see cref="Rune"/> that begins at a specified position in this builder.
 2887        /// </summary>
 2888        /// <param name="index">The starting position in this builder at which to decode the rune.</param>
 2889        /// <returns>The rune obtained from this builder at the specified <paramref name="index"/>.</returns>
 2890        /// <exception cref="ArgumentOutOfRangeException">The index is out of the range of the builder.</exception>
 2891        /// <exception cref="ArgumentException">The rune at the specified index is not valid.</exception>
 2892        public Rune GetRuneAt(int index)
 2893        {
 02894            if (TryGetRuneAt(index, out Rune value))
 2895            {
 02896                return value;
 2897            }
 02898            ThrowHelper.ThrowArgumentException_CannotExtractScalar(ExceptionArgument.index);
 2899            return default;
 2900        }
 2901
 2902        /// <summary>
 2903        /// Attempts to get the <see cref="Rune"/> that begins at a specified position in this builder, and return a val
 2904        /// </summary>
 2905        /// <param name="index">The starting position in this builder at which to decode the rune.</param>
 2906        /// <param name="value">When this method returns, the decoded rune.</param>
 2907        /// <returns>
 2908        /// <see langword="true"/> if a scalar value was successfully extracted from the specified index;
 2909        /// <see langword="false"/> if a value could not be extracted because of invalid data.
 2910        /// </returns>
 2911        /// <exception cref="ArgumentOutOfRangeException">The index is out of the range of the builder.</exception>
 2912        public bool TryGetRuneAt(int index, out Rune value)
 2913        {
 02914            ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, Length);
 02915            ArgumentOutOfRangeException.ThrowIfNegative(index);
 2916
 2917            // Get span at StringBuilder index
 02918            Span<char> chars = index + 1 < Length
 02919                ? [this[index], this[index + 1]]
 02920                : [this[index]];
 2921
 02922            OperationStatus status = Rune.DecodeFromUtf16(chars, out Rune result, out _);
 02923            if (status is OperationStatus.Done)
 2924            {
 02925                value = result;
 02926                return true;
 2927            }
 2928
 02929            value = default;
 02930            return false;
 2931        }
 2932
 2933        /// <summary>Provides a handler used by the language compiler to append interpolated strings into <see cref="Str
 2934        [EditorBrowsable(EditorBrowsableState.Never)]
 2935        [InterpolatedStringHandler]
 2936        public struct AppendInterpolatedStringHandler
 2937        {
 2938            // Implementation note:
 2939            // As this type is only intended to be targeted by the compiler, public APIs eschew argument validation logi
 2940            // in a variety of places, e.g. allowing a null input when one isn't expected to produce a NullReferenceExce
 2941            // than an ArgumentNullException.
 2942
 2943            /// <summary>The associated StringBuilder to which to append.</summary>
 2944            internal readonly StringBuilder _stringBuilder;
 2945            /// <summary>Optional provider to pass to IFormattable.ToString or ISpanFormattable.TryFormat calls.</summar
 2946            private readonly IFormatProvider? _provider;
 2947            /// <summary>Whether <see cref="_provider"/> provides an ICustomFormatter.</summary>
 2948            /// <remarks>
 2949            /// Custom formatters are very rare.  We want to support them, but it's ok if we make them more expensive
 2950            /// in order to make them as pay-for-play as possible.  So, we avoid adding another reference type field
 2951            /// to reduce the size of the handler and to reduce required zero'ing, by only storing whether the provider
 2952            /// provides a formatter, rather than actually storing the formatter.  This in turn means, if there is a
 2953            /// formatter, we pay for the extra interface call on each AppendFormatted that needs it.
 2954            /// </remarks>
 2955            private readonly bool _hasCustomFormatter;
 2956
 2957            /// <summary>Creates a handler used to append an interpolated string into a <see cref="StringBuilder"/>.</su
 2958            /// <param name="literalLength">The number of constant characters outside of interpolation expressions in th
 2959            /// <param name="formattedCount">The number of interpolation expressions in the interpolated string.</param>
 2960            /// <param name="stringBuilder">The associated StringBuilder to which to append.</param>
 2961            /// <remarks>This is intended to be called only by compiler-generated code. Arguments are not validated as t
 2962            public AppendInterpolatedStringHandler(int literalLength, int formattedCount, StringBuilder stringBuilder)
 2963            {
 02964                _stringBuilder = stringBuilder;
 02965                _provider = null;
 02966                _hasCustomFormatter = false;
 02967            }
 2968
 2969            /// <summary>Creates a handler used to translate an interpolated string into a <see cref="string"/>.</summar
 2970            /// <param name="literalLength">The number of constant characters outside of interpolation expressions in th
 2971            /// <param name="formattedCount">The number of interpolation expressions in the interpolated string.</param>
 2972            /// <param name="stringBuilder">The associated StringBuilder to which to append.</param>
 2973            /// <param name="provider">An object that supplies culture-specific formatting information.</param>
 2974            /// <remarks>This is intended to be called only by compiler-generated code. Arguments are not validated as t
 2975            public AppendInterpolatedStringHandler(int literalLength, int formattedCount, StringBuilder stringBuilder, I
 2976            {
 02977                _stringBuilder = stringBuilder;
 02978                _provider = provider;
 02979                _hasCustomFormatter = provider is not null && DefaultInterpolatedStringHandler.HasCustomFormatter(provid
 02980            }
 2981
 2982            /// <summary>Writes the specified string to the handler.</summary>
 2983            /// <param name="value">The string to write.</param>
 02984            public void AppendLiteral(string value) => _stringBuilder.Append(value);
 2985
 2986            #region AppendFormatted
 2987            // Design note:
 2988            // This provides the same set of overloads and semantics as DefaultInterpolatedStringHandler.
 2989
 2990            #region AppendFormatted T
 2991            /// <summary>Writes the specified value to the handler.</summary>
 2992            /// <param name="value">The value to write.</param>
 2993            /// <typeparam name="T">The type of the value to write.</typeparam>
 2994            public void AppendFormatted<T>(T value)
 2995            {
 2996                // This method could delegate to AppendFormatted with a null format, but explicitly passing
 2997                // default as the format to TryFormat helps to improve code quality in some cases when TryFormat is inli
 2998                // e.g. for Int32 it enables the JIT to eliminate code in the inlined method based on a length check on 
 2999
 03000                if (_hasCustomFormatter)
 3001                {
 3002                    // If there's a custom formatter, always use it.
 03003                    AppendCustomFormatter(value, format: null);
 03004                    return;
 3005                }
 3006
 03007                if (value is null)
 3008                {
 03009                    return;
 3010                }
 3011
 03012                if (value is IFormattable)
 3013                {
 3014                    // Check first for IFormattable, even though we'll prefer to use ISpanFormattable, as the latter
 3015                    // requires the former.  For value types, it won't matter as the type checks devolve into
 3016                    // JIT-time constants.  For reference types, they're more likely to implement IFormattable
 3017                    // than they are to implement ISpanFormattable: if they don't implement either, we save an
 3018                    // interface check over first checking for ISpanFormattable and then for IFormattable, and
 3019                    // if it only implements IFormattable, we come out even: only if it implements both do we
 3020                    // end up paying for an extra interface check.
 3021
 03022                    if (typeof(T).IsEnum)
 3023                    {
 03024                        if (Enum.TryFormatUnconstrained(value, _stringBuilder.RemainingCurrentChunk, out int charsWritte
 3025                        {
 03026                            _stringBuilder.m_ChunkLength += charsWritten;
 3027                        }
 3028                        else
 3029                        {
 03030                            AppendFormattedWithTempSpace(value, 0, format: null);
 3031                        }
 3032                    }
 03033                    else if (value is ISpanFormattable)
 3034                    {
 03035                        Span<char> destination = _stringBuilder.RemainingCurrentChunk;
 03036                        if (((ISpanFormattable)value).TryFormat(destination, out int charsWritten, default, _provider)) 
 3037                        {
 03038                            if ((uint)charsWritten > (uint)destination.Length)
 3039                            {
 3040                                // Protect against faulty ISpanFormattable implementations returning invalid charsWritte
 3041                                // Other code in _stringBuilder uses Unsafe manipulation, and we want to ensure m_ChunkL
 03042                                ThrowHelper.ThrowFormatInvalidString();
 3043                            }
 3044
 03045                            _stringBuilder.m_ChunkLength += charsWritten;
 3046                        }
 3047                        else
 3048                        {
 3049                            // Not enough room in the current chunk.  Take the slow path that formats into temporary spa
 3050                            // and then copies the result into the StringBuilder.
 03051                            AppendFormattedWithTempSpace(value, 0, format: null);
 3052                        }
 3053                    }
 3054                    else
 3055                    {
 03056                        _stringBuilder.Append(((IFormattable)value).ToString(format: null, _provider)); // constrained c
 3057                    }
 3058                }
 3059                else
 3060                {
 03061                    _stringBuilder.Append(value.ToString());
 3062                }
 03063            }
 3064
 3065            /// <summary>Writes the specified value to the handler.</summary>
 3066            /// <param name="value">The value to write.</param>
 3067            /// <param name="format">The format string.</param>
 3068            /// <typeparam name="T">The type of the value to write.</typeparam>
 3069            public void AppendFormatted<T>(T value, string? format)
 3070            {
 03071                if (_hasCustomFormatter)
 3072                {
 3073                    // If there's a custom formatter, always use it.
 03074                    AppendCustomFormatter(value, format);
 03075                    return;
 3076                }
 3077
 03078                if (value is null)
 3079                {
 03080                    return;
 3081                }
 3082
 03083                if (value is IFormattable)
 3084                {
 3085                    // Check first for IFormattable, even though we'll prefer to use ISpanFormattable, as the latter
 3086                    // requires the former.  For value types, it won't matter as the type checks devolve into
 3087                    // JIT-time constants.  For reference types, they're more likely to implement IFormattable
 3088                    // than they are to implement ISpanFormattable: if they don't implement either, we save an
 3089                    // interface check over first checking for ISpanFormattable and then for IFormattable, and
 3090                    // if it only implements IFormattable, we come out even: only if it implements both do we
 3091                    // end up paying for an extra interface check.
 3092
 03093                    if (typeof(T).IsEnum)
 3094                    {
 03095                        if (Enum.TryFormatUnconstrained(value, _stringBuilder.RemainingCurrentChunk, out int charsWritte
 3096                        {
 03097                            _stringBuilder.m_ChunkLength += charsWritten;
 3098                        }
 3099                        else
 3100                        {
 03101                            AppendFormattedWithTempSpace(value, 0, format);
 3102                        }
 3103                    }
 03104                    else if (value is ISpanFormattable)
 3105                    {
 03106                        Span<char> destination = _stringBuilder.RemainingCurrentChunk;
 03107                        if (((ISpanFormattable)value).TryFormat(destination, out int charsWritten, format, _provider)) /
 3108                        {
 03109                            if ((uint)charsWritten > (uint)destination.Length)
 3110                            {
 3111                                // Protect against faulty ISpanFormattable implementations returning invalid charsWritte
 3112                                // Other code in _stringBuilder uses Unsafe manipulation, and we want to ensure m_ChunkL
 03113                                ThrowHelper.ThrowFormatInvalidString();
 3114                            }
 3115
 03116                            _stringBuilder.m_ChunkLength += charsWritten;
 3117                        }
 3118                        else
 3119                        {
 3120                            // Not enough room in the current chunk.  Take the slow path that formats into temporary spa
 3121                            // and then copies the result into the StringBuilder.
 03122                            AppendFormattedWithTempSpace(value, 0, format);
 3123                        }
 3124                    }
 3125                    else
 3126                    {
 03127                        _stringBuilder.Append(((IFormattable)value).ToString(format, _provider)); // constrained call av
 3128                    }
 3129                }
 3130                else
 3131                {
 03132                    _stringBuilder.Append(value.ToString());
 3133                }
 03134            }
 3135
 3136            /// <summary>Writes the specified value to the handler.</summary>
 3137            /// <param name="value">The value to write.</param>
 3138            /// <param name="alignment">Minimum number of characters that should be written for this value.  If the valu
 3139            /// <typeparam name="T">The type of the value to write.</typeparam>
 3140            public void AppendFormatted<T>(T value, int alignment) =>
 03141                AppendFormatted(value, alignment, format: null);
 3142
 3143            /// <summary>Writes the specified value to the handler.</summary>
 3144            /// <param name="value">The value to write.</param>
 3145            /// <param name="format">The format string.</param>
 3146            /// <param name="alignment">Minimum number of characters that should be written for this value.  If the valu
 3147            /// <typeparam name="T">The type of the value to write.</typeparam>
 3148            public void AppendFormatted<T>(T value, int alignment, string? format)
 3149            {
 03150                if (alignment == 0)
 3151                {
 3152                    // This overload is used as a fallback from several disambiguation overloads, so special-case 0.
 03153                    AppendFormatted(value, format);
 3154                }
 03155                else if (alignment < 0)
 3156                {
 3157                    // Left aligned: format into the handler, then append any additional padding required.
 03158                    int start = _stringBuilder.Length;
 03159                    AppendFormatted(value, format);
 03160                    int paddingRequired = -alignment - (_stringBuilder.Length - start);
 03161                    if (paddingRequired > 0)
 3162                    {
 03163                        _stringBuilder.Append(' ', paddingRequired);
 3164                    }
 3165                }
 3166                else
 3167                {
 3168                    // Right aligned: format into temporary space and then copy that into the handler, appropriately ali
 03169                    AppendFormattedWithTempSpace(value, alignment, format);
 3170                }
 03171            }
 3172
 3173            /// <summary>Formats into temporary space and then appends the result into the StringBuilder.</summary>
 3174            private unsafe void AppendFormattedWithTempSpace<T>(T value, int alignment, string? format)
 3175            {
 3176                // It's expected that either there's not enough space in the current chunk to store this formatted value
 3177                // or we have a non-0 alignment that could require padding inserted. So format into temporary space and
 3178                // then append that written span into the StringBuilder: StringBuilder.Append(span) is able to split the
 3179                // span across the current chunk and any additional chunks required.
 3180
 03181                var handler = new DefaultInterpolatedStringHandler(0, 0, _provider, stackalloc char[string.StackallocCha
 03182                handler.AppendFormatted(value, format);
 03183                AppendFormatted(handler.Text, alignment);
 03184                handler.Clear();
 03185            }
 3186            #endregion
 3187
 3188            #region AppendFormatted ReadOnlySpan<char>
 3189            /// <summary>Writes the specified character span to the handler.</summary>
 3190            /// <param name="value">The span to write.</param>
 03191            public void AppendFormatted(ReadOnlySpan<char> value) => _stringBuilder.Append(value);
 3192
 3193            /// <summary>Writes the specified string of chars to the handler.</summary>
 3194            /// <param name="value">The span to write.</param>
 3195            /// <param name="alignment">Minimum number of characters that should be written for this value.  If the valu
 3196            /// <param name="format">The format string.</param>
 3197            public void AppendFormatted(ReadOnlySpan<char> value, int alignment = 0, string? format = null)
 3198            {
 03199                if (alignment == 0)
 3200                {
 03201                    _stringBuilder.Append(value);
 3202                }
 3203                else
 3204                {
 03205                    bool leftAlign = false;
 03206                    if (alignment < 0)
 3207                    {
 03208                        leftAlign = true;
 03209                        alignment = -alignment;
 3210                    }
 3211
 03212                    int paddingRequired = alignment - value.Length;
 03213                    if (paddingRequired <= 0)
 3214                    {
 03215                        _stringBuilder.Append(value);
 3216                    }
 03217                    else if (leftAlign)
 3218                    {
 03219                        _stringBuilder.Append(value);
 03220                        _stringBuilder.Append(' ', paddingRequired);
 3221                    }
 3222                    else
 3223                    {
 03224                        _stringBuilder.Append(' ', paddingRequired);
 03225                        _stringBuilder.Append(value);
 3226                    }
 3227                }
 03228            }
 3229            #endregion
 3230
 3231            #region AppendFormatted string
 3232            /// <summary>Writes the specified value to the handler.</summary>
 3233            /// <param name="value">The value to write.</param>
 3234            public void AppendFormatted(string? value)
 3235            {
 03236                if (!_hasCustomFormatter)
 3237                {
 03238                    _stringBuilder.Append(value);
 3239                }
 3240                else
 3241                {
 03242                    AppendFormatted<string?>(value);
 3243                }
 03244            }
 3245
 3246            /// <summary>Writes the specified value to the handler.</summary>
 3247            /// <param name="value">The value to write.</param>
 3248            /// <param name="alignment">Minimum number of characters that should be written for this value.  If the valu
 3249            /// <param name="format">The format string.</param>
 3250            public void AppendFormatted(string? value, int alignment = 0, string? format = null) =>
 3251                // Format is meaningless for strings and doesn't make sense for someone to specify.  We have the overloa
 3252                // simply to disambiguate between ROS<char> and object, just in case someone does specify a format, as
 3253                // string is implicitly convertible to both. Just delegate to the T-based implementation.
 03254                AppendFormatted<string?>(value, alignment, format);
 3255            #endregion
 3256
 3257            #region AppendFormatted object
 3258            /// <summary>Writes the specified value to the handler.</summary>
 3259            /// <param name="value">The value to write.</param>
 3260            /// <param name="alignment">Minimum number of characters that should be written for this value.  If the valu
 3261            /// <param name="format">The format string.</param>
 3262            public void AppendFormatted(object? value, int alignment = 0, string? format = null) =>
 3263                // This overload is expected to be used rarely, only if either a) something strongly typed as object is
 3264                // formatted with both an alignment and a format, or b) the compiler is unable to target type to T. It
 3265                // exists purely to help make cases from (b) compile. Just delegate to the T-based implementation.
 03266                AppendFormatted<object?>(value, alignment, format);
 3267            #endregion
 3268            #endregion
 3269
 3270            /// <summary>Formats the value using the custom formatter from the provider.</summary>
 3271            /// <param name="value">The value to write.</param>
 3272            /// <param name="format">The format string.</param>
 3273            /// <typeparam name="T">The type of the value to write.</typeparam>
 3274            [MethodImpl(MethodImplOptions.NoInlining)]
 3275            private void AppendCustomFormatter<T>(T value, string? format)
 3276            {
 3277                // This case is very rare, but we need to handle it prior to the other checks in case
 3278                // a provider was used that supplied an ICustomFormatter which wanted to intercept the particular value.
 3279                // We do the cast here rather than in the ctor, even though this could be executed multiple times per
 3280                // formatting, to make the cast pay for play.
 03281                Debug.Assert(_hasCustomFormatter);
 03282                Debug.Assert(_provider != null);
 3283
 03284                ICustomFormatter? formatter = (ICustomFormatter?)_provider.GetFormat(typeof(ICustomFormatter));
 03285                Debug.Assert(formatter != null, "An incorrectly written provider said it implemented ICustomFormatter, a
 3286
 03287                if (formatter is not null)
 3288                {
 03289                    _stringBuilder.Append(formatter.Format(format, value, _provider));
 3290                }
 03291            }
 3292        }
 3293    }
 3294}
 3295

Methods/Properties

GetReplaceBufferCapacity(System.Int32)
ReplaceBufferInternal(System.Char*,System.Int32)
ReplaceBufferUtf8Internal(System.ReadOnlySpan`1<System.Byte>)
ReplaceBufferAnsiInternal(System.SByte*,System.Int32)
InternalCopy(System.IntPtr,System.Int32)
.ctor()
.ctor(System.Int32)
.ctor(System.String)
.ctor(System.String,System.Int32)
.ctor(System.String,System.Int32,System.Int32,System.Int32)
.ctor(System.Int32,System.Int32)
.ctor(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext)
System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext)
AssertInvariants()
Capacity()
Capacity(System.Int32)
MaxCapacity()
EnsureCapacity(System.Int32)
ToString()
ToString(System.Int32,System.Int32)
Clear()
MoveChunks(System.Text.StringBuilder)
Length()
Length(System.Int32)
Chars(System.Int32)
Chars(System.Int32,System.Char)
GetChunks()
GetEnumerator()
MoveNext()
Current()
.ctor(System.Text.StringBuilder)
ChunkCount(System.Text.StringBuilder)
MoveNext(System.Text.StringBuilder&)
.ctor(System.Text.StringBuilder,System.Int32)
EnumerateRunes()
Append(System.Char,System.Int32)
AppendWithExpansion(System.Char,System.Int32)
Append(System.Char[],System.Int32,System.Int32)
Append(System.String)
Append(System.String,System.Int32,System.Int32)
Append(System.Text.StringBuilder)
Append(System.Text.StringBuilder,System.Int32,System.Int32)
AppendCore(System.Text.StringBuilder,System.Int32,System.Int32)
AppendLine()
AppendLine(System.String)
CopyTo(System.Int32,System.Char[],System.Int32,System.Int32)
CopyTo(System.Int32,System.Span`1<System.Char>,System.Int32)
Insert(System.Int32,System.String,System.Int32)
Insert(System.Int32,System.ReadOnlySpan`1<System.Char>,System.Int32)
Remove(System.Int32,System.Int32)
Append(System.Boolean)
Append(System.Char)
AppendWithExpansion(System.Char)
Append(System.Text.Rune)
Append(System.SByte)
Append(System.Byte)
Append(System.Int16)
Append(System.Int32)
Append(System.Int64)
Append(System.Single)
Append(System.Double)
Append(System.Decimal)
Append(System.UInt16)
Append(System.UInt32)
Append(System.UInt64)
AppendSpanFormattable(T)
Append(System.Object)
Append(System.Char[])
Append(System.ReadOnlySpan`1<System.Char>)
Append(System.ReadOnlyMemory`1<System.Char>)
Append(System.Text.StringBuilder/AppendInterpolatedStringHandler&)
Append(System.IFormatProvider,System.Text.StringBuilder/AppendInterpolatedStringHandler&)
AppendLine(System.Text.StringBuilder/AppendInterpolatedStringHandler&)
AppendLine(System.IFormatProvider,System.Text.StringBuilder/AppendInterpolatedStringHandler&)
AppendJoin(System.String,System.Object[])
AppendJoin(System.String,System.ReadOnlySpan`1<System.Object>)
AppendJoin(System.String,System.Collections.Generic.IEnumerable`1<T>)
AppendJoin(System.String,System.String[])
AppendJoin(System.String,System.ReadOnlySpan`1<System.String>)
AppendJoin(System.Char,System.Object[])
AppendJoin(System.Char,System.ReadOnlySpan`1<System.Object>)
AppendJoin(System.Char,System.Collections.Generic.IEnumerable`1<T>)
AppendJoin(System.Char,System.String[])
AppendJoin(System.Char,System.ReadOnlySpan`1<System.String>)
AppendJoinCore(System.Char&,System.Int32,System.Collections.Generic.IEnumerable`1<T>)
AppendJoinCore(System.Char&,System.Int32,System.ReadOnlySpan`1<T>)
Insert(System.Int32,System.String)
Insert(System.Int32,System.Boolean)
Insert(System.Int32,System.SByte)
Insert(System.Int32,System.Byte)
Insert(System.Int32,System.Int16)
Insert(System.Int32,System.Char)
Insert(System.Int32,System.Text.Rune)
Insert(System.Int32,System.Char[])
Insert(System.Int32,System.Char[],System.Int32,System.Int32)
Insert(System.Int32,System.Int32)
Insert(System.Int32,System.Int64)
Insert(System.Int32,System.Single)
Insert(System.Int32,System.Double)
Insert(System.Int32,System.Decimal)
Insert(System.Int32,System.UInt16)
Insert(System.Int32,System.UInt32)
Insert(System.Int32,System.UInt64)
Insert(System.Int32,System.Object)
Insert(System.Int32,System.ReadOnlySpan`1<System.Char>)
InsertSpanFormattable(System.Int32,T)
AppendFormat(System.String,System.Object)
AppendFormat(System.String,System.Object,System.Object)
AppendFormat(System.String,System.Object,System.Object,System.Object)
AppendFormat(System.String,System.Object[])
AppendFormat(System.String,System.ReadOnlySpan`1<System.Object>)
AppendFormat(System.IFormatProvider,System.String,System.Object)
AppendFormat(System.IFormatProvider,System.String,System.Object,System.Object)
AppendFormat(System.IFormatProvider,System.String,System.Object,System.Object,System.Object)
AppendFormat(System.IFormatProvider,System.String,System.Object[])
AppendFormat(System.IFormatProvider,System.String,System.ReadOnlySpan`1<System.Object>)
MoveNext(System.String,System.Int32&)
AppendFormat(System.IFormatProvider,System.Text.CompositeFormat,TArg0)
AppendFormat(System.IFormatProvider,System.Text.CompositeFormat,TArg0,TArg1)
AppendFormat(System.IFormatProvider,System.Text.CompositeFormat,TArg0,TArg1,TArg2)
AppendFormat(System.IFormatProvider,System.Text.CompositeFormat,System.Object[])
AppendFormat(System.IFormatProvider,System.Text.CompositeFormat,System.ReadOnlySpan`1<System.Object>)
AppendFormat(System.IFormatProvider,System.Text.CompositeFormat,TArg0,TArg1,TArg2,System.ReadOnlySpan`1<System.Object>)
Replace(System.String,System.String)
Replace(System.ReadOnlySpan`1<System.Char>,System.ReadOnlySpan`1<System.Char>)
Equals(System.Text.StringBuilder)
Equals(System.ReadOnlySpan`1<System.Char>)
Replace(System.String,System.String,System.Int32,System.Int32)
Replace(System.ReadOnlySpan`1<System.Char>,System.ReadOnlySpan`1<System.Char>,System.Int32,System.Int32)
Replace(System.Char,System.Char)
Replace(System.Char,System.Char,System.Int32,System.Int32)
Replace(System.Text.Rune,System.Text.Rune)
Replace(System.Text.Rune,System.Text.Rune,System.Int32,System.Int32)
Append(System.Char*,System.Int32)
Append(System.Char&,System.Int32)
AppendWithExpansion(System.Char&,System.Int32)
Insert(System.Int32,System.Char&,System.Int32)
ReplaceAllInChunk(System.ReadOnlySpan`1<System.Int32>,System.Text.StringBuilder,System.Int32,System.ReadOnlySpan`1<System.Char>)
StartsWith(System.Text.StringBuilder,System.Int32,System.Int32,System.ReadOnlySpan`1<System.Char>)
ReplaceInPlaceAtChunk(System.Text.StringBuilder&,System.Int32&,System.Char&,System.Int32)
FindChunkForIndex(System.Int32)
RemainingCurrentChunk()
Next(System.Text.StringBuilder)
ExpandByABlock(System.Int32)
.ctor(System.Text.StringBuilder)
MakeRoom(System.Int32,System.Int32,System.Text.StringBuilder&,System.Int32&,System.Boolean)
.ctor(System.Int32,System.Int32,System.Text.StringBuilder)
Remove(System.Int32,System.Int32,System.Text.StringBuilder&,System.Int32&)
GetRuneAt(System.Int32)
TryGetRuneAt(System.Int32,System.Text.Rune&)
.ctor(System.Int32,System.Int32,System.Text.StringBuilder)
.ctor(System.Int32,System.Int32,System.Text.StringBuilder,System.IFormatProvider)
AppendLiteral(System.String)
AppendFormatted(T)
AppendFormatted(T,System.String)
AppendFormatted(T,System.Int32)
AppendFormatted(T,System.Int32,System.String)
AppendFormattedWithTempSpace(T,System.Int32,System.String)
AppendFormatted(System.ReadOnlySpan`1<System.Char>)
AppendFormatted(System.ReadOnlySpan`1<System.Char>,System.Int32,System.String)
AppendFormatted(System.String)
AppendFormatted(System.String,System.Int32,System.String)
AppendFormatted(System.Object,System.Int32,System.String)
AppendCustomFormatter(T,System.String)