| | | 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 | | |
| | | 4 | | using System.Buffers; |
| | | 5 | | using System.Collections; |
| | | 6 | | using System.Collections.Generic; |
| | | 7 | | using System.ComponentModel; |
| | | 8 | | using System.Diagnostics; |
| | | 9 | | using System.Diagnostics.CodeAnalysis; |
| | | 10 | | using System.Runtime.CompilerServices; |
| | | 11 | | using System.Runtime.InteropServices; |
| | | 12 | | using System.Runtime.Serialization; |
| | | 13 | | |
| | | 14 | | namespace 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> |
| | 16 | 78 | | public StringBuilder() |
| | | 79 | | { |
| | 16 | 80 | | m_MaxCapacity = int.MaxValue; |
| | 16 | 81 | | m_ChunkChars = new char[DefaultCapacity]; |
| | 16 | 82 | | } |
| | | 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) |
| | 8713 | 89 | | : this(capacity, int.MaxValue) |
| | | 90 | | { |
| | 8713 | 91 | | } |
| | | 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) |
| | 0 | 98 | | : this(value, DefaultCapacity) |
| | | 99 | | { |
| | 0 | 100 | | } |
| | | 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) |
| | 0 | 108 | | : this(value, 0, value?.Length ?? 0, capacity) |
| | | 109 | | { |
| | 0 | 110 | | } |
| | | 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> |
| | 0 | 119 | | public StringBuilder(string? value, int startIndex, int length, int capacity) |
| | | 120 | | { |
| | 0 | 121 | | ArgumentOutOfRangeException.ThrowIfNegative(capacity); |
| | 0 | 122 | | ArgumentOutOfRangeException.ThrowIfNegative(length); |
| | 0 | 123 | | ArgumentOutOfRangeException.ThrowIfNegative(startIndex); |
| | | 124 | | |
| | 0 | 125 | | value ??= string.Empty; |
| | | 126 | | |
| | 0 | 127 | | if (startIndex > value.Length - length) |
| | | 128 | | { |
| | 0 | 129 | | throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexLength); |
| | | 130 | | } |
| | | 131 | | |
| | 0 | 132 | | m_MaxCapacity = int.MaxValue; |
| | 0 | 133 | | if (capacity == 0) |
| | | 134 | | { |
| | 0 | 135 | | capacity = DefaultCapacity; |
| | | 136 | | } |
| | 0 | 137 | | capacity = Math.Max(capacity, length); |
| | | 138 | | |
| | 0 | 139 | | m_ChunkChars = GC.AllocateUninitializedArray<char>(capacity); |
| | 0 | 140 | | m_ChunkLength = length; |
| | | 141 | | |
| | 0 | 142 | | value.AsSpan(startIndex, length).CopyTo(m_ChunkChars); |
| | 0 | 143 | | } |
| | | 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> |
| | 8713 | 150 | | public StringBuilder(int capacity, int maxCapacity) |
| | | 151 | | { |
| | 8713 | 152 | | if (capacity > maxCapacity) |
| | | 153 | | { |
| | 0 | 154 | | throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_Capacity); |
| | | 155 | | } |
| | 8713 | 156 | | ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxCapacity); |
| | 8713 | 157 | | ArgumentOutOfRangeException.ThrowIfNegative(capacity); |
| | | 158 | | |
| | 8713 | 159 | | if (capacity == 0) |
| | | 160 | | { |
| | 0 | 161 | | capacity = Math.Min(DefaultCapacity, maxCapacity); |
| | | 162 | | } |
| | | 163 | | |
| | 8713 | 164 | | m_MaxCapacity = maxCapacity; |
| | 8713 | 165 | | m_ChunkChars = GC.AllocateUninitializedArray<char>(capacity); |
| | 8713 | 166 | | } |
| | | 167 | | |
| | 0 | 168 | | private StringBuilder(SerializationInfo info, StreamingContext context) |
| | | 169 | | { |
| | 0 | 170 | | ArgumentNullException.ThrowIfNull(info); |
| | | 171 | | |
| | 0 | 172 | | int persistedCapacity = 0; |
| | 0 | 173 | | string? persistedString = null; |
| | 0 | 174 | | int persistedMaxCapacity = int.MaxValue; |
| | 0 | 175 | | bool capacityPresent = false; |
| | | 176 | | |
| | | 177 | | // Get the data |
| | 0 | 178 | | SerializationInfoEnumerator enumerator = info.GetEnumerator(); |
| | 0 | 179 | | while (enumerator.MoveNext()) |
| | | 180 | | { |
| | 0 | 181 | | switch (enumerator.Name) |
| | | 182 | | { |
| | | 183 | | case MaxCapacityField: |
| | 0 | 184 | | persistedMaxCapacity = info.GetInt32(MaxCapacityField); |
| | 0 | 185 | | break; |
| | | 186 | | case StringValueField: |
| | 0 | 187 | | persistedString = info.GetString(StringValueField); |
| | 0 | 188 | | break; |
| | | 189 | | case CapacityField: |
| | 0 | 190 | | persistedCapacity = info.GetInt32(CapacityField); |
| | 0 | 191 | | capacityPresent = true; |
| | | 192 | | break; |
| | | 193 | | default: |
| | | 194 | | // Ignore other fields for forwards-compatibility. |
| | | 195 | | break; |
| | | 196 | | } |
| | | 197 | | } |
| | | 198 | | |
| | | 199 | | // Check values and set defaults |
| | 0 | 200 | | persistedString ??= string.Empty; |
| | 0 | 201 | | if (persistedMaxCapacity < 1 || persistedString.Length > persistedMaxCapacity) |
| | | 202 | | { |
| | 0 | 203 | | throw new SerializationException(SR.Serialization_StringBuilderMaxCapacity); |
| | | 204 | | } |
| | | 205 | | |
| | 0 | 206 | | if (!capacityPresent) |
| | | 207 | | { |
| | | 208 | | // StringBuilder in V1.X did not persist the Capacity, so this is a valid legacy code path. |
| | 0 | 209 | | persistedCapacity = Math.Min(Math.Max(DefaultCapacity, persistedString.Length), persistedMaxCapacity); |
| | | 210 | | } |
| | | 211 | | |
| | 0 | 212 | | if (persistedCapacity < 0 || persistedCapacity < persistedString.Length || persistedCapacity > persistedMaxC |
| | | 213 | | { |
| | 0 | 214 | | throw new SerializationException(SR.Serialization_StringBuilderCapacity); |
| | | 215 | | } |
| | | 216 | | |
| | | 217 | | // Assign |
| | 0 | 218 | | m_MaxCapacity = persistedMaxCapacity; |
| | 0 | 219 | | m_ChunkChars = GC.AllocateUninitializedArray<char>(persistedCapacity); |
| | 0 | 220 | | persistedString.CopyTo(0, m_ChunkChars, 0, persistedString.Length); |
| | 0 | 221 | | m_ChunkLength = persistedString.Length; |
| | 0 | 222 | | AssertInvariants(); |
| | 0 | 223 | | } |
| | | 224 | | |
| | | 225 | | void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) |
| | | 226 | | { |
| | 0 | 227 | | ArgumentNullException.ThrowIfNull(info); |
| | | 228 | | |
| | 0 | 229 | | AssertInvariants(); |
| | 0 | 230 | | info.AddValue(MaxCapacityField, m_MaxCapacity); |
| | 0 | 231 | | info.AddValue(CapacityField, Capacity); |
| | 0 | 232 | | info.AddValue(StringValueField, ToString()); |
| | | 233 | | // Note: persist "m_currentThread" to be compatible with old versions |
| | 0 | 234 | | info.AddValue(ThreadIDField, 0); |
| | 0 | 235 | | } |
| | | 236 | | |
| | | 237 | | [Conditional("DEBUG")] |
| | | 238 | | private void AssertInvariants() |
| | | 239 | | { |
| | 8874 | 240 | | Debug.Assert(m_ChunkOffset + m_ChunkChars.Length >= m_ChunkOffset, "The length of the string is greater than |
| | | 241 | | |
| | 8874 | 242 | | StringBuilder currentBlock = this; |
| | 8874 | 243 | | int maxCapacity = this.m_MaxCapacity; |
| | 235 | 244 | | while (true) |
| | | 245 | | { |
| | | 246 | | // All blocks have the same max capacity. |
| | 9109 | 247 | | Debug.Assert(currentBlock.m_MaxCapacity == maxCapacity); |
| | 9109 | 248 | | Debug.Assert(currentBlock.m_ChunkChars != null); |
| | | 249 | | |
| | 9109 | 250 | | Debug.Assert(currentBlock.m_ChunkLength <= currentBlock.m_ChunkChars.Length); |
| | 9109 | 251 | | Debug.Assert(currentBlock.m_ChunkLength >= 0); |
| | 9109 | 252 | | Debug.Assert(currentBlock.m_ChunkOffset >= 0); |
| | | 253 | | |
| | 9109 | 254 | | StringBuilder? prevBlock = currentBlock.m_ChunkPrevious; |
| | 9109 | 255 | | if (prevBlock == null) |
| | | 256 | | { |
| | 8874 | 257 | | Debug.Assert(currentBlock.m_ChunkOffset == 0); |
| | 8874 | 258 | | break; |
| | | 259 | | } |
| | | 260 | | // There are no gaps in the blocks. |
| | 235 | 261 | | Debug.Assert(currentBlock.m_ChunkOffset == prevBlock.m_ChunkOffset + prevBlock.m_ChunkLength); |
| | 235 | 262 | | currentBlock = prevBlock; |
| | | 263 | | } |
| | | 264 | | } |
| | | 265 | | |
| | | 266 | | public int Capacity |
| | | 267 | | { |
| | 37 | 268 | | get => m_ChunkChars.Length + m_ChunkOffset; |
| | | 269 | | set |
| | | 270 | | { |
| | 0 | 271 | | ArgumentOutOfRangeException.ThrowIfNegative(value); |
| | 0 | 272 | | if (value > MaxCapacity) |
| | | 273 | | { |
| | 0 | 274 | | throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_Capacity); |
| | | 275 | | } |
| | 0 | 276 | | if (value < Length) |
| | | 277 | | { |
| | 0 | 278 | | throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity); |
| | | 279 | | } |
| | | 280 | | |
| | 0 | 281 | | if (Capacity != value) |
| | | 282 | | { |
| | 0 | 283 | | int newLen = value - m_ChunkOffset; |
| | 0 | 284 | | char[] newArray = GC.AllocateUninitializedArray<char>(newLen); |
| | 0 | 285 | | Array.Copy(m_ChunkChars, newArray, m_ChunkLength); |
| | 0 | 286 | | m_ChunkChars = newArray; |
| | | 287 | | } |
| | 0 | 288 | | } |
| | | 289 | | } |
| | | 290 | | |
| | | 291 | | /// <summary> |
| | | 292 | | /// Gets the maximum capacity this builder is allowed to have. |
| | | 293 | | /// </summary> |
| | 0 | 294 | | 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 | | { |
| | 0 | 306 | | ArgumentOutOfRangeException.ThrowIfNegative(capacity); |
| | | 307 | | |
| | 0 | 308 | | if (Capacity < capacity) |
| | | 309 | | { |
| | 0 | 310 | | Capacity = capacity; |
| | | 311 | | } |
| | 0 | 312 | | return Capacity; |
| | | 313 | | } |
| | | 314 | | |
| | | 315 | | public override string ToString() |
| | | 316 | | { |
| | 8729 | 317 | | AssertInvariants(); |
| | | 318 | | |
| | 8729 | 319 | | if (Length == 0) |
| | | 320 | | { |
| | 0 | 321 | | return string.Empty; |
| | | 322 | | } |
| | | 323 | | |
| | 8729 | 324 | | string result = string.FastAllocateString(Length); |
| | 8729 | 325 | | StringBuilder? chunk = this; |
| | | 326 | | do |
| | | 327 | | { |
| | 8766 | 328 | | if (chunk.m_ChunkLength > 0) |
| | | 329 | | { |
| | | 330 | | // Copy these into local variables so that they are stable even in the presence of race conditions |
| | 8766 | 331 | | char[] sourceArray = chunk.m_ChunkChars; |
| | 8766 | 332 | | int chunkOffset = chunk.m_ChunkOffset; |
| | 8766 | 333 | | int chunkLength = chunk.m_ChunkLength; |
| | | 334 | | |
| | | 335 | | // Check that we will not overrun our boundaries. |
| | 8766 | 336 | | if ((uint)(chunkLength + chunkOffset) > (uint)result.Length || (uint)chunkLength > (uint)sourceArray |
| | | 337 | | { |
| | 0 | 338 | | throw new ArgumentOutOfRangeException(null, SR.InvalidOperation_ConcurrentOperationsNotSupported |
| | | 339 | | } |
| | | 340 | | |
| | 8766 | 341 | | Buffer.Memmove( |
| | 8766 | 342 | | ref Unsafe.Add(ref result.GetRawStringData(), chunkOffset), |
| | 8766 | 343 | | ref MemoryMarshal.GetArrayDataReference(sourceArray), |
| | 8766 | 344 | | (nuint)chunkLength); |
| | | 345 | | } |
| | 8766 | 346 | | chunk = chunk.m_ChunkPrevious; |
| | | 347 | | } |
| | 8766 | 348 | | while (chunk != null); |
| | | 349 | | |
| | 8729 | 350 | | 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 | | { |
| | 0 | 360 | | int currentLength = this.Length; |
| | 0 | 361 | | ArgumentOutOfRangeException.ThrowIfNegative(startIndex); |
| | 0 | 362 | | if (startIndex > currentLength) |
| | | 363 | | { |
| | 0 | 364 | | throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndexLargerThanLeng |
| | | 365 | | } |
| | 0 | 366 | | ArgumentOutOfRangeException.ThrowIfNegative(length); |
| | 0 | 367 | | if (startIndex > currentLength - length) |
| | | 368 | | { |
| | 0 | 369 | | throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexLength); |
| | | 370 | | } |
| | | 371 | | |
| | 0 | 372 | | AssertInvariants(); |
| | 0 | 373 | | string result = string.FastAllocateString(length); |
| | 0 | 374 | | CopyTo(startIndex, new Span<char>(ref result.GetRawStringData(), result.Length), result.Length); |
| | 0 | 375 | | return result; |
| | | 376 | | } |
| | | 377 | | |
| | | 378 | | public StringBuilder Clear() |
| | | 379 | | { |
| | 0 | 380 | | this.Length = 0; |
| | 0 | 381 | | 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 | | { |
| | 0 | 410 | | ArgumentNullException.ThrowIfNull(source); |
| | | 411 | | |
| | 0 | 412 | | StringBuilder destination = new StringBuilder(source); |
| | | 413 | | |
| | 0 | 414 | | source.m_ChunkChars = []; |
| | 0 | 415 | | source.m_ChunkPrevious = null; |
| | 0 | 416 | | source.m_ChunkLength = 0; |
| | 0 | 417 | | source.m_ChunkOffset = 0; |
| | | 418 | | |
| | 0 | 419 | | return destination; |
| | | 420 | | } |
| | | 421 | | |
| | | 422 | | /// <summary> |
| | | 423 | | /// Gets or sets the length of this builder. |
| | | 424 | | /// </summary> |
| | | 425 | | public int Length |
| | | 426 | | { |
| | 17640 | 427 | | get => m_ChunkOffset + m_ChunkLength; |
| | | 428 | | set |
| | | 429 | | { |
| | | 430 | | // If the new length is less than 0 or greater than our Maximum capacity, bail. |
| | 0 | 431 | | ArgumentOutOfRangeException.ThrowIfNegative(value); |
| | | 432 | | |
| | 0 | 433 | | if (value > MaxCapacity) |
| | | 434 | | { |
| | 0 | 435 | | throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity); |
| | | 436 | | } |
| | | 437 | | |
| | 0 | 438 | | if (value == 0 && m_ChunkPrevious == null) |
| | | 439 | | { |
| | 0 | 440 | | m_ChunkLength = 0; |
| | 0 | 441 | | m_ChunkOffset = 0; |
| | 0 | 442 | | return; |
| | | 443 | | } |
| | | 444 | | |
| | 0 | 445 | | int delta = value - Length; |
| | 0 | 446 | | if (delta > 0) |
| | | 447 | | { |
| | | 448 | | // Pad ourselves with null characters. |
| | 0 | 449 | | Append('\0', delta); |
| | | 450 | | } |
| | | 451 | | else |
| | | 452 | | { |
| | 0 | 453 | | StringBuilder chunk = FindChunkForIndex(value); |
| | 0 | 454 | | if (chunk != this) |
| | | 455 | | { |
| | | 456 | | // Avoid possible infinite capacity growth. See https://github.com/dotnet/coreclr/pull/16926 |
| | 0 | 457 | | int capacityToPreserve = Math.Min(Capacity, Math.Max(Length * 6 / 5, m_ChunkChars.Length)); |
| | 0 | 458 | | int newLen = capacityToPreserve - chunk.m_ChunkOffset; |
| | 0 | 459 | | 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. |
| | 0 | 463 | | char[] newArray = GC.AllocateUninitializedArray<char>(newLen); |
| | 0 | 464 | | Array.Copy(chunk.m_ChunkChars, newArray, chunk.m_ChunkLength); |
| | 0 | 465 | | 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. |
| | 0 | 471 | | Debug.Assert(newLen == chunk.m_ChunkChars.Length, "The new chunk should be larger or equal t |
| | 0 | 472 | | m_ChunkChars = chunk.m_ChunkChars; |
| | | 473 | | } |
| | | 474 | | |
| | 0 | 475 | | m_ChunkPrevious = chunk.m_ChunkPrevious; |
| | 0 | 476 | | m_ChunkOffset = chunk.m_ChunkOffset; |
| | | 477 | | } |
| | 0 | 478 | | m_ChunkLength = value - chunk.m_ChunkOffset; |
| | 0 | 479 | | AssertInvariants(); |
| | | 480 | | } |
| | 0 | 481 | | Debug.Assert(Length == value, "Something went wrong setting Length."); |
| | 0 | 482 | | } |
| | | 483 | | } |
| | | 484 | | |
| | | 485 | | [IndexerName("Chars")] |
| | | 486 | | public char this[int index] |
| | | 487 | | { |
| | | 488 | | get |
| | | 489 | | { |
| | 0 | 490 | | if ((uint)index >= (uint)Length) |
| | | 491 | | { |
| | 0 | 492 | | ThrowHelper.ThrowIndexOutOfRangeException(); |
| | | 493 | | } |
| | | 494 | | |
| | 0 | 495 | | StringBuilder chunk = FindChunkForIndex(index); |
| | 0 | 496 | | return chunk.m_ChunkChars[index - chunk.m_ChunkOffset]; |
| | | 497 | | } |
| | | 498 | | set |
| | | 499 | | { |
| | 0 | 500 | | if ((uint)index >= (uint)Length) |
| | | 501 | | { |
| | 0 | 502 | | ThrowHelper.ThrowArgumentOutOfRange_IndexMustBeLessException(); |
| | | 503 | | } |
| | | 504 | | |
| | 0 | 505 | | StringBuilder chunk = FindChunkForIndex(index); |
| | 0 | 506 | | chunk.m_ChunkChars[index - chunk.m_ChunkOffset] = value; |
| | 0 | 507 | | } |
| | | 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<char> 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<char> chunk in sb.GetChunks()) |
| | | 531 | | /// { |
| | | 532 | | /// var span = chunk.Span; |
| | | 533 | | /// for (int i = 0; i < span.Length; i++) |
| | | 534 | | /// { /* operation on span[i] */ } |
| | | 535 | | /// } |
| | | 536 | | /// </summary> |
| | 0 | 537 | | 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 |
| | 0 | 555 | | public ChunkEnumerator GetEnumerator() { return this; } |
| | | 556 | | |
| | | 557 | | /// <summary> |
| | | 558 | | /// Implements the IEnumerator pattern. |
| | | 559 | | /// </summary> |
| | | 560 | | public bool MoveNext() |
| | | 561 | | { |
| | 0 | 562 | | if (_currentChunk == _firstChunk) |
| | | 563 | | { |
| | 0 | 564 | | return false; |
| | | 565 | | } |
| | | 566 | | |
| | | 567 | | |
| | 0 | 568 | | if (_manyChunks != null) |
| | | 569 | | { |
| | 0 | 570 | | return _manyChunks.MoveNext(ref _currentChunk); |
| | | 571 | | } |
| | | 572 | | |
| | 0 | 573 | | StringBuilder next = _firstChunk; |
| | 0 | 574 | | while (next.m_ChunkPrevious != _currentChunk) |
| | | 575 | | { |
| | 0 | 576 | | Debug.Assert(next.m_ChunkPrevious != null); |
| | 0 | 577 | | next = next.m_ChunkPrevious; |
| | | 578 | | } |
| | 0 | 579 | | _currentChunk = next; |
| | 0 | 580 | | return true; |
| | | 581 | | } |
| | | 582 | | |
| | | 583 | | /// <summary> |
| | | 584 | | /// Implements the IEnumerator pattern. |
| | | 585 | | /// </summary> |
| | | 586 | | public ReadOnlyMemory<char> Current |
| | | 587 | | { |
| | | 588 | | get |
| | | 589 | | { |
| | 0 | 590 | | if (_currentChunk == null) |
| | | 591 | | { |
| | 0 | 592 | | ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); |
| | | 593 | | } |
| | | 594 | | |
| | 0 | 595 | | return new ReadOnlyMemory<char>(_currentChunk.m_ChunkChars, 0, _currentChunk.m_ChunkLength); |
| | | 596 | | } |
| | | 597 | | } |
| | | 598 | | |
| | | 599 | | #region private |
| | | 600 | | internal ChunkEnumerator(StringBuilder stringBuilder) |
| | | 601 | | { |
| | 0 | 602 | | Debug.Assert(stringBuilder != null); |
| | 0 | 603 | | _firstChunk = stringBuilder; |
| | 0 | 604 | | _currentChunk = null; // MoveNext will find the last chunk if we do this. |
| | 0 | 605 | | _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. |
| | 0 | 613 | | int chunkCount = ChunkCount(stringBuilder); |
| | 0 | 614 | | if (8 < chunkCount) |
| | | 615 | | { |
| | 0 | 616 | | _manyChunks = new ManyChunkInfo(stringBuilder, chunkCount); |
| | | 617 | | } |
| | 0 | 618 | | } |
| | | 619 | | |
| | | 620 | | private static int ChunkCount(StringBuilder? stringBuilder) |
| | | 621 | | { |
| | 0 | 622 | | int ret = 0; |
| | 0 | 623 | | while (stringBuilder != null) |
| | | 624 | | { |
| | 0 | 625 | | ret++; |
| | 0 | 626 | | stringBuilder = stringBuilder.m_ChunkPrevious; |
| | | 627 | | } |
| | 0 | 628 | | 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 | | { |
| | 0 | 641 | | int pos = ++_chunkPos; |
| | 0 | 642 | | if (_chunks.Length <= pos) |
| | | 643 | | { |
| | 0 | 644 | | return false; |
| | | 645 | | } |
| | 0 | 646 | | current = _chunks[pos]; |
| | 0 | 647 | | return true; |
| | | 648 | | } |
| | | 649 | | |
| | 0 | 650 | | public ManyChunkInfo(StringBuilder? stringBuilder, int chunkCount) |
| | | 651 | | { |
| | 0 | 652 | | _chunks = new StringBuilder[chunkCount]; |
| | 0 | 653 | | while (0 <= --chunkCount) |
| | | 654 | | { |
| | 0 | 655 | | Debug.Assert(stringBuilder != null); |
| | 0 | 656 | | _chunks[chunkCount] = stringBuilder; |
| | 0 | 657 | | stringBuilder = stringBuilder.m_ChunkPrevious; |
| | | 658 | | } |
| | 0 | 659 | | _chunkPos = -1; |
| | 0 | 660 | | } |
| | | 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> |
| | 0 | 671 | | 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 | | { |
| | 0 | 680 | | ArgumentOutOfRangeException.ThrowIfNegative(repeatCount); |
| | | 681 | | |
| | 0 | 682 | | if (repeatCount == 0) |
| | | 683 | | { |
| | 0 | 684 | | return this; |
| | | 685 | | } |
| | | 686 | | |
| | 0 | 687 | | char[] chunkChars = m_ChunkChars; |
| | 0 | 688 | | 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 |
| | 0 | 693 | | if (((nuint)(uint)chunkLength + (nuint)(uint)repeatCount) <= (nuint)(uint)chunkChars.Length) |
| | | 694 | | { |
| | 0 | 695 | | chunkChars.AsSpan(chunkLength, repeatCount).Fill(value); |
| | 0 | 696 | | m_ChunkLength += repeatCount; |
| | | 697 | | } |
| | | 698 | | else |
| | | 699 | | { |
| | 0 | 700 | | AppendWithExpansion(value, repeatCount); |
| | | 701 | | } |
| | | 702 | | |
| | 0 | 703 | | AssertInvariants(); |
| | 0 | 704 | | return this; |
| | | 705 | | } |
| | | 706 | | |
| | | 707 | | private void AppendWithExpansion(char value, int repeatCount) |
| | | 708 | | { |
| | 0 | 709 | | Debug.Assert(repeatCount > 0, "Invalid length; should have been validated by caller."); |
| | | 710 | | |
| | | 711 | | // Check if the repeatCount will put us over m_MaxCapacity |
| | 0 | 712 | | if ((uint)(repeatCount + Length) > (uint)m_MaxCapacity) |
| | | 713 | | { |
| | 0 | 714 | | throw new ArgumentOutOfRangeException(nameof(repeatCount), SR.ArgumentOutOfRange_LengthGreaterThanCapaci |
| | | 715 | | } |
| | | 716 | | |
| | 0 | 717 | | char[] chunkChars = m_ChunkChars; |
| | 0 | 718 | | int chunkLength = m_ChunkLength; |
| | | 719 | | |
| | | 720 | | // Fill the rest of the current chunk |
| | 0 | 721 | | int firstLength = chunkChars.Length - chunkLength; |
| | 0 | 722 | | if (firstLength > 0) |
| | | 723 | | { |
| | 0 | 724 | | chunkChars.AsSpan(chunkLength, firstLength).Fill(value); |
| | 0 | 725 | | m_ChunkLength = chunkChars.Length; |
| | | 726 | | } |
| | | 727 | | |
| | | 728 | | // Expand the builder to add another chunk |
| | 0 | 729 | | int restLength = repeatCount - firstLength; |
| | 0 | 730 | | ExpandByABlock(restLength); |
| | 0 | 731 | | Debug.Assert(m_ChunkLength == 0, "A new block was not created."); |
| | | 732 | | |
| | | 733 | | // Fill the new chunk with the remaining part of repeatCount |
| | 0 | 734 | | m_ChunkChars.AsSpan(0, restLength).Fill(value); |
| | 0 | 735 | | m_ChunkLength = restLength; |
| | 0 | 736 | | } |
| | | 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 | | { |
| | 0 | 746 | | ArgumentOutOfRangeException.ThrowIfNegative(startIndex); |
| | 0 | 747 | | ArgumentOutOfRangeException.ThrowIfNegative(charCount); |
| | | 748 | | |
| | 0 | 749 | | if (value == null) |
| | | 750 | | { |
| | 0 | 751 | | if (startIndex == 0 && charCount == 0) |
| | | 752 | | { |
| | 0 | 753 | | return this; |
| | | 754 | | } |
| | | 755 | | |
| | 0 | 756 | | ArgumentNullException.Throw(nameof(value)); |
| | | 757 | | } |
| | 0 | 758 | | if (charCount > value.Length - startIndex) |
| | | 759 | | { |
| | 0 | 760 | | throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); |
| | | 761 | | } |
| | | 762 | | |
| | 0 | 763 | | if (charCount != 0) |
| | | 764 | | { |
| | 0 | 765 | | Append(ref value[startIndex], charCount); |
| | | 766 | | } |
| | | 767 | | |
| | 0 | 768 | | 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 | | { |
| | 40073 | 777 | | if (value is not null) |
| | | 778 | | { |
| | 40073 | 779 | | Append(ref value.GetRawStringData(), value.Length); |
| | | 780 | | } |
| | | 781 | | |
| | 40073 | 782 | | 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 | | { |
| | 116 | 793 | | ArgumentOutOfRangeException.ThrowIfNegative(startIndex); |
| | 116 | 794 | | ArgumentOutOfRangeException.ThrowIfNegative(count); |
| | | 795 | | |
| | 116 | 796 | | if (value == null) |
| | | 797 | | { |
| | 0 | 798 | | if (startIndex == 0 && count == 0) |
| | | 799 | | { |
| | 0 | 800 | | return this; |
| | | 801 | | } |
| | 0 | 802 | | ArgumentNullException.Throw(nameof(value)); |
| | | 803 | | } |
| | | 804 | | |
| | 116 | 805 | | if (count != 0) |
| | | 806 | | { |
| | 99 | 807 | | if (startIndex > value.Length - count) |
| | | 808 | | { |
| | 0 | 809 | | throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqu |
| | | 810 | | } |
| | | 811 | | |
| | 99 | 812 | | Append(ref Unsafe.Add(ref value.GetRawStringData(), startIndex), count); |
| | | 813 | | } |
| | | 814 | | |
| | 116 | 815 | | return this; |
| | | 816 | | } |
| | | 817 | | |
| | | 818 | | public StringBuilder Append(StringBuilder? value) |
| | | 819 | | { |
| | 0 | 820 | | if (value != null && value.Length != 0) |
| | | 821 | | { |
| | 0 | 822 | | return AppendCore(value, 0, value.Length); |
| | | 823 | | } |
| | 0 | 824 | | return this; |
| | | 825 | | } |
| | | 826 | | |
| | | 827 | | public StringBuilder Append(StringBuilder? value, int startIndex, int count) |
| | | 828 | | { |
| | 0 | 829 | | ArgumentOutOfRangeException.ThrowIfNegative(startIndex); |
| | 0 | 830 | | ArgumentOutOfRangeException.ThrowIfNegative(count); |
| | | 831 | | |
| | 0 | 832 | | if (value == null) |
| | | 833 | | { |
| | 0 | 834 | | if (startIndex == 0 && count == 0) |
| | | 835 | | { |
| | 0 | 836 | | return this; |
| | | 837 | | } |
| | 0 | 838 | | ArgumentNullException.Throw(nameof(value)); |
| | | 839 | | } |
| | | 840 | | |
| | 0 | 841 | | if (count == 0) |
| | | 842 | | { |
| | 0 | 843 | | return this; |
| | | 844 | | } |
| | | 845 | | |
| | 0 | 846 | | if (count > value.Length - startIndex) |
| | | 847 | | { |
| | 0 | 848 | | throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); |
| | | 849 | | } |
| | | 850 | | |
| | 0 | 851 | | return AppendCore(value, startIndex, count); |
| | | 852 | | } |
| | | 853 | | |
| | | 854 | | private StringBuilder AppendCore(StringBuilder value, int startIndex, int count) |
| | | 855 | | { |
| | 0 | 856 | | if (value == this) |
| | | 857 | | { |
| | 0 | 858 | | return Append(value.ToString(startIndex, count)); |
| | | 859 | | } |
| | | 860 | | |
| | 0 | 861 | | int newLength = Length + count; |
| | | 862 | | |
| | 0 | 863 | | if ((uint)newLength > (uint)m_MaxCapacity) |
| | | 864 | | { |
| | 0 | 865 | | throw new ArgumentOutOfRangeException(nameof(Capacity), SR.ArgumentOutOfRange_Capacity); |
| | | 866 | | } |
| | | 867 | | |
| | 0 | 868 | | while (count > 0) |
| | | 869 | | { |
| | 0 | 870 | | int length = Math.Min(m_ChunkChars.Length - m_ChunkLength, count); |
| | 0 | 871 | | if (length == 0) |
| | | 872 | | { |
| | 0 | 873 | | ExpandByABlock(count); |
| | 0 | 874 | | Debug.Assert(m_ChunkLength == 0 && m_ChunkChars.Length >= count); |
| | 0 | 875 | | length = count; |
| | | 876 | | } |
| | 0 | 877 | | value.CopyTo(startIndex, new Span<char>(m_ChunkChars, m_ChunkLength, length), length); |
| | | 878 | | |
| | 0 | 879 | | m_ChunkLength += length; |
| | 0 | 880 | | startIndex += length; |
| | 0 | 881 | | count -= length; |
| | | 882 | | } |
| | | 883 | | |
| | 0 | 884 | | return this; |
| | | 885 | | } |
| | | 886 | | |
| | 0 | 887 | | public StringBuilder AppendLine() => Append(Environment.NewLine); |
| | | 888 | | |
| | | 889 | | public StringBuilder AppendLine(string? value) |
| | | 890 | | { |
| | 0 | 891 | | Append(value); |
| | 0 | 892 | | return Append(Environment.NewLine); |
| | | 893 | | } |
| | | 894 | | |
| | | 895 | | public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) |
| | | 896 | | { |
| | 0 | 897 | | ArgumentNullException.ThrowIfNull(destination); |
| | | 898 | | |
| | 0 | 899 | | ArgumentOutOfRangeException.ThrowIfNegative(destinationIndex); |
| | | 900 | | |
| | 0 | 901 | | if (destinationIndex > destination.Length - count) |
| | | 902 | | { |
| | 0 | 903 | | throw new ArgumentException(SR.ArgumentOutOfRange_OffsetOut); |
| | | 904 | | } |
| | | 905 | | |
| | 0 | 906 | | CopyTo(sourceIndex, new Span<char>(destination).Slice(destinationIndex), count); |
| | 0 | 907 | | } |
| | | 908 | | |
| | | 909 | | public void CopyTo(int sourceIndex, Span<char> destination, int count) |
| | | 910 | | { |
| | 0 | 911 | | ArgumentOutOfRangeException.ThrowIfNegative(count); |
| | | 912 | | |
| | 0 | 913 | | if ((uint)sourceIndex > (uint)Length) |
| | | 914 | | { |
| | 0 | 915 | | throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual) |
| | | 916 | | } |
| | | 917 | | |
| | 0 | 918 | | if (sourceIndex > Length - count) |
| | | 919 | | { |
| | 0 | 920 | | throw new ArgumentException(SR.Arg_LongerThanSrcString); |
| | | 921 | | } |
| | | 922 | | |
| | 0 | 923 | | AssertInvariants(); |
| | | 924 | | |
| | 0 | 925 | | StringBuilder? chunk = this; |
| | 0 | 926 | | int sourceEndIndex = sourceIndex + count; |
| | 0 | 927 | | int curDestIndex = count; |
| | 0 | 928 | | while (count > 0) |
| | | 929 | | { |
| | 0 | 930 | | Debug.Assert(chunk != null); |
| | 0 | 931 | | int chunkEndIndex = sourceEndIndex - chunk.m_ChunkOffset; |
| | 0 | 932 | | if (chunkEndIndex >= 0) |
| | | 933 | | { |
| | 0 | 934 | | chunkEndIndex = Math.Min(chunkEndIndex, chunk.m_ChunkLength); |
| | | 935 | | |
| | 0 | 936 | | int chunkCount = count; |
| | 0 | 937 | | int chunkStartIndex = chunkEndIndex - count; |
| | 0 | 938 | | if (chunkStartIndex < 0) |
| | | 939 | | { |
| | 0 | 940 | | chunkCount += chunkStartIndex; |
| | 0 | 941 | | chunkStartIndex = 0; |
| | | 942 | | } |
| | 0 | 943 | | curDestIndex -= chunkCount; |
| | 0 | 944 | | count -= chunkCount; |
| | | 945 | | |
| | 0 | 946 | | new ReadOnlySpan<char>(chunk.m_ChunkChars, chunkStartIndex, chunkCount).CopyTo(destination.Slice(cur |
| | | 947 | | } |
| | 0 | 948 | | chunk = chunk.m_ChunkPrevious; |
| | | 949 | | } |
| | 0 | 950 | | } |
| | | 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> |
| | 0 | 958 | | 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 | | { |
| | 0 | 962 | | ArgumentOutOfRangeException.ThrowIfNegative(count); |
| | | 963 | | |
| | 0 | 964 | | int currentLength = Length; |
| | 0 | 965 | | if ((uint)index > (uint)currentLength) |
| | | 966 | | { |
| | 0 | 967 | | throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); |
| | | 968 | | } |
| | | 969 | | |
| | 0 | 970 | | if (value.IsEmpty || count == 0) |
| | | 971 | | { |
| | 0 | 972 | | 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. |
| | 0 | 977 | | long insertingChars = (long)value.Length * count; |
| | 0 | 978 | | if (insertingChars > MaxCapacity - this.Length) |
| | | 979 | | { |
| | 0 | 980 | | throw new OutOfMemoryException(); |
| | | 981 | | } |
| | 0 | 982 | | Debug.Assert(insertingChars + this.Length < int.MaxValue); |
| | | 983 | | |
| | 0 | 984 | | MakeRoom(index, (int)insertingChars, out StringBuilder chunk, out int indexInChunk, false); |
| | | 985 | | |
| | 0 | 986 | | while (count > 0) |
| | | 987 | | { |
| | 0 | 988 | | ReplaceInPlaceAtChunk(ref chunk!, ref indexInChunk, ref MemoryMarshal.GetReference(value), value.Length) |
| | 0 | 989 | | --count; |
| | | 990 | | } |
| | | 991 | | |
| | 0 | 992 | | 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 | | { |
| | 0 | 1003 | | ArgumentOutOfRangeException.ThrowIfNegative(length); |
| | 0 | 1004 | | ArgumentOutOfRangeException.ThrowIfNegative(startIndex); |
| | 0 | 1005 | | if (length > Length - startIndex) |
| | | 1006 | | { |
| | 0 | 1007 | | throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); |
| | | 1008 | | } |
| | | 1009 | | |
| | 0 | 1010 | | if (Length == length && startIndex == 0) |
| | | 1011 | | { |
| | 0 | 1012 | | Length = 0; |
| | 0 | 1013 | | return this; |
| | | 1014 | | } |
| | | 1015 | | |
| | 0 | 1016 | | if (length > 0) |
| | | 1017 | | { |
| | 0 | 1018 | | Remove(startIndex, length, out _, out _); |
| | | 1019 | | } |
| | | 1020 | | |
| | 0 | 1021 | | return this; |
| | | 1022 | | } |
| | | 1023 | | |
| | | 1024 | | #pragma warning disable CA1830 // Prefer strongly-typed Append and Insert method overloads on StringBuilder. No need to |
| | 0 | 1025 | | public StringBuilder Append(bool value) => Append(value.ToString()); |
| | | 1026 | | #pragma warning restore CA1830 |
| | | 1027 | | |
| | | 1028 | | public StringBuilder Append(char value) |
| | | 1029 | | { |
| | 58 | 1030 | | int nextCharIndex = m_ChunkLength; |
| | 58 | 1031 | | char[] chars = m_ChunkChars; |
| | | 1032 | | |
| | 58 | 1033 | | if ((uint)chars.Length > (uint)nextCharIndex) |
| | | 1034 | | { |
| | 55 | 1035 | | chars[nextCharIndex] = value; |
| | 55 | 1036 | | m_ChunkLength++; |
| | | 1037 | | } |
| | | 1038 | | else |
| | | 1039 | | { |
| | 3 | 1040 | | AppendWithExpansion(value); |
| | | 1041 | | } |
| | | 1042 | | |
| | 58 | 1043 | | return this; |
| | | 1044 | | } |
| | | 1045 | | |
| | | 1046 | | [MethodImpl(MethodImplOptions.NoInlining)] |
| | | 1047 | | private void AppendWithExpansion(char value) |
| | | 1048 | | { |
| | 3 | 1049 | | ExpandByABlock(1); |
| | 3 | 1050 | | Debug.Assert(m_ChunkLength == 0, "A new block was not created."); |
| | 3 | 1051 | | m_ChunkChars[0] = value; |
| | 3 | 1052 | | m_ChunkLength++; |
| | 3 | 1053 | | } |
| | | 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 |
| | 0 | 1063 | | ReadOnlySpan<char> valueChars = value.AsSpan(stackalloc char[Rune.MaxUtf16CharsPerRune]); |
| | | 1064 | | |
| | | 1065 | | // Append span |
| | 0 | 1066 | | return Append(valueChars); |
| | | 1067 | | } |
| | | 1068 | | |
| | | 1069 | | [CLSCompliant(false)] |
| | 0 | 1070 | | public StringBuilder Append(sbyte value) => AppendSpanFormattable(value); |
| | | 1071 | | |
| | 0 | 1072 | | public StringBuilder Append(byte value) => AppendSpanFormattable(value); |
| | | 1073 | | |
| | 0 | 1074 | | public StringBuilder Append(short value) => AppendSpanFormattable(value); |
| | | 1075 | | |
| | 58 | 1076 | | public StringBuilder Append(int value) => AppendSpanFormattable(value); |
| | | 1077 | | |
| | 0 | 1078 | | public StringBuilder Append(long value) => AppendSpanFormattable(value); |
| | | 1079 | | |
| | 0 | 1080 | | public StringBuilder Append(float value) => AppendSpanFormattable(value); |
| | | 1081 | | |
| | 0 | 1082 | | public StringBuilder Append(double value) => AppendSpanFormattable(value); |
| | | 1083 | | |
| | 0 | 1084 | | public StringBuilder Append(decimal value) => AppendSpanFormattable(value); |
| | | 1085 | | |
| | | 1086 | | [CLSCompliant(false)] |
| | 0 | 1087 | | public StringBuilder Append(ushort value) => AppendSpanFormattable(value); |
| | | 1088 | | |
| | | 1089 | | [CLSCompliant(false)] |
| | 0 | 1090 | | public StringBuilder Append(uint value) => AppendSpanFormattable(value); |
| | | 1091 | | |
| | | 1092 | | [CLSCompliant(false)] |
| | 0 | 1093 | | public StringBuilder Append(ulong value) => AppendSpanFormattable(value); |
| | | 1094 | | |
| | | 1095 | | private StringBuilder AppendSpanFormattable<T>(T value) where T : ISpanFormattable |
| | | 1096 | | { |
| | 58 | 1097 | | Debug.Assert(typeof(T).Assembly.Equals(typeof(object).Assembly), "Implementation trusts the results of TryFo |
| | | 1098 | | |
| | 58 | 1099 | | if (value.TryFormat(RemainingCurrentChunk, out int charsWritten, format: default, provider: null)) |
| | | 1100 | | { |
| | 57 | 1101 | | m_ChunkLength += charsWritten; |
| | 57 | 1102 | | return this; |
| | | 1103 | | } |
| | | 1104 | | |
| | 1 | 1105 | | 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 | | |
| | 0 | 1121 | | public StringBuilder Append(object? value) => (value == null) ? this : Append(value.ToString()); |
| | | 1122 | | |
| | | 1123 | | public StringBuilder Append(char[]? value) |
| | | 1124 | | { |
| | 0 | 1125 | | if (value is not null) |
| | | 1126 | | { |
| | 0 | 1127 | | Append(ref MemoryMarshal.GetArrayDataReference(value), value.Length); |
| | | 1128 | | } |
| | | 1129 | | |
| | 0 | 1130 | | return this; |
| | | 1131 | | } |
| | | 1132 | | |
| | | 1133 | | public StringBuilder Append(ReadOnlySpan<char> value) |
| | | 1134 | | { |
| | 0 | 1135 | | Append(ref MemoryMarshal.GetReference(value), value.Length); |
| | 0 | 1136 | | return this; |
| | | 1137 | | } |
| | | 1138 | | |
| | 0 | 1139 | | 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> |
| | 20015 | 1144 | | 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> |
| | 0 | 1150 | | 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> |
| | 0 | 1155 | | 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> |
| | 0 | 1161 | | public StringBuilder AppendLine(IFormatProvider? provider, [InterpolatedStringHandlerArgument("", nameof(provide |
| | | 1162 | | |
| | | 1163 | | #region AppendJoin |
| | | 1164 | | |
| | | 1165 | | public StringBuilder AppendJoin(string? separator, params object?[] values) |
| | | 1166 | | { |
| | 0 | 1167 | | if (values is null) |
| | | 1168 | | { |
| | 0 | 1169 | | ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values); |
| | | 1170 | | } |
| | | 1171 | | |
| | 0 | 1172 | | separator ??= string.Empty; |
| | 0 | 1173 | | 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 | | { |
| | 0 | 1185 | | separator ??= string.Empty; |
| | 0 | 1186 | | return AppendJoinCore(ref separator.GetRawStringData(), separator.Length, values); |
| | | 1187 | | } |
| | | 1188 | | |
| | | 1189 | | public StringBuilder AppendJoin<T>(string? separator, IEnumerable<T> values) |
| | | 1190 | | { |
| | 0 | 1191 | | if (values is null) |
| | | 1192 | | { |
| | 0 | 1193 | | ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values); |
| | | 1194 | | } |
| | | 1195 | | |
| | 0 | 1196 | | separator ??= string.Empty; |
| | 0 | 1197 | | return AppendJoinCore(ref separator.GetRawStringData(), separator.Length, values); |
| | | 1198 | | } |
| | | 1199 | | |
| | | 1200 | | public StringBuilder AppendJoin(string? separator, params string?[] values) |
| | | 1201 | | { |
| | 0 | 1202 | | if (values is null) |
| | | 1203 | | { |
| | 0 | 1204 | | ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values); |
| | | 1205 | | } |
| | | 1206 | | |
| | 0 | 1207 | | separator ??= string.Empty; |
| | 0 | 1208 | | 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 | | { |
| | 0 | 1220 | | separator ??= string.Empty; |
| | 0 | 1221 | | return AppendJoinCore(ref separator.GetRawStringData(), separator.Length, values); |
| | | 1222 | | } |
| | | 1223 | | |
| | | 1224 | | public StringBuilder AppendJoin(char separator, params object?[] values) |
| | | 1225 | | { |
| | 0 | 1226 | | if (values is null) |
| | | 1227 | | { |
| | 0 | 1228 | | ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values); |
| | | 1229 | | } |
| | | 1230 | | |
| | 0 | 1231 | | 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) => |
| | 0 | 1242 | | AppendJoinCore(ref separator, 1, values); |
| | | 1243 | | |
| | | 1244 | | public StringBuilder AppendJoin<T>(char separator, IEnumerable<T> values) |
| | | 1245 | | { |
| | 0 | 1246 | | if (values is null) |
| | | 1247 | | { |
| | 0 | 1248 | | ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values); |
| | | 1249 | | } |
| | | 1250 | | |
| | 0 | 1251 | | return AppendJoinCore(ref separator, 1, values); |
| | | 1252 | | } |
| | | 1253 | | |
| | | 1254 | | public StringBuilder AppendJoin(char separator, params string?[] values) |
| | | 1255 | | { |
| | 0 | 1256 | | if (values is null) |
| | | 1257 | | { |
| | 0 | 1258 | | ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values); |
| | | 1259 | | } |
| | | 1260 | | |
| | 0 | 1261 | | 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) => |
| | 0 | 1272 | | AppendJoinCore(ref separator, 1, values); |
| | | 1273 | | |
| | | 1274 | | private StringBuilder AppendJoinCore<T>(ref char separator, int separatorLength, IEnumerable<T> values) |
| | | 1275 | | { |
| | 0 | 1276 | | Debug.Assert(values != null); |
| | 0 | 1277 | | Debug.Assert(!Unsafe.IsNullRef(ref separator)); |
| | 0 | 1278 | | Debug.Assert(separatorLength >= 0); |
| | | 1279 | | |
| | 0 | 1280 | | using (IEnumerator<T> en = values.GetEnumerator()) |
| | | 1281 | | { |
| | 0 | 1282 | | if (!en.MoveNext()) |
| | | 1283 | | { |
| | 0 | 1284 | | return this; |
| | | 1285 | | } |
| | | 1286 | | |
| | 0 | 1287 | | T value = en.Current; |
| | 0 | 1288 | | if (value != null) |
| | | 1289 | | { |
| | 0 | 1290 | | Append(value.ToString()); |
| | | 1291 | | } |
| | | 1292 | | |
| | 0 | 1293 | | while (en.MoveNext()) |
| | | 1294 | | { |
| | 0 | 1295 | | Append(ref separator, separatorLength); |
| | 0 | 1296 | | value = en.Current; |
| | 0 | 1297 | | if (value != null) |
| | | 1298 | | { |
| | 0 | 1299 | | Append(value.ToString()); |
| | | 1300 | | } |
| | | 1301 | | } |
| | 0 | 1302 | | } |
| | 0 | 1303 | | return this; |
| | 0 | 1304 | | } |
| | | 1305 | | |
| | | 1306 | | private StringBuilder AppendJoinCore<T>(ref char separator, int separatorLength, ReadOnlySpan<T> values) |
| | | 1307 | | { |
| | 0 | 1308 | | if (values.IsEmpty) |
| | | 1309 | | { |
| | 0 | 1310 | | return this; |
| | | 1311 | | } |
| | | 1312 | | |
| | 0 | 1313 | | if (values[0] != null) |
| | | 1314 | | { |
| | 0 | 1315 | | Append(values[0]!.ToString()); |
| | | 1316 | | } |
| | | 1317 | | |
| | 0 | 1318 | | for (int i = 1; i < values.Length; i++) |
| | | 1319 | | { |
| | 0 | 1320 | | Append(ref separator, separatorLength); |
| | 0 | 1321 | | if (values[i] != null) |
| | | 1322 | | { |
| | 0 | 1323 | | Append(values[i]!.ToString()); |
| | | 1324 | | } |
| | | 1325 | | } |
| | 0 | 1326 | | return this; |
| | | 1327 | | } |
| | | 1328 | | |
| | | 1329 | | #endregion |
| | | 1330 | | |
| | | 1331 | | public StringBuilder Insert(int index, string? value) |
| | | 1332 | | { |
| | 0 | 1333 | | if ((uint)index > (uint)Length) |
| | | 1334 | | { |
| | 0 | 1335 | | throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); |
| | | 1336 | | } |
| | | 1337 | | |
| | 0 | 1338 | | if (value != null) |
| | | 1339 | | { |
| | 0 | 1340 | | Insert(index, ref value.GetRawStringData(), value.Length); |
| | | 1341 | | } |
| | | 1342 | | |
| | 0 | 1343 | | 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. |
| | 0 | 1348 | | public StringBuilder Insert(int index, bool value) => Insert(index, value.ToString().AsSpan(), 1); |
| | | 1349 | | #pragma warning restore CA1830 |
| | | 1350 | | |
| | | 1351 | | [CLSCompliant(false)] |
| | 0 | 1352 | | public StringBuilder Insert(int index, sbyte value) => InsertSpanFormattable(index, value); |
| | | 1353 | | |
| | 0 | 1354 | | public StringBuilder Insert(int index, byte value) => InsertSpanFormattable(index, value); |
| | | 1355 | | |
| | 0 | 1356 | | public StringBuilder Insert(int index, short value) => InsertSpanFormattable(index, value); |
| | | 1357 | | |
| | | 1358 | | public StringBuilder Insert(int index, char value) |
| | | 1359 | | { |
| | 0 | 1360 | | if ((uint)index > (uint)Length) |
| | | 1361 | | { |
| | 0 | 1362 | | throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); |
| | | 1363 | | } |
| | | 1364 | | |
| | 0 | 1365 | | Insert(index, ref value, 1); |
| | 0 | 1366 | | 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 |
| | 0 | 1378 | | ReadOnlySpan<char> valueChars = value.AsSpan(stackalloc char[Rune.MaxUtf16CharsPerRune]); |
| | | 1379 | | |
| | | 1380 | | // Insert span |
| | 0 | 1381 | | return Insert(index, valueChars); |
| | | 1382 | | } |
| | | 1383 | | |
| | | 1384 | | public StringBuilder Insert(int index, char[]? value) |
| | | 1385 | | { |
| | 0 | 1386 | | if ((uint)index > (uint)Length) |
| | | 1387 | | { |
| | 0 | 1388 | | throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); |
| | | 1389 | | } |
| | | 1390 | | |
| | 0 | 1391 | | if (value != null) |
| | | 1392 | | { |
| | 0 | 1393 | | Insert(index, ref MemoryMarshal.GetArrayDataReference(value), value.Length); |
| | | 1394 | | } |
| | 0 | 1395 | | return this; |
| | | 1396 | | } |
| | | 1397 | | |
| | | 1398 | | public StringBuilder Insert(int index, char[]? value, int startIndex, int charCount) |
| | | 1399 | | { |
| | 0 | 1400 | | int currentLength = Length; |
| | 0 | 1401 | | if ((uint)index > (uint)currentLength) |
| | | 1402 | | { |
| | 0 | 1403 | | throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); |
| | | 1404 | | } |
| | | 1405 | | |
| | 0 | 1406 | | if (value == null) |
| | | 1407 | | { |
| | 0 | 1408 | | if (startIndex == 0 && charCount == 0) |
| | | 1409 | | { |
| | 0 | 1410 | | return this; |
| | | 1411 | | } |
| | 0 | 1412 | | ArgumentNullException.Throw(nameof(value)); |
| | | 1413 | | } |
| | | 1414 | | |
| | 0 | 1415 | | ArgumentOutOfRangeException.ThrowIfNegative(startIndex); |
| | 0 | 1416 | | ArgumentOutOfRangeException.ThrowIfNegative(charCount); |
| | 0 | 1417 | | if (startIndex > value.Length - charCount) |
| | | 1418 | | { |
| | 0 | 1419 | | throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); |
| | | 1420 | | } |
| | | 1421 | | |
| | 0 | 1422 | | if (charCount > 0) |
| | | 1423 | | { |
| | 0 | 1424 | | Insert(index, ref value[startIndex], charCount); |
| | | 1425 | | } |
| | | 1426 | | |
| | 0 | 1427 | | return this; |
| | | 1428 | | } |
| | | 1429 | | |
| | 0 | 1430 | | public StringBuilder Insert(int index, int value) => InsertSpanFormattable(index, value); |
| | | 1431 | | |
| | 0 | 1432 | | public StringBuilder Insert(int index, long value) => InsertSpanFormattable(index, value); |
| | | 1433 | | |
| | 0 | 1434 | | public StringBuilder Insert(int index, float value) => InsertSpanFormattable(index, value); |
| | | 1435 | | |
| | 0 | 1436 | | public StringBuilder Insert(int index, double value) => InsertSpanFormattable(index, value); |
| | | 1437 | | |
| | 0 | 1438 | | public StringBuilder Insert(int index, decimal value) => InsertSpanFormattable(index, value); |
| | | 1439 | | |
| | | 1440 | | [CLSCompliant(false)] |
| | 0 | 1441 | | public StringBuilder Insert(int index, ushort value) => InsertSpanFormattable(index, value); |
| | | 1442 | | |
| | | 1443 | | [CLSCompliant(false)] |
| | 0 | 1444 | | public StringBuilder Insert(int index, uint value) => InsertSpanFormattable(index, value); |
| | | 1445 | | |
| | | 1446 | | [CLSCompliant(false)] |
| | 0 | 1447 | | public StringBuilder Insert(int index, ulong value) => InsertSpanFormattable(index, value); |
| | | 1448 | | |
| | 0 | 1449 | | 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 | | { |
| | 0 | 1453 | | if ((uint)index > (uint)Length) |
| | | 1454 | | { |
| | 0 | 1455 | | throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); |
| | | 1456 | | } |
| | | 1457 | | |
| | 0 | 1458 | | if (value.Length != 0) |
| | | 1459 | | { |
| | 0 | 1460 | | Insert(index, ref MemoryMarshal.GetReference(value), value.Length); |
| | | 1461 | | } |
| | | 1462 | | |
| | 0 | 1463 | | return this; |
| | | 1464 | | } |
| | | 1465 | | |
| | | 1466 | | private unsafe StringBuilder InsertSpanFormattable<T>(int index, T value) where T : ISpanFormattable |
| | | 1467 | | { |
| | 0 | 1468 | | Debug.Assert(typeof(T).Assembly.Equals(typeof(object).Assembly), "Implementation trusts the results of TryFo |
| | | 1469 | | |
| | 0 | 1470 | | Span<char> buffer = stackalloc char[string.StackallocCharBufferSizeLimit]; |
| | 0 | 1471 | | 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. |
| | 0 | 1475 | | return Insert(index, buffer.Slice(0, charsWritten), 1); |
| | | 1476 | | } |
| | | 1477 | | |
| | 0 | 1478 | | return Insert(index, value.ToString(), 1); |
| | | 1479 | | } |
| | | 1480 | | |
| | | 1481 | | public StringBuilder AppendFormat([StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format, object? a |
| | | 1482 | | { |
| | 0 | 1483 | | return AppendFormat(null, format, new ReadOnlySpan<object?>(in arg0)); |
| | | 1484 | | } |
| | | 1485 | | |
| | | 1486 | | public StringBuilder AppendFormat([StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format, object? a |
| | | 1487 | | { |
| | 0 | 1488 | | return AppendFormat(null, format, [arg0, arg1]); |
| | | 1489 | | } |
| | | 1490 | | |
| | | 1491 | | public StringBuilder AppendFormat([StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format, object? a |
| | | 1492 | | { |
| | 0 | 1493 | | return AppendFormat(null, format, [arg0, arg1, arg2]); |
| | | 1494 | | } |
| | | 1495 | | |
| | | 1496 | | public StringBuilder AppendFormat([StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format, params ob |
| | | 1497 | | { |
| | 0 | 1498 | | 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). |
| | 0 | 1502 | | ArgumentNullException.Throw(format is null ? nameof(format) : nameof(args)); |
| | | 1503 | | } |
| | | 1504 | | |
| | 0 | 1505 | | 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 | | { |
| | 0 | 1524 | | return AppendFormat(null, format, args); |
| | | 1525 | | } |
| | | 1526 | | |
| | | 1527 | | public StringBuilder AppendFormat(IFormatProvider? provider, [StringSyntax(StringSyntaxAttribute.CompositeFormat |
| | | 1528 | | { |
| | 0 | 1529 | | return AppendFormat(provider, format, new ReadOnlySpan<object?>(in arg0)); |
| | | 1530 | | } |
| | | 1531 | | |
| | | 1532 | | public StringBuilder AppendFormat(IFormatProvider? provider, [StringSyntax(StringSyntaxAttribute.CompositeFormat |
| | | 1533 | | { |
| | 0 | 1534 | | return AppendFormat(provider, format, [arg0, arg1]); |
| | | 1535 | | } |
| | | 1536 | | |
| | | 1537 | | public StringBuilder AppendFormat(IFormatProvider? provider, [StringSyntax(StringSyntaxAttribute.CompositeFormat |
| | | 1538 | | { |
| | 0 | 1539 | | return AppendFormat(provider, format, [arg0, arg1, arg2]); |
| | | 1540 | | } |
| | | 1541 | | |
| | | 1542 | | public StringBuilder AppendFormat(IFormatProvider? provider, [StringSyntax(StringSyntaxAttribute.CompositeFormat |
| | | 1543 | | { |
| | 0 | 1544 | | 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). |
| | 0 | 1548 | | ArgumentNullException.Throw(format is null ? nameof(format) : nameof(args)); |
| | | 1549 | | } |
| | | 1550 | | |
| | 0 | 1551 | | 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 | | { |
| | 0 | 1571 | | 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. |
| | 0 | 1579 | | ICustomFormatter? cf = (ICustomFormatter?)provider?.GetFormat(typeof(ICustomFormatter)); |
| | | 1580 | | |
| | | 1581 | | // Repeatedly find the next hole and process it. |
| | 0 | 1582 | | int pos = 0; |
| | | 1583 | | char ch; |
| | 0 | 1584 | | 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 |
| | 0 | 1591 | | if ((uint)pos >= (uint)format.Length) |
| | | 1592 | | { |
| | 0 | 1593 | | return this; |
| | | 1594 | | } |
| | | 1595 | | |
| | 0 | 1596 | | ReadOnlySpan<char> remainder = format.AsSpan(pos); |
| | 0 | 1597 | | int countUntilNextBrace = remainder.IndexOfAny('{', '}'); |
| | 0 | 1598 | | if (countUntilNextBrace < 0) |
| | | 1599 | | { |
| | 0 | 1600 | | Append(remainder); |
| | 0 | 1601 | | return this; |
| | | 1602 | | } |
| | | 1603 | | |
| | | 1604 | | // Append the text until the brace. |
| | 0 | 1605 | | Append(remainder.Slice(0, countUntilNextBrace)); |
| | 0 | 1606 | | 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. |
| | 0 | 1610 | | char brace = format[pos]; |
| | 0 | 1611 | | ch = MoveNext(format, ref pos); |
| | 0 | 1612 | | if (brace == ch) |
| | | 1613 | | { |
| | 0 | 1614 | | Append(ch); |
| | 0 | 1615 | | pos++; |
| | 0 | 1616 | | continue; |
| | | 1617 | | } |
| | | 1618 | | |
| | | 1619 | | // This wasn't an escape, so it must be an opening brace. |
| | 0 | 1620 | | if (brace != '{') |
| | | 1621 | | { |
| | 0 | 1622 | | 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. |
| | 0 | 1632 | | int width = 0; |
| | 0 | 1633 | | bool leftJustify = false; |
| | 0 | 1634 | | 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. |
| | 0 | 1640 | | Debug.Assert(format[pos - 1] == '{'); |
| | 0 | 1641 | | Debug.Assert(ch != '{'); |
| | 0 | 1642 | | int index = ch - '0'; |
| | 0 | 1643 | | if ((uint)index >= 10u) |
| | | 1644 | | { |
| | 0 | 1645 | | 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. |
| | 0 | 1650 | | ch = MoveNext(format, ref pos); |
| | 0 | 1651 | | if (ch != '}') |
| | | 1652 | | { |
| | | 1653 | | // Continue consuming optional additional digits. |
| | 0 | 1654 | | while (char.IsAsciiDigit(ch) && index < IndexLimit) |
| | | 1655 | | { |
| | 0 | 1656 | | index = index * 10 + ch - '0'; |
| | 0 | 1657 | | ch = MoveNext(format, ref pos); |
| | | 1658 | | } |
| | | 1659 | | |
| | | 1660 | | // Consume optional whitespace. |
| | 0 | 1661 | | while (ch == ' ') |
| | | 1662 | | { |
| | 0 | 1663 | | 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 |
| | 0 | 1672 | | if (ch == ',') |
| | | 1673 | | { |
| | | 1674 | | // Consume optional whitespace. |
| | | 1675 | | do |
| | | 1676 | | { |
| | 0 | 1677 | | ch = MoveNext(format, ref pos); |
| | | 1678 | | } |
| | 0 | 1679 | | while (ch == ' '); |
| | | 1680 | | |
| | | 1681 | | // Consume an optional minus sign indicating left alignment. |
| | 0 | 1682 | | if (ch == '-') |
| | | 1683 | | { |
| | 0 | 1684 | | leftJustify = true; |
| | 0 | 1685 | | ch = MoveNext(format, ref pos); |
| | | 1686 | | } |
| | | 1687 | | |
| | | 1688 | | // Parse alignment digits. The read character must be a digit. |
| | 0 | 1689 | | width = ch - '0'; |
| | 0 | 1690 | | if ((uint)width >= 10u) |
| | | 1691 | | { |
| | 0 | 1692 | | ThrowHelper.ThrowFormatInvalidString(pos, ExceptionResource.Format_ExpectedAsciiDigit); |
| | | 1693 | | } |
| | 0 | 1694 | | ch = MoveNext(format, ref pos); |
| | 0 | 1695 | | while (char.IsAsciiDigit(ch) && width < WidthLimit) |
| | | 1696 | | { |
| | 0 | 1697 | | width = width * 10 + ch - '0'; |
| | 0 | 1698 | | ch = MoveNext(format, ref pos); |
| | | 1699 | | } |
| | | 1700 | | |
| | | 1701 | | // Consume optional whitespace |
| | 0 | 1702 | | while (ch == ' ') |
| | | 1703 | | { |
| | 0 | 1704 | | 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. |
| | 0 | 1710 | | if (ch != '}') |
| | | 1711 | | { |
| | 0 | 1712 | | if (ch != ':') |
| | | 1713 | | { |
| | | 1714 | | // Unexpected character |
| | 0 | 1715 | | 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. |
| | 0 | 1720 | | int startingPos = pos; |
| | | 1721 | | while (true) |
| | | 1722 | | { |
| | 0 | 1723 | | ch = MoveNext(format, ref pos); |
| | | 1724 | | |
| | 0 | 1725 | | if (ch == '}') |
| | | 1726 | | { |
| | | 1727 | | // Argument hole closed |
| | | 1728 | | break; |
| | | 1729 | | } |
| | | 1730 | | |
| | 0 | 1731 | | if (ch == '{') |
| | | 1732 | | { |
| | | 1733 | | // Braces inside the argument hole are not supported |
| | 0 | 1734 | | ThrowHelper.ThrowFormatInvalidString(pos, ExceptionResource.Format_UnclosedFormatItem); |
| | | 1735 | | } |
| | | 1736 | | } |
| | | 1737 | | |
| | 0 | 1738 | | startingPos++; |
| | 0 | 1739 | | itemFormatSpan = format.AsSpan(startingPos, pos - startingPos); |
| | | 1740 | | } |
| | | 1741 | | } |
| | | 1742 | | |
| | | 1743 | | // Construct the output for this arg hole. |
| | 0 | 1744 | | Debug.Assert(format[pos] == '}'); |
| | 0 | 1745 | | pos++; |
| | 0 | 1746 | | string? s = null; |
| | 0 | 1747 | | string? itemFormat = null; |
| | | 1748 | | |
| | 0 | 1749 | | if ((uint)index >= (uint)args.Length) |
| | | 1750 | | { |
| | 0 | 1751 | | ThrowHelper.ThrowFormatIndexOutOfRange(); |
| | | 1752 | | } |
| | 0 | 1753 | | object? arg = args[index]; |
| | | 1754 | | |
| | 0 | 1755 | | if (cf != null) |
| | | 1756 | | { |
| | 0 | 1757 | | if (!itemFormatSpan.IsEmpty) |
| | | 1758 | | { |
| | 0 | 1759 | | itemFormat = new string(itemFormatSpan); |
| | | 1760 | | } |
| | | 1761 | | |
| | 0 | 1762 | | s = cf.Format(itemFormat, arg, provider); |
| | | 1763 | | } |
| | | 1764 | | |
| | 0 | 1765 | | 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. |
| | 0 | 1769 | | if ((leftJustify || width == 0) && |
| | 0 | 1770 | | arg is ISpanFormattable spanFormattableArg && |
| | 0 | 1771 | | spanFormattableArg.TryFormat(RemainingCurrentChunk, out int charsWritten, itemFormatSpan, provid |
| | | 1772 | | { |
| | 0 | 1773 | | 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. |
| | 0 | 1778 | | ThrowHelper.ThrowFormatInvalidString(); |
| | | 1779 | | } |
| | | 1780 | | |
| | 0 | 1781 | | m_ChunkLength += charsWritten; |
| | | 1782 | | |
| | | 1783 | | // Pad the end, if needed. |
| | 0 | 1784 | | if (leftJustify && width > charsWritten) |
| | | 1785 | | { |
| | 0 | 1786 | | Append(' ', width - charsWritten); |
| | | 1787 | | } |
| | | 1788 | | |
| | | 1789 | | // Continue to parse other characters. |
| | 0 | 1790 | | continue; |
| | | 1791 | | } |
| | | 1792 | | |
| | | 1793 | | // Otherwise, fallback to trying IFormattable or calling ToString. |
| | 0 | 1794 | | if (arg is IFormattable formattableArg) |
| | | 1795 | | { |
| | 0 | 1796 | | if (itemFormatSpan.Length != 0) |
| | | 1797 | | { |
| | 0 | 1798 | | itemFormat ??= new string(itemFormatSpan); |
| | | 1799 | | } |
| | 0 | 1800 | | s = formattableArg.ToString(itemFormat, provider); |
| | | 1801 | | } |
| | | 1802 | | else |
| | | 1803 | | { |
| | 0 | 1804 | | s = arg?.ToString(); |
| | | 1805 | | } |
| | | 1806 | | |
| | 0 | 1807 | | s ??= string.Empty; |
| | | 1808 | | } |
| | | 1809 | | |
| | | 1810 | | // Append it to the final output of the Format String. |
| | 0 | 1811 | | if (width <= s.Length) |
| | | 1812 | | { |
| | 0 | 1813 | | Append(s); |
| | | 1814 | | } |
| | 0 | 1815 | | else if (leftJustify) |
| | | 1816 | | { |
| | 0 | 1817 | | Append(s); |
| | 0 | 1818 | | Append(' ', width - s.Length); |
| | | 1819 | | } |
| | | 1820 | | else |
| | | 1821 | | { |
| | 0 | 1822 | | Append(' ', width - s.Length); |
| | 0 | 1823 | | 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 | | { |
| | 0 | 1832 | | pos++; |
| | 0 | 1833 | | if ((uint)pos >= (uint)format.Length) |
| | | 1834 | | { |
| | 0 | 1835 | | ThrowHelper.ThrowFormatInvalidString(pos, ExceptionResource.Format_UnclosedFormatItem); |
| | | 1836 | | } |
| | 0 | 1837 | | 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 | | { |
| | 0 | 1854 | | ArgumentNullException.ThrowIfNull(format); |
| | 0 | 1855 | | format.ValidateNumberOfArgs(1); |
| | 0 | 1856 | | 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 | | { |
| | 0 | 1874 | | ArgumentNullException.ThrowIfNull(format); |
| | 0 | 1875 | | format.ValidateNumberOfArgs(2); |
| | 0 | 1876 | | 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 | | { |
| | 0 | 1896 | | ArgumentNullException.ThrowIfNull(format); |
| | 0 | 1897 | | format.ValidateNumberOfArgs(3); |
| | 0 | 1898 | | 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 | | { |
| | 0 | 1914 | | ArgumentNullException.ThrowIfNull(format); |
| | 0 | 1915 | | ArgumentNullException.ThrowIfNull(args); |
| | 0 | 1916 | | 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 | | { |
| | 0 | 1931 | | ArgumentNullException.ThrowIfNull(format); |
| | 0 | 1932 | | format.ValidateNumberOfArgs(args.Length); |
| | 0 | 1933 | | return args.Length switch |
| | 0 | 1934 | | { |
| | 0 | 1935 | | 0 => AppendFormat(provider, format, 0, 0, 0, args), |
| | 0 | 1936 | | 1 => AppendFormat(provider, format, args[0], 0, 0, args), |
| | 0 | 1937 | | 2 => AppendFormat(provider, format, args[0], args[1], 0, args), |
| | 0 | 1938 | | _ => AppendFormat(provider, format, args[0], args[1], args[2], args), |
| | 0 | 1939 | | }; |
| | | 1940 | | } |
| | | 1941 | | |
| | | 1942 | | private StringBuilder AppendFormat<TArg0, TArg1, TArg2>(IFormatProvider? provider, CompositeFormat format, TArg0 |
| | | 1943 | | { |
| | | 1944 | | // Create the interpolated string handler. |
| | 0 | 1945 | | var handler = new AppendInterpolatedStringHandler(format._literalLength, format._formattedCount, this, provi |
| | | 1946 | | |
| | | 1947 | | // Append each segment. |
| | 0 | 1948 | | foreach ((string? Literal, int ArgIndex, int Alignment, string? Format) segment in format._segments) |
| | | 1949 | | { |
| | 0 | 1950 | | if (segment.Literal is string literal) |
| | | 1951 | | { |
| | 0 | 1952 | | handler.AppendLiteral(literal); |
| | | 1953 | | } |
| | | 1954 | | else |
| | | 1955 | | { |
| | 0 | 1956 | | int index = segment.ArgIndex; |
| | | 1957 | | switch (index) |
| | | 1958 | | { |
| | | 1959 | | case 0: |
| | 0 | 1960 | | handler.AppendFormatted(arg0, segment.Alignment, segment.Format); |
| | 0 | 1961 | | break; |
| | | 1962 | | |
| | | 1963 | | case 1: |
| | 0 | 1964 | | handler.AppendFormatted(arg1, segment.Alignment, segment.Format); |
| | 0 | 1965 | | break; |
| | | 1966 | | |
| | | 1967 | | case 2: |
| | 0 | 1968 | | handler.AppendFormatted(arg2, segment.Alignment, segment.Format); |
| | 0 | 1969 | | break; |
| | | 1970 | | |
| | | 1971 | | default: |
| | 0 | 1972 | | Debug.Assert(index > 2); |
| | 0 | 1973 | | handler.AppendFormatted(args[index], segment.Alignment, segment.Format); |
| | | 1974 | | break; |
| | | 1975 | | } |
| | | 1976 | | } |
| | | 1977 | | } |
| | | 1978 | | |
| | | 1979 | | // Complete the operation. |
| | 0 | 1980 | | 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> |
| | 0 | 1992 | | 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> |
| | 0 | 2003 | | 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 | | { |
| | 0 | 2011 | | if (sb == null) |
| | | 2012 | | { |
| | 0 | 2013 | | return false; |
| | | 2014 | | } |
| | 0 | 2015 | | if (Length != sb.Length) |
| | | 2016 | | { |
| | 0 | 2017 | | return false; |
| | | 2018 | | } |
| | 0 | 2019 | | if (sb == this) |
| | | 2020 | | { |
| | 0 | 2021 | | return true; |
| | | 2022 | | } |
| | 0 | 2023 | | StringBuilder? thisChunk = this; |
| | 0 | 2024 | | int thisChunkIndex = thisChunk.m_ChunkLength; |
| | 0 | 2025 | | StringBuilder? sbChunk = sb; |
| | 0 | 2026 | | int sbChunkIndex = sbChunk.m_ChunkLength; |
| | | 2027 | | while (true) |
| | | 2028 | | { |
| | 0 | 2029 | | --thisChunkIndex; |
| | 0 | 2030 | | --sbChunkIndex; |
| | | 2031 | | |
| | 0 | 2032 | | while (thisChunkIndex < 0) |
| | | 2033 | | { |
| | 0 | 2034 | | thisChunk = thisChunk.m_ChunkPrevious; |
| | 0 | 2035 | | if (thisChunk == null) |
| | | 2036 | | { |
| | | 2037 | | break; |
| | | 2038 | | } |
| | 0 | 2039 | | thisChunkIndex = thisChunk.m_ChunkLength + thisChunkIndex; |
| | | 2040 | | } |
| | | 2041 | | |
| | 0 | 2042 | | while (sbChunkIndex < 0) |
| | | 2043 | | { |
| | 0 | 2044 | | sbChunk = sbChunk.m_ChunkPrevious; |
| | 0 | 2045 | | if (sbChunk == null) |
| | | 2046 | | { |
| | | 2047 | | break; |
| | | 2048 | | } |
| | 0 | 2049 | | sbChunkIndex = sbChunk.m_ChunkLength + sbChunkIndex; |
| | | 2050 | | } |
| | | 2051 | | |
| | 0 | 2052 | | if (thisChunkIndex < 0) |
| | | 2053 | | { |
| | 0 | 2054 | | return sbChunkIndex < 0; |
| | | 2055 | | } |
| | 0 | 2056 | | if (sbChunkIndex < 0) |
| | | 2057 | | { |
| | 0 | 2058 | | return false; |
| | | 2059 | | } |
| | | 2060 | | |
| | 0 | 2061 | | Debug.Assert(thisChunk != null && sbChunk != null); |
| | 0 | 2062 | | if (thisChunk.m_ChunkChars[thisChunkIndex] != sbChunk.m_ChunkChars[sbChunkIndex]) |
| | | 2063 | | { |
| | 0 | 2064 | | 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 | | { |
| | 0 | 2075 | | if (span.Length != Length) |
| | | 2076 | | { |
| | 0 | 2077 | | return false; |
| | | 2078 | | } |
| | | 2079 | | |
| | 0 | 2080 | | StringBuilder? sbChunk = this; |
| | 0 | 2081 | | int offset = 0; |
| | | 2082 | | |
| | | 2083 | | do |
| | | 2084 | | { |
| | 0 | 2085 | | int chunk_length = sbChunk.m_ChunkLength; |
| | 0 | 2086 | | offset += chunk_length; |
| | | 2087 | | |
| | 0 | 2088 | | ReadOnlySpan<char> chunk = new ReadOnlySpan<char>(sbChunk.m_ChunkChars, 0, chunk_length); |
| | | 2089 | | |
| | 0 | 2090 | | if (!chunk.EqualsOrdinal(span.Slice(span.Length - offset, chunk_length))) |
| | | 2091 | | { |
| | 0 | 2092 | | return false; |
| | | 2093 | | } |
| | | 2094 | | |
| | 0 | 2095 | | sbChunk = sbChunk.m_ChunkPrevious; |
| | 0 | 2096 | | } while (sbChunk != null); |
| | | 2097 | | |
| | 0 | 2098 | | Debug.Assert(offset == Length); |
| | 0 | 2099 | | 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 | | { |
| | 0 | 2115 | | ArgumentException.ThrowIfNullOrEmpty(oldValue); |
| | 0 | 2116 | | 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 | | { |
| | 0 | 2132 | | int currentLength = Length; |
| | 0 | 2133 | | if ((uint)startIndex > (uint)currentLength) |
| | | 2134 | | { |
| | 0 | 2135 | | throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); |
| | | 2136 | | } |
| | 0 | 2137 | | if (count < 0 || startIndex > currentLength - count) |
| | | 2138 | | { |
| | 0 | 2139 | | throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); |
| | | 2140 | | } |
| | 0 | 2141 | | if (oldValue.Length == 0) |
| | | 2142 | | { |
| | 0 | 2143 | | throw new ArgumentException(SR.Arg_EmptySpan, nameof(oldValue)); |
| | | 2144 | | } |
| | | 2145 | | |
| | 0 | 2146 | | 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 |
| | 0 | 2149 | | StringBuilder chunk = FindChunkForIndex(startIndex); |
| | 0 | 2150 | | int indexInChunk = startIndex - chunk.m_ChunkOffset; |
| | 0 | 2151 | | while (count > 0) |
| | | 2152 | | { |
| | 0 | 2153 | | 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. |
| | 0 | 2159 | | ReadOnlySpan<char> remainingChunk = chunk.m_ChunkChars.AsSpan(indexInChunk, Math.Min(chunk.m_ChunkLength |
| | 0 | 2160 | | while (oldValue.Length <= remainingChunk.Length) |
| | | 2161 | | { |
| | | 2162 | | // Find the next match. |
| | 0 | 2163 | | int foundPos = remainingChunk.IndexOf(oldValue); |
| | 0 | 2164 | | if (foundPos >= 0) |
| | | 2165 | | { |
| | | 2166 | | // We found one. Add it as a location for the replacement. |
| | 0 | 2167 | | indexInChunk += foundPos; |
| | 0 | 2168 | | replacements.Append(indexInChunk); |
| | | 2169 | | |
| | | 2170 | | // Move ahead to the next location. |
| | 0 | 2171 | | remainingChunk = remainingChunk.Slice(foundPos + oldValue.Length); |
| | 0 | 2172 | | indexInChunk += oldValue.Length; |
| | 0 | 2173 | | 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. |
| | 0 | 2177 | | Debug.Assert(count >= 0, "count should never go negative"); |
| | 0 | 2178 | | if (count == 0) |
| | | 2179 | | { |
| | 0 | 2180 | | 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. |
| | 0 | 2188 | | int move = remainingChunk.Length - (oldValue.Length - 1); |
| | 0 | 2189 | | indexInChunk += move; |
| | 0 | 2190 | | count -= move; |
| | 0 | 2191 | | break; |
| | | 2192 | | } |
| | | 2193 | | } |
| | | 2194 | | |
| | 0 | 2195 | | Debug.Assert(oldValue.Length > Math.Min(count, chunk.m_ChunkLength - indexInChunk), |
| | 0 | 2196 | | $"oldValue.Length = {oldValue.Length}, chunk.m_ChunkLength - indexInChunk = {chunk.m_ChunkLength - i |
| | | 2197 | | |
| | | 2198 | | // Now do the more complicated cross-chunk matching. |
| | 0 | 2199 | | while (indexInChunk < chunk.m_ChunkLength && count > 0) |
| | | 2200 | | { |
| | 0 | 2201 | | if (StartsWith(chunk, indexInChunk, count, oldValue)) |
| | | 2202 | | { |
| | 0 | 2203 | | replacements.Append(indexInChunk); |
| | 0 | 2204 | | indexInChunk += oldValue.Length; |
| | 0 | 2205 | | count -= oldValue.Length; |
| | | 2206 | | } |
| | | 2207 | | else |
| | | 2208 | | { |
| | 0 | 2209 | | indexInChunk++; |
| | 0 | 2210 | | --count; |
| | | 2211 | | } |
| | | 2212 | | } |
| | | 2213 | | |
| | | 2214 | | // We've either fully explored the chunk or we've reached our count limit. |
| | 0 | 2215 | | Debug.Assert(indexInChunk >= chunk.m_ChunkLength || count == 0, |
| | 0 | 2216 | | $"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. |
| | 0 | 2219 | | int index = indexInChunk + chunk.m_ChunkOffset; |
| | | 2220 | | |
| | | 2221 | | // Apply any replacements we accumulated. |
| | 0 | 2222 | | 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. |
| | 0 | 2226 | | ReplaceAllInChunk(replacements.AsSpan(), chunk, oldValue.Length, newValue); |
| | 0 | 2227 | | index += (newValue.Length - oldValue.Length) * replacements.Length; |
| | 0 | 2228 | | replacements.Length = 0; |
| | | 2229 | | } |
| | | 2230 | | |
| | 0 | 2231 | | chunk = FindChunkForIndex(index); |
| | 0 | 2232 | | indexInChunk = index - chunk.m_ChunkOffset; |
| | 0 | 2233 | | Debug.Assert(chunk != null || count == 0, "Chunks ended prematurely!"); |
| | | 2234 | | } |
| | | 2235 | | |
| | 0 | 2236 | | replacements.Dispose(); |
| | | 2237 | | |
| | 0 | 2238 | | AssertInvariants(); |
| | 0 | 2239 | | 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 | | { |
| | 0 | 2249 | | 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 | | { |
| | 0 | 2261 | | int currentLength = Length; |
| | 0 | 2262 | | if ((uint)startIndex > (uint)currentLength) |
| | | 2263 | | { |
| | 0 | 2264 | | throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); |
| | | 2265 | | } |
| | | 2266 | | |
| | 0 | 2267 | | if (count < 0 || startIndex > currentLength - count) |
| | | 2268 | | { |
| | 0 | 2269 | | throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); |
| | | 2270 | | } |
| | | 2271 | | |
| | 0 | 2272 | | int endIndex = startIndex + count; |
| | 0 | 2273 | | StringBuilder chunk = this; |
| | | 2274 | | |
| | 0 | 2275 | | while (true) |
| | | 2276 | | { |
| | 0 | 2277 | | int endIndexInChunk = endIndex - chunk.m_ChunkOffset; |
| | 0 | 2278 | | int startIndexInChunk = startIndex - chunk.m_ChunkOffset; |
| | 0 | 2279 | | if (endIndexInChunk >= 0) |
| | | 2280 | | { |
| | 0 | 2281 | | int curInChunk = Math.Max(startIndexInChunk, 0); |
| | 0 | 2282 | | int endInChunk = Math.Min(chunk.m_ChunkLength, endIndexInChunk); |
| | | 2283 | | |
| | 0 | 2284 | | Span<char> span = chunk.m_ChunkChars.AsSpan(curInChunk, endInChunk - curInChunk); |
| | 0 | 2285 | | span.Replace(oldChar, newChar); |
| | | 2286 | | } |
| | | 2287 | | |
| | 0 | 2288 | | if (startIndexInChunk >= 0) |
| | | 2289 | | { |
| | | 2290 | | break; |
| | | 2291 | | } |
| | | 2292 | | |
| | 0 | 2293 | | Debug.Assert(chunk.m_ChunkPrevious != null); |
| | 0 | 2294 | | chunk = chunk.m_ChunkPrevious; |
| | | 2295 | | } |
| | | 2296 | | |
| | 0 | 2297 | | AssertInvariants(); |
| | 0 | 2298 | | 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 | | { |
| | 0 | 2309 | | 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 |
| | 0 | 2326 | | ReadOnlySpan<char> oldChars = oldRune.AsSpan(stackalloc char[Rune.MaxUtf16CharsPerRune]); |
| | | 2327 | | |
| | | 2328 | | // Convert newRune to span |
| | 0 | 2329 | | ReadOnlySpan<char> newChars = newRune.AsSpan(stackalloc char[Rune.MaxUtf16CharsPerRune]); |
| | | 2330 | | |
| | | 2331 | | // Replace span with span |
| | 0 | 2332 | | 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 |
| | 0 | 2344 | | ArgumentOutOfRangeException.ThrowIfNegative(valueCount); |
| | | 2345 | | |
| | 0 | 2346 | | Append(ref *value, valueCount); |
| | 0 | 2347 | | 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 | | { |
| | 40172 | 2353 | | Debug.Assert(valueCount >= 0, "Invalid length; should have been validated by caller."); |
| | 40172 | 2354 | | if (valueCount != 0) |
| | | 2355 | | { |
| | 40172 | 2356 | | char[] chunkChars = m_ChunkChars; |
| | 40172 | 2357 | | int chunkLength = m_ChunkLength; |
| | | 2358 | | |
| | 40172 | 2359 | | if (((uint)chunkLength + (uint)valueCount) <= (uint)chunkChars.Length) |
| | | 2360 | | { |
| | 40138 | 2361 | | ref char destination = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(chunkChars), chunkLeng |
| | 40138 | 2362 | | if (valueCount <= 2) |
| | | 2363 | | { |
| | 40111 | 2364 | | destination = value; |
| | 40111 | 2365 | | if (valueCount == 2) |
| | | 2366 | | { |
| | 41 | 2367 | | Unsafe.Add(ref destination, 1) = Unsafe.Add(ref value, 1); |
| | | 2368 | | } |
| | | 2369 | | } |
| | | 2370 | | else |
| | | 2371 | | { |
| | 27 | 2372 | | Buffer.Memmove(ref destination, ref value, (nuint)valueCount); |
| | | 2373 | | } |
| | | 2374 | | |
| | 40138 | 2375 | | m_ChunkLength = chunkLength + valueCount; |
| | | 2376 | | } |
| | | 2377 | | else |
| | | 2378 | | { |
| | 34 | 2379 | | AppendWithExpansion(ref value, valueCount); |
| | | 2380 | | } |
| | | 2381 | | } |
| | 34 | 2382 | | } |
| | | 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. |
| | 34 | 2388 | | int newLength = Length + valueCount; |
| | 34 | 2389 | | if (newLength > m_MaxCapacity || newLength < valueCount) |
| | | 2390 | | { |
| | 0 | 2391 | | throw new ArgumentOutOfRangeException(nameof(valueCount), SR.ArgumentOutOfRange_LengthGreaterThanCapacit |
| | | 2392 | | } |
| | | 2393 | | |
| | | 2394 | | // Copy the first chunk |
| | 34 | 2395 | | int firstLength = m_ChunkChars.Length - m_ChunkLength; |
| | 34 | 2396 | | if (firstLength > 0) |
| | | 2397 | | { |
| | 29 | 2398 | | new ReadOnlySpan<char>(ref value, firstLength).CopyTo(m_ChunkChars.AsSpan(m_ChunkLength)); |
| | 29 | 2399 | | m_ChunkLength = m_ChunkChars.Length; |
| | | 2400 | | } |
| | | 2401 | | |
| | | 2402 | | // Expand the builder to add another chunk. |
| | 34 | 2403 | | int restLength = valueCount - firstLength; |
| | 34 | 2404 | | ExpandByABlock(restLength); |
| | 34 | 2405 | | Debug.Assert(m_ChunkLength == 0, "A new block was not created."); |
| | | 2406 | | |
| | | 2407 | | // Copy the second chunk |
| | 34 | 2408 | | new ReadOnlySpan<char>(ref Unsafe.Add(ref value, firstLength), restLength).CopyTo(m_ChunkChars); |
| | 34 | 2409 | | m_ChunkLength = restLength; |
| | | 2410 | | |
| | 34 | 2411 | | AssertInvariants(); |
| | 34 | 2412 | | } |
| | | 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 | | { |
| | 0 | 2422 | | Debug.Assert((uint)index <= (uint)Length, "Callers should check that index is a legal value."); |
| | | 2423 | | |
| | 0 | 2424 | | if (valueCount > 0) |
| | | 2425 | | { |
| | 0 | 2426 | | MakeRoom(index, valueCount, out StringBuilder chunk, out int indexInChunk, false); |
| | 0 | 2427 | | ReplaceInPlaceAtChunk(ref chunk!, ref indexInChunk, ref value, valueCount); |
| | | 2428 | | } |
| | 0 | 2429 | | } |
| | | 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 | | { |
| | 0 | 2443 | | Debug.Assert(!replacements.IsEmpty); |
| | | 2444 | | |
| | | 2445 | | // calculate the total amount of extra space or space needed for all the replacements. |
| | 0 | 2446 | | long longDelta = (value.Length - removeCount) * (long)replacements.Length; |
| | 0 | 2447 | | int delta = (int)longDelta; |
| | 0 | 2448 | | if (delta != longDelta) |
| | | 2449 | | { |
| | 0 | 2450 | | throw new OutOfMemoryException(); |
| | | 2451 | | } |
| | | 2452 | | |
| | 0 | 2453 | | StringBuilder targetChunk = sourceChunk; // the target as we copy chars down |
| | 0 | 2454 | | int targetIndexInChunk = replacements[0]; |
| | | 2455 | | |
| | | 2456 | | // Make the room needed for all the new characters if needed. |
| | 0 | 2457 | | if (delta > 0) |
| | | 2458 | | { |
| | 0 | 2459 | | 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, |
| | 0 | 2463 | | int i = 0; |
| | 0 | 2464 | | while (true) |
| | | 2465 | | { |
| | | 2466 | | // Copy in the new string for the ith replacement |
| | 0 | 2467 | | ReplaceInPlaceAtChunk(ref targetChunk!, ref targetIndexInChunk, ref MemoryMarshal.GetReference<char>(val |
| | 0 | 2468 | | int gapStart = replacements[i] + removeCount; |
| | 0 | 2469 | | i++; |
| | 0 | 2470 | | if ((uint)i >= replacements.Length) |
| | | 2471 | | { |
| | | 2472 | | break; |
| | | 2473 | | } |
| | | 2474 | | |
| | 0 | 2475 | | int gapEnd = replacements[i]; |
| | 0 | 2476 | | Debug.Assert(gapStart < sourceChunk.m_ChunkChars.Length, "gap starts at end of buffer. Should not happe |
| | 0 | 2477 | | Debug.Assert(gapStart <= gapEnd, "negative gap size"); |
| | 0 | 2478 | | Debug.Assert(gapEnd <= sourceChunk.m_ChunkLength, "gap too big"); |
| | 0 | 2479 | | 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 |
| | 0 | 2482 | | ReplaceInPlaceAtChunk(ref targetChunk!, ref targetIndexInChunk, ref sourceChunk.m_ChunkChars[gapStar |
| | | 2483 | | } |
| | | 2484 | | else |
| | | 2485 | | { |
| | 0 | 2486 | | targetIndexInChunk += gapEnd - gapStart; |
| | 0 | 2487 | | Debug.Assert(targetIndexInChunk <= targetChunk.m_ChunkLength, "gap not in chunk"); |
| | | 2488 | | } |
| | | 2489 | | } |
| | | 2490 | | |
| | | 2491 | | // Remove extra space if necessary. |
| | 0 | 2492 | | if (delta < 0) |
| | | 2493 | | { |
| | 0 | 2494 | | Remove(targetChunk.m_ChunkOffset + targetIndexInChunk, -delta, out targetChunk, out targetIndexInChunk); |
| | | 2495 | | } |
| | 0 | 2496 | | } |
| | | 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 | | { |
| | 0 | 2507 | | for (int i = 0; i < value.Length; i++) |
| | | 2508 | | { |
| | 0 | 2509 | | if (count == 0) |
| | | 2510 | | { |
| | 0 | 2511 | | return false; |
| | | 2512 | | } |
| | | 2513 | | |
| | 0 | 2514 | | if (indexInChunk >= chunk.m_ChunkLength) |
| | | 2515 | | { |
| | 0 | 2516 | | chunk = Next(chunk)!; |
| | 0 | 2517 | | if (chunk == null) |
| | | 2518 | | { |
| | 0 | 2519 | | return false; |
| | | 2520 | | } |
| | 0 | 2521 | | indexInChunk = 0; |
| | | 2522 | | } |
| | | 2523 | | |
| | 0 | 2524 | | if (value[i] != chunk.m_ChunkChars[indexInChunk]) |
| | | 2525 | | { |
| | 0 | 2526 | | return false; |
| | | 2527 | | } |
| | | 2528 | | |
| | 0 | 2529 | | indexInChunk++; |
| | 0 | 2530 | | --count; |
| | | 2531 | | } |
| | | 2532 | | |
| | 0 | 2533 | | 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 | | { |
| | 0 | 2552 | | if (count != 0) |
| | | 2553 | | { |
| | 0 | 2554 | | while (true) |
| | | 2555 | | { |
| | 0 | 2556 | | Debug.Assert(chunk != null, "chunk should not be null at this point"); |
| | 0 | 2557 | | int lengthInChunk = chunk.m_ChunkLength - indexInChunk; |
| | 0 | 2558 | | Debug.Assert(lengthInChunk >= 0, "Index isn't in the chunk."); |
| | | 2559 | | |
| | 0 | 2560 | | int lengthToCopy = Math.Min(lengthInChunk, count); |
| | 0 | 2561 | | new ReadOnlySpan<char>(ref value, lengthToCopy).CopyTo(chunk.m_ChunkChars.AsSpan(indexInChunk)); |
| | | 2562 | | |
| | | 2563 | | // Advance the index. |
| | 0 | 2564 | | indexInChunk += lengthToCopy; |
| | 0 | 2565 | | if (indexInChunk >= chunk.m_ChunkLength) |
| | | 2566 | | { |
| | 0 | 2567 | | chunk = Next(chunk); |
| | 0 | 2568 | | indexInChunk = 0; |
| | | 2569 | | } |
| | 0 | 2570 | | count -= lengthToCopy; |
| | 0 | 2571 | | if (count == 0) |
| | | 2572 | | { |
| | | 2573 | | break; |
| | | 2574 | | } |
| | 0 | 2575 | | value = ref Unsafe.Add(ref value, lengthToCopy); |
| | | 2576 | | } |
| | | 2577 | | } |
| | 0 | 2578 | | } |
| | | 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 | | { |
| | 0 | 2590 | | Debug.Assert(0 <= index && index <= Length); |
| | | 2591 | | |
| | 0 | 2592 | | StringBuilder result = this; |
| | 0 | 2593 | | while (result.m_ChunkOffset > index) |
| | | 2594 | | { |
| | 0 | 2595 | | Debug.Assert(result.m_ChunkPrevious != null); |
| | 0 | 2596 | | result = result.m_ChunkPrevious; |
| | | 2597 | | } |
| | | 2598 | | |
| | 0 | 2599 | | Debug.Assert(result != null); |
| | 0 | 2600 | | 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)] |
| | 20073 | 2607 | | 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> |
| | 0 | 2620 | | 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 | | { |
| | 37 | 2632 | | Debug.Assert(Capacity == Length, nameof(ExpandByABlock) + " should only be called when there is no space lef |
| | 37 | 2633 | | Debug.Assert(minBlockCharCount > 0); |
| | | 2634 | | |
| | 37 | 2635 | | AssertInvariants(); |
| | | 2636 | | |
| | 37 | 2637 | | if ((minBlockCharCount + Length) > m_MaxCapacity || minBlockCharCount + Length < minBlockCharCount) |
| | | 2638 | | { |
| | 0 | 2639 | | 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. |
| | 37 | 2646 | | int newBlockLength = Math.Max(minBlockCharCount, Math.Min(Length, MaxChunkSize)); |
| | | 2647 | | |
| | | 2648 | | // Check for integer overflow (logical buffer size > int.MaxValue) |
| | 37 | 2649 | | if (m_ChunkOffset + m_ChunkLength + newBlockLength < newBlockLength) |
| | | 2650 | | { |
| | 0 | 2651 | | throw new OutOfMemoryException(); |
| | | 2652 | | } |
| | | 2653 | | |
| | | 2654 | | // Allocate the array before updating any state to avoid leaving inconsistent state behind in case of out of |
| | 37 | 2655 | | 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. |
| | 37 | 2659 | | m_ChunkPrevious = new StringBuilder(this); |
| | 37 | 2660 | | m_ChunkOffset += m_ChunkLength; |
| | 37 | 2661 | | m_ChunkLength = 0; |
| | | 2662 | | |
| | 37 | 2663 | | m_ChunkChars = chunkChars; |
| | | 2664 | | |
| | 37 | 2665 | | AssertInvariants(); |
| | 37 | 2666 | | } |
| | | 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> |
| | 37 | 2683 | | private StringBuilder(StringBuilder from) |
| | | 2684 | | { |
| | 37 | 2685 | | m_ChunkLength = from.m_ChunkLength; |
| | 37 | 2686 | | m_ChunkOffset = from.m_ChunkOffset; |
| | 37 | 2687 | | m_ChunkChars = from.m_ChunkChars; |
| | 37 | 2688 | | m_ChunkPrevious = from.m_ChunkPrevious; |
| | 37 | 2689 | | m_MaxCapacity = from.m_MaxCapacity; |
| | | 2690 | | |
| | 37 | 2691 | | AssertInvariants(); |
| | 37 | 2692 | | } |
| | | 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 | | { |
| | 0 | 2722 | | AssertInvariants(); |
| | 0 | 2723 | | Debug.Assert(count > 0); |
| | 0 | 2724 | | Debug.Assert(index >= 0); |
| | | 2725 | | |
| | 0 | 2726 | | if (count + Length > m_MaxCapacity || count + Length < count) |
| | | 2727 | | { |
| | 0 | 2728 | | throw new ArgumentOutOfRangeException("requiredLength", SR.ArgumentOutOfRange_SmallCapacity); |
| | | 2729 | | } |
| | | 2730 | | |
| | 0 | 2731 | | chunk = this; |
| | 0 | 2732 | | while (chunk.m_ChunkOffset > index) |
| | | 2733 | | { |
| | 0 | 2734 | | chunk.m_ChunkOffset += count; |
| | 0 | 2735 | | Debug.Assert(chunk.m_ChunkPrevious != null); |
| | 0 | 2736 | | chunk = chunk.m_ChunkPrevious; |
| | | 2737 | | } |
| | 0 | 2738 | | 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 |
| | 0 | 2742 | | if (!doNotMoveFollowingChars && chunk.m_ChunkLength <= DefaultCapacity * 2 && chunk.m_ChunkChars.Length - ch |
| | | 2743 | | { |
| | 0 | 2744 | | for (int i = chunk.m_ChunkLength; i > indexInChunk;) |
| | | 2745 | | { |
| | 0 | 2746 | | --i; |
| | 0 | 2747 | | chunk.m_ChunkChars[i + count] = chunk.m_ChunkChars[i]; |
| | | 2748 | | } |
| | 0 | 2749 | | chunk.m_ChunkLength += count; |
| | 0 | 2750 | | return; |
| | | 2751 | | } |
| | | 2752 | | |
| | | 2753 | | // Allocate space for the new chunk, which will go before the current one. |
| | 0 | 2754 | | StringBuilder newChunk = new StringBuilder(Math.Max(count, DefaultCapacity), chunk.m_MaxCapacity, chunk.m_Ch |
| | 0 | 2755 | | newChunk.m_ChunkLength = count; |
| | | 2756 | | |
| | | 2757 | | // Copy the head of the current buffer to the new buffer. |
| | 0 | 2758 | | int copyCount1 = Math.Min(count, indexInChunk); |
| | 0 | 2759 | | if (copyCount1 > 0) |
| | | 2760 | | { |
| | 0 | 2761 | | new ReadOnlySpan<char>(chunk.m_ChunkChars, 0, copyCount1).CopyTo(newChunk.m_ChunkChars); |
| | | 2762 | | |
| | | 2763 | | // Slide characters over in the current buffer to make room. |
| | 0 | 2764 | | int copyCount2 = indexInChunk - copyCount1; |
| | 0 | 2765 | | if (copyCount2 >= 0) |
| | | 2766 | | { |
| | 0 | 2767 | | new ReadOnlySpan<char>(chunk.m_ChunkChars, copyCount1, copyCount2).CopyTo(chunk.m_ChunkChars); |
| | 0 | 2768 | | indexInChunk = copyCount2; |
| | | 2769 | | } |
| | | 2770 | | } |
| | | 2771 | | |
| | | 2772 | | // Wire in the new chunk. |
| | 0 | 2773 | | chunk.m_ChunkPrevious = newChunk; |
| | 0 | 2774 | | chunk.m_ChunkOffset += count; |
| | 0 | 2775 | | if (copyCount1 < count) |
| | | 2776 | | { |
| | 0 | 2777 | | chunk = newChunk; |
| | 0 | 2778 | | indexInChunk = copyCount1; |
| | | 2779 | | } |
| | | 2780 | | |
| | 0 | 2781 | | AssertInvariants(); |
| | 0 | 2782 | | } |
| | | 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> |
| | 0 | 2790 | | private StringBuilder(int size, int maxCapacity, StringBuilder? previousBlock) |
| | | 2791 | | { |
| | 0 | 2792 | | Debug.Assert(size > 0); |
| | 0 | 2793 | | Debug.Assert(maxCapacity > 0); |
| | | 2794 | | |
| | 0 | 2795 | | m_ChunkChars = GC.AllocateUninitializedArray<char>(size); |
| | 0 | 2796 | | m_MaxCapacity = maxCapacity; |
| | 0 | 2797 | | m_ChunkPrevious = previousBlock; |
| | 0 | 2798 | | if (previousBlock != null) |
| | | 2799 | | { |
| | 0 | 2800 | | m_ChunkOffset = previousBlock.m_ChunkOffset + previousBlock.m_ChunkLength; |
| | | 2801 | | } |
| | | 2802 | | |
| | 0 | 2803 | | AssertInvariants(); |
| | 0 | 2804 | | } |
| | | 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 | | { |
| | 0 | 2817 | | AssertInvariants(); |
| | 0 | 2818 | | Debug.Assert(startIndex >= 0 && startIndex < Length); |
| | | 2819 | | |
| | 0 | 2820 | | int endIndex = startIndex + count; |
| | | 2821 | | |
| | | 2822 | | // Find the chunks for the start and end of the block to delete. |
| | 0 | 2823 | | chunk = this; |
| | 0 | 2824 | | StringBuilder? endChunk = null; |
| | 0 | 2825 | | int endIndexInChunk = 0; |
| | 0 | 2826 | | while (true) |
| | | 2827 | | { |
| | 0 | 2828 | | if (endIndex - chunk.m_ChunkOffset >= 0) |
| | | 2829 | | { |
| | 0 | 2830 | | if (endChunk == null) |
| | | 2831 | | { |
| | 0 | 2832 | | endChunk = chunk; |
| | 0 | 2833 | | endIndexInChunk = endIndex - endChunk.m_ChunkOffset; |
| | | 2834 | | } |
| | 0 | 2835 | | if (startIndex - chunk.m_ChunkOffset >= 0) |
| | | 2836 | | { |
| | 0 | 2837 | | indexInChunk = startIndex - chunk.m_ChunkOffset; |
| | 0 | 2838 | | break; |
| | | 2839 | | } |
| | | 2840 | | } |
| | | 2841 | | else |
| | | 2842 | | { |
| | 0 | 2843 | | chunk.m_ChunkOffset -= count; |
| | | 2844 | | } |
| | | 2845 | | |
| | 0 | 2846 | | Debug.Assert(chunk.m_ChunkPrevious != null); |
| | 0 | 2847 | | chunk = chunk.m_ChunkPrevious; |
| | | 2848 | | } |
| | 0 | 2849 | | Debug.Assert(chunk != null, "We fell off the beginning of the string!"); |
| | | 2850 | | |
| | 0 | 2851 | | int copyTargetIndexInChunk = indexInChunk; |
| | 0 | 2852 | | int copyCount = endChunk.m_ChunkLength - endIndexInChunk; |
| | 0 | 2853 | | if (endChunk != chunk) |
| | | 2854 | | { |
| | 0 | 2855 | | copyTargetIndexInChunk = 0; |
| | | 2856 | | // Remove the characters after `startIndex` to the end of the chunk. |
| | 0 | 2857 | | chunk.m_ChunkLength = indexInChunk; |
| | | 2858 | | |
| | | 2859 | | // Remove the characters in chunks between the start and the end chunk. |
| | 0 | 2860 | | endChunk.m_ChunkPrevious = chunk; |
| | 0 | 2861 | | 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. |
| | 0 | 2864 | | if (indexInChunk == 0) |
| | | 2865 | | { |
| | 0 | 2866 | | endChunk.m_ChunkPrevious = chunk.m_ChunkPrevious; |
| | 0 | 2867 | | chunk = endChunk; |
| | | 2868 | | } |
| | | 2869 | | } |
| | 0 | 2870 | | 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. |
| | 0 | 2876 | | if (copyTargetIndexInChunk != endIndexInChunk) // Sometimes no move is necessary |
| | | 2877 | | { |
| | 0 | 2878 | | new ReadOnlySpan<char>(endChunk.m_ChunkChars, endIndexInChunk, copyCount).CopyTo(endChunk.m_ChunkChars.A |
| | | 2879 | | } |
| | | 2880 | | |
| | 0 | 2881 | | Debug.Assert(chunk != null, "We fell off the beginning of the string!"); |
| | 0 | 2882 | | AssertInvariants(); |
| | 0 | 2883 | | } |
| | | 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 | | { |
| | 0 | 2894 | | if (TryGetRuneAt(index, out Rune value)) |
| | | 2895 | | { |
| | 0 | 2896 | | return value; |
| | | 2897 | | } |
| | 0 | 2898 | | 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 | | { |
| | 0 | 2914 | | ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, Length); |
| | 0 | 2915 | | ArgumentOutOfRangeException.ThrowIfNegative(index); |
| | | 2916 | | |
| | | 2917 | | // Get span at StringBuilder index |
| | 0 | 2918 | | Span<char> chars = index + 1 < Length |
| | 0 | 2919 | | ? [this[index], this[index + 1]] |
| | 0 | 2920 | | : [this[index]]; |
| | | 2921 | | |
| | 0 | 2922 | | OperationStatus status = Rune.DecodeFromUtf16(chars, out Rune result, out _); |
| | 0 | 2923 | | if (status is OperationStatus.Done) |
| | | 2924 | | { |
| | 0 | 2925 | | value = result; |
| | 0 | 2926 | | return true; |
| | | 2927 | | } |
| | | 2928 | | |
| | 0 | 2929 | | value = default; |
| | 0 | 2930 | | 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 | | { |
| | 20015 | 2964 | | _stringBuilder = stringBuilder; |
| | 20015 | 2965 | | _provider = null; |
| | 20015 | 2966 | | _hasCustomFormatter = false; |
| | 20015 | 2967 | | } |
| | | 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 | | { |
| | 0 | 2977 | | _stringBuilder = stringBuilder; |
| | 0 | 2978 | | _provider = provider; |
| | 0 | 2979 | | _hasCustomFormatter = provider is not null && DefaultInterpolatedStringHandler.HasCustomFormatter(provid |
| | 0 | 2980 | | } |
| | | 2981 | | |
| | | 2982 | | /// <summary>Writes the specified string to the handler.</summary> |
| | | 2983 | | /// <param name="value">The string to write.</param> |
| | 40030 | 2984 | | 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 | | |
| | 0 | 3000 | | if (_hasCustomFormatter) |
| | | 3001 | | { |
| | | 3002 | | // If there's a custom formatter, always use it. |
| | 0 | 3003 | | AppendCustomFormatter(value, format: null); |
| | 0 | 3004 | | return; |
| | | 3005 | | } |
| | | 3006 | | |
| | 0 | 3007 | | if (value is null) |
| | | 3008 | | { |
| | 0 | 3009 | | return; |
| | | 3010 | | } |
| | | 3011 | | |
| | 0 | 3012 | | 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 | | |
| | 0 | 3022 | | if (typeof(T).IsEnum) |
| | | 3023 | | { |
| | 0 | 3024 | | if (Enum.TryFormatUnconstrained(value, _stringBuilder.RemainingCurrentChunk, out int charsWritte |
| | | 3025 | | { |
| | 0 | 3026 | | _stringBuilder.m_ChunkLength += charsWritten; |
| | | 3027 | | } |
| | | 3028 | | else |
| | | 3029 | | { |
| | 0 | 3030 | | AppendFormattedWithTempSpace(value, 0, format: null); |
| | | 3031 | | } |
| | | 3032 | | } |
| | 0 | 3033 | | else if (value is ISpanFormattable) |
| | | 3034 | | { |
| | 0 | 3035 | | Span<char> destination = _stringBuilder.RemainingCurrentChunk; |
| | 0 | 3036 | | if (((ISpanFormattable)value).TryFormat(destination, out int charsWritten, default, _provider)) |
| | | 3037 | | { |
| | 0 | 3038 | | 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 |
| | 0 | 3042 | | ThrowHelper.ThrowFormatInvalidString(); |
| | | 3043 | | } |
| | | 3044 | | |
| | 0 | 3045 | | _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. |
| | 0 | 3051 | | AppendFormattedWithTempSpace(value, 0, format: null); |
| | | 3052 | | } |
| | | 3053 | | } |
| | | 3054 | | else |
| | | 3055 | | { |
| | 0 | 3056 | | _stringBuilder.Append(((IFormattable)value).ToString(format: null, _provider)); // constrained c |
| | | 3057 | | } |
| | | 3058 | | } |
| | | 3059 | | else |
| | | 3060 | | { |
| | 0 | 3061 | | _stringBuilder.Append(value.ToString()); |
| | | 3062 | | } |
| | 0 | 3063 | | } |
| | | 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 | | { |
| | 20015 | 3071 | | if (_hasCustomFormatter) |
| | | 3072 | | { |
| | | 3073 | | // If there's a custom formatter, always use it. |
| | 0 | 3074 | | AppendCustomFormatter(value, format); |
| | 0 | 3075 | | return; |
| | | 3076 | | } |
| | | 3077 | | |
| | 20015 | 3078 | | if (value is null) |
| | | 3079 | | { |
| | 0 | 3080 | | return; |
| | | 3081 | | } |
| | | 3082 | | |
| | 20015 | 3083 | | 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 | | |
| | 20015 | 3093 | | if (typeof(T).IsEnum) |
| | | 3094 | | { |
| | 0 | 3095 | | if (Enum.TryFormatUnconstrained(value, _stringBuilder.RemainingCurrentChunk, out int charsWritte |
| | | 3096 | | { |
| | 0 | 3097 | | _stringBuilder.m_ChunkLength += charsWritten; |
| | | 3098 | | } |
| | | 3099 | | else |
| | | 3100 | | { |
| | 0 | 3101 | | AppendFormattedWithTempSpace(value, 0, format); |
| | | 3102 | | } |
| | | 3103 | | } |
| | 20015 | 3104 | | else if (value is ISpanFormattable) |
| | | 3105 | | { |
| | 20015 | 3106 | | Span<char> destination = _stringBuilder.RemainingCurrentChunk; |
| | 20015 | 3107 | | if (((ISpanFormattable)value).TryFormat(destination, out int charsWritten, format, _provider)) / |
| | | 3108 | | { |
| | 20015 | 3109 | | 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 |
| | 0 | 3113 | | ThrowHelper.ThrowFormatInvalidString(); |
| | | 3114 | | } |
| | | 3115 | | |
| | 20015 | 3116 | | _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. |
| | 0 | 3122 | | AppendFormattedWithTempSpace(value, 0, format); |
| | | 3123 | | } |
| | | 3124 | | } |
| | | 3125 | | else |
| | | 3126 | | { |
| | 0 | 3127 | | _stringBuilder.Append(((IFormattable)value).ToString(format, _provider)); // constrained call av |
| | | 3128 | | } |
| | | 3129 | | } |
| | | 3130 | | else |
| | | 3131 | | { |
| | 0 | 3132 | | _stringBuilder.Append(value.ToString()); |
| | | 3133 | | } |
| | 0 | 3134 | | } |
| | | 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) => |
| | 0 | 3141 | | 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 | | { |
| | 0 | 3150 | | if (alignment == 0) |
| | | 3151 | | { |
| | | 3152 | | // This overload is used as a fallback from several disambiguation overloads, so special-case 0. |
| | 0 | 3153 | | AppendFormatted(value, format); |
| | | 3154 | | } |
| | 0 | 3155 | | else if (alignment < 0) |
| | | 3156 | | { |
| | | 3157 | | // Left aligned: format into the handler, then append any additional padding required. |
| | 0 | 3158 | | int start = _stringBuilder.Length; |
| | 0 | 3159 | | AppendFormatted(value, format); |
| | 0 | 3160 | | int paddingRequired = -alignment - (_stringBuilder.Length - start); |
| | 0 | 3161 | | if (paddingRequired > 0) |
| | | 3162 | | { |
| | 0 | 3163 | | _stringBuilder.Append(' ', paddingRequired); |
| | | 3164 | | } |
| | | 3165 | | } |
| | | 3166 | | else |
| | | 3167 | | { |
| | | 3168 | | // Right aligned: format into temporary space and then copy that into the handler, appropriately ali |
| | 0 | 3169 | | AppendFormattedWithTempSpace(value, alignment, format); |
| | | 3170 | | } |
| | 0 | 3171 | | } |
| | | 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 | | |
| | 0 | 3181 | | var handler = new DefaultInterpolatedStringHandler(0, 0, _provider, stackalloc char[string.StackallocCha |
| | 0 | 3182 | | handler.AppendFormatted(value, format); |
| | 0 | 3183 | | AppendFormatted(handler.Text, alignment); |
| | 0 | 3184 | | handler.Clear(); |
| | 0 | 3185 | | } |
| | | 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> |
| | 0 | 3191 | | 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 | | { |
| | 0 | 3199 | | if (alignment == 0) |
| | | 3200 | | { |
| | 0 | 3201 | | _stringBuilder.Append(value); |
| | | 3202 | | } |
| | | 3203 | | else |
| | | 3204 | | { |
| | 0 | 3205 | | bool leftAlign = false; |
| | 0 | 3206 | | if (alignment < 0) |
| | | 3207 | | { |
| | 0 | 3208 | | leftAlign = true; |
| | 0 | 3209 | | alignment = -alignment; |
| | | 3210 | | } |
| | | 3211 | | |
| | 0 | 3212 | | int paddingRequired = alignment - value.Length; |
| | 0 | 3213 | | if (paddingRequired <= 0) |
| | | 3214 | | { |
| | 0 | 3215 | | _stringBuilder.Append(value); |
| | | 3216 | | } |
| | 0 | 3217 | | else if (leftAlign) |
| | | 3218 | | { |
| | 0 | 3219 | | _stringBuilder.Append(value); |
| | 0 | 3220 | | _stringBuilder.Append(' ', paddingRequired); |
| | | 3221 | | } |
| | | 3222 | | else |
| | | 3223 | | { |
| | 0 | 3224 | | _stringBuilder.Append(' ', paddingRequired); |
| | 0 | 3225 | | _stringBuilder.Append(value); |
| | | 3226 | | } |
| | | 3227 | | } |
| | 0 | 3228 | | } |
| | | 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 | | { |
| | 0 | 3236 | | if (!_hasCustomFormatter) |
| | | 3237 | | { |
| | 0 | 3238 | | _stringBuilder.Append(value); |
| | | 3239 | | } |
| | | 3240 | | else |
| | | 3241 | | { |
| | 0 | 3242 | | AppendFormatted<string?>(value); |
| | | 3243 | | } |
| | 0 | 3244 | | } |
| | | 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. |
| | 0 | 3254 | | 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. |
| | 0 | 3266 | | 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. |
| | 0 | 3281 | | Debug.Assert(_hasCustomFormatter); |
| | 0 | 3282 | | Debug.Assert(_provider != null); |
| | | 3283 | | |
| | 0 | 3284 | | ICustomFormatter? formatter = (ICustomFormatter?)_provider.GetFormat(typeof(ICustomFormatter)); |
| | 0 | 3285 | | Debug.Assert(formatter != null, "An incorrectly written provider said it implemented ICustomFormatter, a |
| | | 3286 | | |
| | 0 | 3287 | | if (formatter is not null) |
| | | 3288 | | { |
| | 0 | 3289 | | _stringBuilder.Append(formatter.Format(format, value, _provider)); |
| | | 3290 | | } |
| | 0 | 3291 | | } |
| | | 3292 | | } |
| | | 3293 | | } |
| | | 3294 | | } |
| | | 3295 | | |