StringBuilder.cs 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Text;
  5. using System.Runtime;
  6. using System.Runtime.Serialization;
  7. using System;
  8. using System.Runtime.CompilerServices;
  9. using System.Runtime.InteropServices;
  10. using System.Runtime.Versioning;
  11. using System.Security;
  12. using System.Threading;
  13. using System.Globalization;
  14. using System.Diagnostics;
  15. using System.Collections.Generic;
  16. namespace System.Text
  17. {
  18. // This class represents a mutable string. It is convenient for situations in
  19. // which it is desirable to modify a string, perhaps by removing, replacing, or
  20. // inserting characters, without creating a new String subsequent to
  21. // each modification.
  22. //
  23. // The methods contained within this class do not return a new StringBuilder
  24. // object unless specified otherwise. This class may be used in conjunction with the String
  25. // class to carry out modifications upon strings.
  26. [Serializable]
  27. [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
  28. public sealed partial class StringBuilder : ISerializable
  29. {
  30. // A StringBuilder is internally represented as a linked list of blocks each of which holds
  31. // a chunk of the string. It turns out string as a whole can also be represented as just a chunk,
  32. // so that is what we do.
  33. /// <summary>
  34. /// The character buffer for this chunk.
  35. /// </summary>
  36. internal char[] m_ChunkChars;
  37. /// <summary>
  38. /// The chunk that logically precedes this chunk.
  39. /// </summary>
  40. internal StringBuilder m_ChunkPrevious;
  41. /// <summary>
  42. /// The number of characters in this chunk.
  43. /// This is the number of elements in <see cref="m_ChunkChars"/> that are in use, from the start of the buffer.
  44. /// </summary>
  45. internal int m_ChunkLength;
  46. /// <summary>
  47. /// The logical offset of this chunk's characters in the string it is a part of.
  48. /// This is the sum of the number of characters in preceding blocks.
  49. /// </summary>
  50. internal int m_ChunkOffset;
  51. /// <summary>
  52. /// The maximum capacity this builder is allowed to have.
  53. /// </summary>
  54. internal int m_MaxCapacity;
  55. /// <summary>
  56. /// The default capacity of a <see cref="StringBuilder"/>.
  57. /// </summary>
  58. internal const int DefaultCapacity = 16;
  59. private const string CapacityField = "Capacity"; // Do not rename (binary serialization)
  60. private const string MaxCapacityField = "m_MaxCapacity"; // Do not rename (binary serialization)
  61. private const string StringValueField = "m_StringValue"; // Do not rename (binary serialization)
  62. private const string ThreadIDField = "m_currentThread"; // Do not rename (binary serialization)
  63. // We want to keep chunk arrays out of large object heap (< 85K bytes ~ 40K chars) to be sure.
  64. // Making the maximum chunk size big means less allocation code called, but also more waste
  65. // in unused characters and slower inserts / replaces (since you do need to slide characters over
  66. // within a buffer).
  67. internal const int MaxChunkSize = 8000;
  68. /// <summary>
  69. /// Initializes a new instance of the <see cref="StringBuilder"/> class.
  70. /// </summary>
  71. public StringBuilder()
  72. {
  73. m_MaxCapacity = int.MaxValue;
  74. m_ChunkChars = new char[DefaultCapacity];
  75. }
  76. /// <summary>
  77. /// Initializes a new instance of the <see cref="StringBuilder"/> class.
  78. /// </summary>
  79. /// <param name="capacity">The initial capacity of this builder.</param>
  80. public StringBuilder(int capacity)
  81. : this(capacity, int.MaxValue)
  82. {
  83. }
  84. /// <summary>
  85. /// Initializes a new instance of the <see cref="StringBuilder"/> class.
  86. /// </summary>
  87. /// <param name="value">The initial contents of this builder.</param>
  88. public StringBuilder(string value)
  89. : this(value, DefaultCapacity)
  90. {
  91. }
  92. /// <summary>
  93. /// Initializes a new instance of the <see cref="StringBuilder"/> class.
  94. /// </summary>
  95. /// <param name="value">The initial contents of this builder.</param>
  96. /// <param name="capacity">The initial capacity of this builder.</param>
  97. public StringBuilder(string value, int capacity)
  98. : this(value, 0, value?.Length ?? 0, capacity)
  99. {
  100. }
  101. /// <summary>
  102. /// Initializes a new instance of the <see cref="StringBuilder"/> class.
  103. /// </summary>
  104. /// <param name="value">The initial contents of this builder.</param>
  105. /// <param name="startIndex">The index to start in <paramref name="value"/>.</param>
  106. /// <param name="length">The number of characters to read in <paramref name="value"/>.</param>
  107. /// <param name="capacity">The initial capacity of this builder.</param>
  108. public StringBuilder(string value, int startIndex, int length, int capacity)
  109. {
  110. if (capacity < 0)
  111. {
  112. throw new ArgumentOutOfRangeException(nameof(capacity), SR.Format(SR.ArgumentOutOfRange_MustBePositive, nameof(capacity)));
  113. }
  114. if (length < 0)
  115. {
  116. throw new ArgumentOutOfRangeException(nameof(length), SR.Format(SR.ArgumentOutOfRange_MustBeNonNegNum, nameof(length)));
  117. }
  118. if (startIndex < 0)
  119. {
  120. throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
  121. }
  122. if (value == null)
  123. {
  124. value = string.Empty;
  125. }
  126. if (startIndex > value.Length - length)
  127. {
  128. throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexLength);
  129. }
  130. m_MaxCapacity = int.MaxValue;
  131. if (capacity == 0)
  132. {
  133. capacity = DefaultCapacity;
  134. }
  135. capacity = Math.Max(capacity, length);
  136. m_ChunkChars = new char[capacity];
  137. m_ChunkLength = length;
  138. unsafe
  139. {
  140. fixed (char* sourcePtr = value)
  141. {
  142. ThreadSafeCopy(sourcePtr + startIndex, m_ChunkChars, 0, length);
  143. }
  144. }
  145. }
  146. /// <summary>
  147. /// Initializes a new instance of the <see cref="StringBuilder"/> class.
  148. /// </summary>
  149. /// <param name="capacity">The initial capacity of this builder.</param>
  150. /// <param name="maxCapacity">The maximum capacity of this builder.</param>
  151. public StringBuilder(int capacity, int maxCapacity)
  152. {
  153. if (capacity > maxCapacity)
  154. {
  155. throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_Capacity);
  156. }
  157. if (maxCapacity < 1)
  158. {
  159. throw new ArgumentOutOfRangeException(nameof(maxCapacity), SR.ArgumentOutOfRange_SmallMaxCapacity);
  160. }
  161. if (capacity < 0)
  162. {
  163. throw new ArgumentOutOfRangeException(nameof(capacity), SR.Format(SR.ArgumentOutOfRange_MustBePositive, nameof(capacity)));
  164. }
  165. if (capacity == 0)
  166. {
  167. capacity = Math.Min(DefaultCapacity, maxCapacity);
  168. }
  169. m_MaxCapacity = maxCapacity;
  170. m_ChunkChars = new char[capacity];
  171. }
  172. private StringBuilder(SerializationInfo info, StreamingContext context)
  173. {
  174. if (info == null)
  175. {
  176. throw new ArgumentNullException(nameof(info));
  177. }
  178. int persistedCapacity = 0;
  179. string persistedString = null;
  180. int persistedMaxCapacity = int.MaxValue;
  181. bool capacityPresent = false;
  182. // Get the data
  183. SerializationInfoEnumerator enumerator = info.GetEnumerator();
  184. while (enumerator.MoveNext())
  185. {
  186. switch (enumerator.Name)
  187. {
  188. case MaxCapacityField:
  189. persistedMaxCapacity = info.GetInt32(MaxCapacityField);
  190. break;
  191. case StringValueField:
  192. persistedString = info.GetString(StringValueField);
  193. break;
  194. case CapacityField:
  195. persistedCapacity = info.GetInt32(CapacityField);
  196. capacityPresent = true;
  197. break;
  198. default:
  199. // Ignore other fields for forwards-compatibility.
  200. break;
  201. }
  202. }
  203. // Check values and set defaults
  204. if (persistedString == null)
  205. {
  206. persistedString = string.Empty;
  207. }
  208. if (persistedMaxCapacity < 1 || persistedString.Length > persistedMaxCapacity)
  209. {
  210. throw new SerializationException(SR.Serialization_StringBuilderMaxCapacity);
  211. }
  212. if (!capacityPresent)
  213. {
  214. // StringBuilder in V1.X did not persist the Capacity, so this is a valid legacy code path.
  215. persistedCapacity = Math.Min(Math.Max(DefaultCapacity, persistedString.Length), persistedMaxCapacity);
  216. }
  217. if (persistedCapacity < 0 || persistedCapacity < persistedString.Length || persistedCapacity > persistedMaxCapacity)
  218. {
  219. throw new SerializationException(SR.Serialization_StringBuilderCapacity);
  220. }
  221. // Assign
  222. m_MaxCapacity = persistedMaxCapacity;
  223. m_ChunkChars = new char[persistedCapacity];
  224. persistedString.CopyTo(0, m_ChunkChars, 0, persistedString.Length);
  225. m_ChunkLength = persistedString.Length;
  226. m_ChunkPrevious = null;
  227. AssertInvariants();
  228. }
  229. void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
  230. {
  231. if (info == null)
  232. {
  233. throw new ArgumentNullException(nameof(info));
  234. }
  235. AssertInvariants();
  236. info.AddValue(MaxCapacityField, m_MaxCapacity);
  237. info.AddValue(CapacityField, Capacity);
  238. info.AddValue(StringValueField, ToString());
  239. // Note: persist "m_currentThread" to be compatible with old versions
  240. info.AddValue(ThreadIDField, 0);
  241. }
  242. [System.Diagnostics.Conditional("DEBUG")]
  243. private void AssertInvariants()
  244. {
  245. Debug.Assert(m_ChunkOffset + m_ChunkChars.Length >= m_ChunkOffset, "The length of the string is greater than int.MaxValue.");
  246. StringBuilder currentBlock = this;
  247. int maxCapacity = this.m_MaxCapacity;
  248. for (;;)
  249. {
  250. // All blocks have the same max capacity.
  251. Debug.Assert(currentBlock.m_MaxCapacity == maxCapacity);
  252. Debug.Assert(currentBlock.m_ChunkChars != null);
  253. Debug.Assert(currentBlock.m_ChunkLength <= currentBlock.m_ChunkChars.Length);
  254. Debug.Assert(currentBlock.m_ChunkLength >= 0);
  255. Debug.Assert(currentBlock.m_ChunkOffset >= 0);
  256. StringBuilder prevBlock = currentBlock.m_ChunkPrevious;
  257. if (prevBlock == null)
  258. {
  259. Debug.Assert(currentBlock.m_ChunkOffset == 0);
  260. break;
  261. }
  262. // There are no gaps in the blocks.
  263. Debug.Assert(currentBlock.m_ChunkOffset == prevBlock.m_ChunkOffset + prevBlock.m_ChunkLength);
  264. currentBlock = prevBlock;
  265. }
  266. }
  267. public int Capacity
  268. {
  269. get { return m_ChunkChars.Length + m_ChunkOffset; }
  270. set
  271. {
  272. if (value < 0)
  273. {
  274. throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NegativeCapacity);
  275. }
  276. if (value > MaxCapacity)
  277. {
  278. throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_Capacity);
  279. }
  280. if (value < Length)
  281. {
  282. throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity);
  283. }
  284. if (Capacity != value)
  285. {
  286. int newLen = value - m_ChunkOffset;
  287. char[] newArray = new char[newLen];
  288. Array.Copy(m_ChunkChars, 0, newArray, 0, m_ChunkLength);
  289. m_ChunkChars = newArray;
  290. }
  291. }
  292. }
  293. /// <summary>
  294. /// Gets the maximum capacity this builder is allowed to have.
  295. /// </summary>
  296. public int MaxCapacity => m_MaxCapacity;
  297. /// <summary>
  298. /// Ensures that the capacity of this builder is at least the specified value.
  299. /// </summary>
  300. /// <param name="capacity">The new capacity for this builder.</param>
  301. /// <remarks>
  302. /// If <paramref name="capacity"/> is less than or equal to the current capacity of
  303. /// this builder, the capacity remains unchanged.
  304. /// </remarks>
  305. public int EnsureCapacity(int capacity)
  306. {
  307. if (capacity < 0)
  308. {
  309. throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NegativeCapacity);
  310. }
  311. if (Capacity < capacity)
  312. Capacity = capacity;
  313. return Capacity;
  314. }
  315. public override string ToString()
  316. {
  317. AssertInvariants();
  318. if (Length == 0)
  319. {
  320. return string.Empty;
  321. }
  322. string result = string.FastAllocateString(Length);
  323. StringBuilder chunk = this;
  324. unsafe
  325. {
  326. fixed (char* destinationPtr = result)
  327. {
  328. do
  329. {
  330. if (chunk.m_ChunkLength > 0)
  331. {
  332. // Copy these into local variables so that they are stable even in the presence of race conditions
  333. char[] sourceArray = chunk.m_ChunkChars;
  334. int chunkOffset = chunk.m_ChunkOffset;
  335. int chunkLength = chunk.m_ChunkLength;
  336. // Check that we will not overrun our boundaries.
  337. if ((uint)(chunkLength + chunkOffset) <= (uint)result.Length && (uint)chunkLength <= (uint)sourceArray.Length)
  338. {
  339. fixed (char* sourcePtr = &sourceArray[0])
  340. string.wstrcpy(destinationPtr + chunkOffset, sourcePtr, chunkLength);
  341. }
  342. else
  343. {
  344. throw new ArgumentOutOfRangeException(nameof(chunkLength), SR.ArgumentOutOfRange_Index);
  345. }
  346. }
  347. chunk = chunk.m_ChunkPrevious;
  348. }
  349. while (chunk != null);
  350. return result;
  351. }
  352. }
  353. }
  354. /// <summary>
  355. /// Creates a string from a substring of this builder.
  356. /// </summary>
  357. /// <param name="startIndex">The index to start in this builder.</param>
  358. /// <param name="length">The number of characters to read in this builder.</param>
  359. public string ToString(int startIndex, int length)
  360. {
  361. int currentLength = this.Length;
  362. if (startIndex < 0)
  363. {
  364. throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
  365. }
  366. if (startIndex > currentLength)
  367. {
  368. throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndexLargerThanLength);
  369. }
  370. if (length < 0)
  371. {
  372. throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
  373. }
  374. if (startIndex > currentLength - length)
  375. {
  376. throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexLength);
  377. }
  378. AssertInvariants();
  379. string result = string.FastAllocateString(length);
  380. unsafe
  381. {
  382. fixed (char* destinationPtr = result)
  383. {
  384. this.CopyTo(startIndex, new Span<char>(destinationPtr, length), length);
  385. return result;
  386. }
  387. }
  388. }
  389. public StringBuilder Clear()
  390. {
  391. this.Length = 0;
  392. return this;
  393. }
  394. /// <summary>
  395. /// Gets or sets the length of this builder.
  396. /// </summary>
  397. public int Length
  398. {
  399. get
  400. {
  401. return m_ChunkOffset + m_ChunkLength;
  402. }
  403. set
  404. {
  405. //If the new length is less than 0 or greater than our Maximum capacity, bail.
  406. if (value < 0)
  407. {
  408. throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NegativeLength);
  409. }
  410. if (value > MaxCapacity)
  411. {
  412. throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity);
  413. }
  414. if (value == 0 && m_ChunkPrevious == null)
  415. {
  416. m_ChunkLength = 0;
  417. m_ChunkOffset = 0;
  418. return;
  419. }
  420. int delta = value - Length;
  421. if (delta > 0)
  422. {
  423. // Pad ourselves with null characters.
  424. Append('\0', delta);
  425. }
  426. else
  427. {
  428. StringBuilder chunk = FindChunkForIndex(value);
  429. if (chunk != this)
  430. {
  431. // Avoid possible infinite capacity growth. See https://github.com/dotnet/coreclr/pull/16926
  432. int capacityToPreserve = Math.Min(Capacity, Math.Max(Length * 6 / 5, m_ChunkChars.Length));
  433. int newLen = capacityToPreserve - chunk.m_ChunkOffset;
  434. if (newLen > chunk.m_ChunkChars.Length)
  435. {
  436. // We crossed a chunk boundary when reducing the Length. We must replace this middle-chunk with a new larger chunk,
  437. // to ensure the capacity we want is preserved.
  438. char[] newArray = new char[newLen];
  439. Array.Copy(chunk.m_ChunkChars, 0, newArray, 0, chunk.m_ChunkLength);
  440. m_ChunkChars = newArray;
  441. }
  442. else
  443. {
  444. // Special case where the capacity we want to keep corresponds exactly to the size of the content.
  445. // Just take ownership of the array.
  446. Debug.Assert(newLen == chunk.m_ChunkChars.Length, "The new chunk should be larger or equal to the one it is replacing.");
  447. m_ChunkChars = chunk.m_ChunkChars;
  448. }
  449. m_ChunkPrevious = chunk.m_ChunkPrevious;
  450. m_ChunkOffset = chunk.m_ChunkOffset;
  451. }
  452. m_ChunkLength = value - chunk.m_ChunkOffset;
  453. AssertInvariants();
  454. }
  455. Debug.Assert(Length == value, "Something went wrong setting Length.");
  456. }
  457. }
  458. [IndexerName("Chars")]
  459. public char this[int index]
  460. {
  461. get
  462. {
  463. StringBuilder chunk = this;
  464. for (;;)
  465. {
  466. int indexInBlock = index - chunk.m_ChunkOffset;
  467. if (indexInBlock >= 0)
  468. {
  469. if (indexInBlock >= chunk.m_ChunkLength)
  470. {
  471. throw new IndexOutOfRangeException();
  472. }
  473. return chunk.m_ChunkChars[indexInBlock];
  474. }
  475. chunk = chunk.m_ChunkPrevious;
  476. if (chunk == null)
  477. {
  478. throw new IndexOutOfRangeException();
  479. }
  480. }
  481. }
  482. set
  483. {
  484. StringBuilder chunk = this;
  485. for (;;)
  486. {
  487. int indexInBlock = index - chunk.m_ChunkOffset;
  488. if (indexInBlock >= 0)
  489. {
  490. if (indexInBlock >= chunk.m_ChunkLength)
  491. {
  492. throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
  493. }
  494. chunk.m_ChunkChars[indexInBlock] = value;
  495. return;
  496. }
  497. chunk = chunk.m_ChunkPrevious;
  498. if (chunk == null)
  499. {
  500. throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
  501. }
  502. }
  503. }
  504. }
  505. /// <summary>
  506. /// GetChunks returns ChunkEnumerator that follows the IEnumerable pattern and
  507. /// thus can be used in a C# 'foreach' statements to retreive the data in the StringBuilder
  508. /// as chunks (ReadOnlyMemory) of characters. An example use is:
  509. ///
  510. /// foreach (ReadOnlyMemory&lt;char&gt; chunk in sb.GetChunks())
  511. /// foreach(char c in chunk.Span)
  512. /// { /* operation on c }
  513. ///
  514. /// It is undefined what happens if the StringBuilder is modified while the chunk
  515. /// enumeration is incomplete. StringBuilder is also not thread-safe, so operating
  516. /// on it with concurrent threads is illegal. Finally the ReadOnlyMemory chunks returned
  517. /// are NOT guarenteed to remain unchanged if the StringBuilder is modified, so do
  518. /// not cache them for later use either. This API's purpose is efficiently extracting
  519. /// the data of a CONSTANT StringBuilder.
  520. ///
  521. /// Creating a ReadOnlySpan from a ReadOnlyMemory (the .Span property) is expensive
  522. /// compared to the fetching of the character, so create a local variable for the SPAN
  523. /// if you need to use it in a nested for statement. For example
  524. ///
  525. /// foreach (ReadOnlyMemory&lt;char&gt; chunk in sb.GetChunks())
  526. /// {
  527. /// var span = chunk.Span;
  528. /// for(int i = 0; i &lt; span.Length; i++)
  529. /// { /* operation on span[i] */ }
  530. /// }
  531. /// </summary>
  532. public ChunkEnumerator GetChunks() => new ChunkEnumerator(this);
  533. /// <summary>
  534. /// ChunkEnumerator supports both the IEnumerable and IEnumerator pattern so foreach
  535. /// works (see GetChunks). It needs to be public (so the compiler can use it
  536. /// when building a foreach statement) but users typically don't use it explicitly.
  537. /// (which is why it is a nested type).
  538. /// </summary>
  539. public struct ChunkEnumerator
  540. {
  541. private readonly StringBuilder _firstChunk; // The first Stringbuilder chunk (which is the end of the logical string)
  542. private StringBuilder _currentChunk; // The chunk that this enumerator is currently returning (Current).
  543. private readonly ManyChunkInfo _manyChunks; // Only used for long string builders with many chunks (see constructor)
  544. /// <summary>
  545. /// Implement IEnumerable.GetEnumerator() to return 'this' as the IEnumerator
  546. /// </summary>
  547. [ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never)] // Only here to make foreach work
  548. public ChunkEnumerator GetEnumerator() { return this; }
  549. /// <summary>
  550. /// Implements the IEnumerator pattern.
  551. /// </summary>
  552. public bool MoveNext()
  553. {
  554. if (_currentChunk == _firstChunk)
  555. return false;
  556. if (_manyChunks != null)
  557. return _manyChunks.MoveNext(ref _currentChunk);
  558. StringBuilder next = _firstChunk;
  559. while (next.m_ChunkPrevious != _currentChunk)
  560. next = next.m_ChunkPrevious;
  561. _currentChunk = next;
  562. return true;
  563. }
  564. /// <summary>
  565. /// Implements the IEnumerator pattern.
  566. /// </summary>
  567. public ReadOnlyMemory<char> Current => new ReadOnlyMemory<char>(_currentChunk.m_ChunkChars, 0, _currentChunk.m_ChunkLength);
  568. #region private
  569. internal ChunkEnumerator(StringBuilder stringBuilder)
  570. {
  571. Debug.Assert(stringBuilder != null);
  572. _firstChunk = stringBuilder;
  573. _currentChunk = null; // MoveNext will find the last chunk if we do this.
  574. _manyChunks = null;
  575. // There is a performance-vs-allocation tradeoff. Because the chunks
  576. // are a linked list with each chunk pointing to its PREDECESSOR, walking
  577. // the list FORWARD is not efficient. If there are few chunks (< 8) we
  578. // simply scan from the start each time, and tolerate the N*N behavior.
  579. // However above this size, we allocate an array to hold pointers to all
  580. // the chunks and we can be efficient for large N.
  581. int chunkCount = ChunkCount(stringBuilder);
  582. if (8 < chunkCount)
  583. _manyChunks = new ManyChunkInfo(stringBuilder, chunkCount);
  584. }
  585. private static int ChunkCount(StringBuilder stringBuilder)
  586. {
  587. int ret = 0;
  588. while (stringBuilder != null)
  589. {
  590. ret++;
  591. stringBuilder = stringBuilder.m_ChunkPrevious;
  592. }
  593. return ret;
  594. }
  595. /// <summary>
  596. /// Used to hold all the chunks indexes when you have many chunks.
  597. /// </summary>
  598. private class ManyChunkInfo
  599. {
  600. private readonly StringBuilder[] _chunks; // These are in normal order (first chunk first)
  601. private int _chunkPos;
  602. public bool MoveNext(ref StringBuilder current)
  603. {
  604. int pos = ++_chunkPos;
  605. if (_chunks.Length <= pos)
  606. return false;
  607. current = _chunks[pos];
  608. return true;
  609. }
  610. public ManyChunkInfo(StringBuilder stringBuilder, int chunkCount)
  611. {
  612. _chunks = new StringBuilder[chunkCount];
  613. while (0 <= --chunkCount)
  614. {
  615. Debug.Assert(stringBuilder != null);
  616. _chunks[chunkCount] = stringBuilder;
  617. stringBuilder = stringBuilder.m_ChunkPrevious;
  618. }
  619. _chunkPos = -1;
  620. }
  621. }
  622. #endregion
  623. }
  624. /// <summary>
  625. /// Appends a character 0 or more times to the end of this builder.
  626. /// </summary>
  627. /// <param name="value">The character to append.</param>
  628. /// <param name="repeatCount">The number of times to append <paramref name="value"/>.</param>
  629. public StringBuilder Append(char value, int repeatCount)
  630. {
  631. if (repeatCount < 0)
  632. {
  633. throw new ArgumentOutOfRangeException(nameof(repeatCount), SR.ArgumentOutOfRange_NegativeCount);
  634. }
  635. if (repeatCount == 0)
  636. {
  637. return this;
  638. }
  639. // this is where we can check if the repeatCount will put us over m_MaxCapacity
  640. // We are doing the check here to prevent the corruption of the StringBuilder.
  641. int newLength = Length + repeatCount;
  642. if (newLength > m_MaxCapacity || newLength < repeatCount)
  643. {
  644. throw new ArgumentOutOfRangeException(nameof(repeatCount), SR.ArgumentOutOfRange_LengthGreaterThanCapacity);
  645. }
  646. int index = m_ChunkLength;
  647. while (repeatCount > 0)
  648. {
  649. if (index < m_ChunkChars.Length)
  650. {
  651. m_ChunkChars[index++] = value;
  652. --repeatCount;
  653. }
  654. else
  655. {
  656. m_ChunkLength = index;
  657. ExpandByABlock(repeatCount);
  658. Debug.Assert(m_ChunkLength == 0);
  659. index = 0;
  660. }
  661. }
  662. m_ChunkLength = index;
  663. AssertInvariants();
  664. return this;
  665. }
  666. /// <summary>
  667. /// Appends a range of characters to the end of this builder.
  668. /// </summary>
  669. /// <param name="value">The characters to append.</param>
  670. /// <param name="startIndex">The index to start in <paramref name="value"/>.</param>
  671. /// <param name="charCount">The number of characters to read in <paramref name="value"/>.</param>
  672. public StringBuilder Append(char[] value, int startIndex, int charCount)
  673. {
  674. if (startIndex < 0)
  675. {
  676. throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_GenericPositive);
  677. }
  678. if (charCount < 0)
  679. {
  680. throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GenericPositive);
  681. }
  682. if (value == null)
  683. {
  684. if (startIndex == 0 && charCount == 0)
  685. {
  686. return this;
  687. }
  688. throw new ArgumentNullException(nameof(value));
  689. }
  690. if (charCount > value.Length - startIndex)
  691. {
  692. throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_Index);
  693. }
  694. if (charCount == 0)
  695. {
  696. return this;
  697. }
  698. unsafe
  699. {
  700. fixed (char* valueChars = &value[startIndex])
  701. {
  702. Append(valueChars, charCount);
  703. return this;
  704. }
  705. }
  706. }
  707. /// <summary>
  708. /// Appends a string to the end of this builder.
  709. /// </summary>
  710. /// <param name="value">The string to append.</param>
  711. public StringBuilder Append(string value)
  712. {
  713. if (value != null)
  714. {
  715. // We could have just called AppendHelper here; this is a hand-specialization of that code.
  716. char[] chunkChars = m_ChunkChars;
  717. int chunkLength = m_ChunkLength;
  718. int valueLen = value.Length;
  719. int newCurrentIndex = chunkLength + valueLen;
  720. if (newCurrentIndex < chunkChars.Length) // Use strictly < to avoid issues if count == 0, newIndex == length
  721. {
  722. if (valueLen <= 2)
  723. {
  724. if (valueLen > 0)
  725. chunkChars[chunkLength] = value[0];
  726. if (valueLen > 1)
  727. chunkChars[chunkLength + 1] = value[1];
  728. }
  729. else
  730. {
  731. unsafe
  732. {
  733. fixed (char* valuePtr = value)
  734. fixed (char* destPtr = &chunkChars[chunkLength])
  735. {
  736. string.wstrcpy(destPtr, valuePtr, valueLen);
  737. }
  738. }
  739. }
  740. m_ChunkLength = newCurrentIndex;
  741. }
  742. else
  743. {
  744. AppendHelper(value);
  745. }
  746. }
  747. return this;
  748. }
  749. // We put this fixed in its own helper to avoid the cost of zero-initing `valueChars` in the
  750. // case we don't actually use it.
  751. private void AppendHelper(string value)
  752. {
  753. unsafe
  754. {
  755. fixed (char* valueChars = value)
  756. {
  757. Append(valueChars, value.Length);
  758. }
  759. }
  760. }
  761. /// <summary>
  762. /// Appends part of a string to the end of this builder.
  763. /// </summary>
  764. /// <param name="value">The string to append.</param>
  765. /// <param name="startIndex">The index to start in <paramref name="value"/>.</param>
  766. /// <param name="count">The number of characters to read in <paramref name="value"/>.</param>
  767. public StringBuilder Append(string value, int startIndex, int count)
  768. {
  769. if (startIndex < 0)
  770. {
  771. throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
  772. }
  773. if (count < 0)
  774. {
  775. throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_GenericPositive);
  776. }
  777. if (value == null)
  778. {
  779. if (startIndex == 0 && count == 0)
  780. {
  781. return this;
  782. }
  783. throw new ArgumentNullException(nameof(value));
  784. }
  785. if (count == 0)
  786. {
  787. return this;
  788. }
  789. if (startIndex > value.Length - count)
  790. {
  791. throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
  792. }
  793. unsafe
  794. {
  795. fixed (char* valueChars = value)
  796. {
  797. Append(valueChars + startIndex, count);
  798. return this;
  799. }
  800. }
  801. }
  802. public StringBuilder Append(StringBuilder value)
  803. {
  804. if (value != null && value.Length != 0)
  805. {
  806. return AppendCore(value, 0, value.Length);
  807. }
  808. return this;
  809. }
  810. public StringBuilder Append(StringBuilder value, int startIndex, int count)
  811. {
  812. if (startIndex < 0)
  813. {
  814. throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
  815. }
  816. if (count < 0)
  817. {
  818. throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_GenericPositive);
  819. }
  820. if (value == null)
  821. {
  822. if (startIndex == 0 && count == 0)
  823. {
  824. return this;
  825. }
  826. throw new ArgumentNullException(nameof(value));
  827. }
  828. if (count == 0)
  829. {
  830. return this;
  831. }
  832. if (count > value.Length - startIndex)
  833. {
  834. throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
  835. }
  836. return AppendCore(value, startIndex, count);
  837. }
  838. private StringBuilder AppendCore(StringBuilder value, int startIndex, int count)
  839. {
  840. if (value == this)
  841. return Append(value.ToString(startIndex, count));
  842. int newLength = Length + count;
  843. if ((uint)newLength > (uint)m_MaxCapacity)
  844. {
  845. throw new ArgumentOutOfRangeException(nameof(Capacity), SR.ArgumentOutOfRange_Capacity);
  846. }
  847. while (count > 0)
  848. {
  849. int length = Math.Min(m_ChunkChars.Length - m_ChunkLength, count);
  850. if (length == 0)
  851. {
  852. ExpandByABlock(count);
  853. length = Math.Min(m_ChunkChars.Length - m_ChunkLength, count);
  854. }
  855. value.CopyTo(startIndex, new Span<char>(m_ChunkChars, m_ChunkLength, length), length);
  856. m_ChunkLength += length;
  857. startIndex += length;
  858. count -= length;
  859. }
  860. return this;
  861. }
  862. public StringBuilder AppendLine() => Append(Environment.NewLine);
  863. public StringBuilder AppendLine(string value)
  864. {
  865. Append(value);
  866. return Append(Environment.NewLine);
  867. }
  868. public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
  869. {
  870. if (destination == null)
  871. {
  872. throw new ArgumentNullException(nameof(destination));
  873. }
  874. if (destinationIndex < 0)
  875. {
  876. throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.Format(SR.ArgumentOutOfRange_MustBeNonNegNum, nameof(destinationIndex)));
  877. }
  878. if (destinationIndex > destination.Length - count)
  879. {
  880. throw new ArgumentException(SR.ArgumentOutOfRange_OffsetOut);
  881. }
  882. CopyTo(sourceIndex, new Span<char>(destination).Slice(destinationIndex), count);
  883. }
  884. public void CopyTo(int sourceIndex, Span<char> destination, int count)
  885. {
  886. if (count < 0)
  887. {
  888. throw new ArgumentOutOfRangeException(nameof(count), SR.Arg_NegativeArgCount);
  889. }
  890. if ((uint)sourceIndex > (uint)Length)
  891. {
  892. throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_Index);
  893. }
  894. if (sourceIndex > Length - count)
  895. {
  896. throw new ArgumentException(SR.Arg_LongerThanSrcString);
  897. }
  898. AssertInvariants();
  899. StringBuilder chunk = this;
  900. int sourceEndIndex = sourceIndex + count;
  901. int curDestIndex = count;
  902. while (count > 0)
  903. {
  904. int chunkEndIndex = sourceEndIndex - chunk.m_ChunkOffset;
  905. if (chunkEndIndex >= 0)
  906. {
  907. chunkEndIndex = Math.Min(chunkEndIndex, chunk.m_ChunkLength);
  908. int chunkCount = count;
  909. int chunkStartIndex = chunkEndIndex - count;
  910. if (chunkStartIndex < 0)
  911. {
  912. chunkCount += chunkStartIndex;
  913. chunkStartIndex = 0;
  914. }
  915. curDestIndex -= chunkCount;
  916. count -= chunkCount;
  917. // We ensure that chunkStartIndex + chunkCount are within range of m_chunkChars as well as
  918. // ensuring that curDestIndex + chunkCount are within range of destination
  919. ThreadSafeCopy(chunk.m_ChunkChars, chunkStartIndex, destination, curDestIndex, chunkCount);
  920. }
  921. chunk = chunk.m_ChunkPrevious;
  922. }
  923. }
  924. /// <summary>
  925. /// Inserts a string 0 or more times into this builder at the specified position.
  926. /// </summary>
  927. /// <param name="index">The index to insert in this builder.</param>
  928. /// <param name="value">The string to insert.</param>
  929. /// <param name="count">The number of times to insert the string.</param>
  930. public StringBuilder Insert(int index, string value, int count)
  931. {
  932. if (count < 0)
  933. {
  934. throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
  935. }
  936. int currentLength = Length;
  937. if ((uint)index > (uint)currentLength)
  938. {
  939. throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
  940. }
  941. if (string.IsNullOrEmpty(value) || count == 0)
  942. {
  943. return this;
  944. }
  945. // Ensure we don't insert more chars than we can hold, and we don't
  946. // have any integer overflow in our new length.
  947. long insertingChars = (long)value.Length * count;
  948. if (insertingChars > MaxCapacity - this.Length)
  949. {
  950. throw new OutOfMemoryException();
  951. }
  952. Debug.Assert(insertingChars + this.Length < int.MaxValue);
  953. StringBuilder chunk;
  954. int indexInChunk;
  955. MakeRoom(index, (int)insertingChars, out chunk, out indexInChunk, false);
  956. unsafe
  957. {
  958. fixed (char* valuePtr = value)
  959. {
  960. while (count > 0)
  961. {
  962. ReplaceInPlaceAtChunk(ref chunk, ref indexInChunk, valuePtr, value.Length);
  963. --count;
  964. }
  965. return this;
  966. }
  967. }
  968. }
  969. /// <summary>
  970. /// Removes a range of characters from this builder.
  971. /// </summary>
  972. /// <remarks>
  973. /// This method does not reduce the capacity of this builder.
  974. /// </remarks>
  975. public StringBuilder Remove(int startIndex, int length)
  976. {
  977. if (length < 0)
  978. {
  979. throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
  980. }
  981. if (startIndex < 0)
  982. {
  983. throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
  984. }
  985. if (length > Length - startIndex)
  986. {
  987. throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index);
  988. }
  989. if (Length == length && startIndex == 0)
  990. {
  991. Length = 0;
  992. return this;
  993. }
  994. if (length > 0)
  995. {
  996. StringBuilder chunk;
  997. int indexInChunk;
  998. Remove(startIndex, length, out chunk, out indexInChunk);
  999. }
  1000. return this;
  1001. }
  1002. public StringBuilder Append(bool value) => Append(value.ToString());
  1003. public StringBuilder Append(char value)
  1004. {
  1005. if (m_ChunkLength < m_ChunkChars.Length)
  1006. {
  1007. m_ChunkChars[m_ChunkLength++] = value;
  1008. }
  1009. else
  1010. {
  1011. Append(value, 1);
  1012. }
  1013. return this;
  1014. }
  1015. [CLSCompliant(false)]
  1016. public StringBuilder Append(sbyte value) => AppendSpanFormattable(value);
  1017. public StringBuilder Append(byte value) => AppendSpanFormattable(value);
  1018. public StringBuilder Append(short value) => AppendSpanFormattable(value);
  1019. public StringBuilder Append(int value) => AppendSpanFormattable(value);
  1020. public StringBuilder Append(long value) => AppendSpanFormattable(value);
  1021. public StringBuilder Append(float value) => AppendSpanFormattable(value);
  1022. public StringBuilder Append(double value) => AppendSpanFormattable(value);
  1023. public StringBuilder Append(decimal value) => AppendSpanFormattable(value);
  1024. [CLSCompliant(false)]
  1025. public StringBuilder Append(ushort value) => AppendSpanFormattable(value);
  1026. [CLSCompliant(false)]
  1027. public StringBuilder Append(uint value) => AppendSpanFormattable(value);
  1028. [CLSCompliant(false)]
  1029. public StringBuilder Append(ulong value) => AppendSpanFormattable(value);
  1030. private StringBuilder AppendSpanFormattable<T>(T value) where T : ISpanFormattable
  1031. {
  1032. if (value.TryFormat(RemainingCurrentChunk, out int charsWritten, format: default, provider: null))
  1033. {
  1034. m_ChunkLength += charsWritten;
  1035. return this;
  1036. }
  1037. return Append(value.ToString());
  1038. }
  1039. internal StringBuilder AppendSpanFormattable<T>(T value, string format, IFormatProvider provider) where T : ISpanFormattable, IFormattable
  1040. {
  1041. if (value.TryFormat(RemainingCurrentChunk, out int charsWritten, format, provider))
  1042. {
  1043. m_ChunkLength += charsWritten;
  1044. return this;
  1045. }
  1046. return Append(value.ToString(format, provider));
  1047. }
  1048. public StringBuilder Append(object value) => (value == null) ? this : Append(value.ToString());
  1049. public StringBuilder Append(char[] value)
  1050. {
  1051. if (value?.Length > 0)
  1052. {
  1053. unsafe
  1054. {
  1055. fixed (char* valueChars = &value[0])
  1056. {
  1057. Append(valueChars, value.Length);
  1058. }
  1059. }
  1060. }
  1061. return this;
  1062. }
  1063. public StringBuilder Append(ReadOnlySpan<char> value)
  1064. {
  1065. if (value.Length > 0)
  1066. {
  1067. unsafe
  1068. {
  1069. fixed (char* valueChars = &MemoryMarshal.GetReference(value))
  1070. {
  1071. Append(valueChars, value.Length);
  1072. }
  1073. }
  1074. }
  1075. return this;
  1076. }
  1077. public StringBuilder Append(ReadOnlyMemory<char> value) => Append(value.Span);
  1078. #region AppendJoin
  1079. public unsafe StringBuilder AppendJoin(string separator, params object[] values)
  1080. {
  1081. separator = separator ?? string.Empty;
  1082. fixed (char* pSeparator = separator)
  1083. {
  1084. return AppendJoinCore(pSeparator, separator.Length, values);
  1085. }
  1086. }
  1087. public unsafe StringBuilder AppendJoin<T>(string separator, IEnumerable<T> values)
  1088. {
  1089. separator = separator ?? string.Empty;
  1090. fixed (char* pSeparator = separator)
  1091. {
  1092. return AppendJoinCore(pSeparator, separator.Length, values);
  1093. }
  1094. }
  1095. public unsafe StringBuilder AppendJoin(string separator, params string[] values)
  1096. {
  1097. separator = separator ?? string.Empty;
  1098. fixed (char* pSeparator = separator)
  1099. {
  1100. return AppendJoinCore(pSeparator, separator.Length, values);
  1101. }
  1102. }
  1103. public unsafe StringBuilder AppendJoin(char separator, params object[] values)
  1104. {
  1105. return AppendJoinCore(&separator, 1, values);
  1106. }
  1107. public unsafe StringBuilder AppendJoin<T>(char separator, IEnumerable<T> values)
  1108. {
  1109. return AppendJoinCore(&separator, 1, values);
  1110. }
  1111. public unsafe StringBuilder AppendJoin(char separator, params string[] values)
  1112. {
  1113. return AppendJoinCore(&separator, 1, values);
  1114. }
  1115. private unsafe StringBuilder AppendJoinCore<T>(char* separator, int separatorLength, IEnumerable<T> values)
  1116. {
  1117. Debug.Assert(separator != null);
  1118. Debug.Assert(separatorLength >= 0);
  1119. if (values == null)
  1120. {
  1121. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values);
  1122. }
  1123. using (IEnumerator<T> en = values.GetEnumerator())
  1124. {
  1125. if (!en.MoveNext())
  1126. {
  1127. return this;
  1128. }
  1129. var value = en.Current;
  1130. if (value != null)
  1131. {
  1132. Append(value.ToString());
  1133. }
  1134. while (en.MoveNext())
  1135. {
  1136. Append(separator, separatorLength);
  1137. value = en.Current;
  1138. if (value != null)
  1139. {
  1140. Append(value.ToString());
  1141. }
  1142. }
  1143. }
  1144. return this;
  1145. }
  1146. private unsafe StringBuilder AppendJoinCore<T>(char* separator, int separatorLength, T[] values)
  1147. {
  1148. if (values == null)
  1149. {
  1150. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values);
  1151. }
  1152. if (values.Length == 0)
  1153. {
  1154. return this;
  1155. }
  1156. if (values[0] != null)
  1157. {
  1158. Append(values[0].ToString());
  1159. }
  1160. for (int i = 1; i < values.Length; i++)
  1161. {
  1162. Append(separator, separatorLength);
  1163. if (values[i] != null)
  1164. {
  1165. Append(values[i].ToString());
  1166. }
  1167. }
  1168. return this;
  1169. }
  1170. #endregion
  1171. public StringBuilder Insert(int index, string value)
  1172. {
  1173. if ((uint)index > (uint)Length)
  1174. {
  1175. throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
  1176. }
  1177. if (value != null)
  1178. {
  1179. unsafe
  1180. {
  1181. fixed (char* sourcePtr = value)
  1182. Insert(index, sourcePtr, value.Length);
  1183. }
  1184. }
  1185. return this;
  1186. }
  1187. public StringBuilder Insert(int index, bool value) => Insert(index, value.ToString(), 1);
  1188. [CLSCompliant(false)]
  1189. public StringBuilder Insert(int index, sbyte value) => Insert(index, value.ToString(), 1);
  1190. public StringBuilder Insert(int index, byte value) => Insert(index, value.ToString(), 1);
  1191. public StringBuilder Insert(int index, short value) => Insert(index, value.ToString(), 1);
  1192. public StringBuilder Insert(int index, char value)
  1193. {
  1194. unsafe
  1195. {
  1196. Insert(index, &value, 1);
  1197. }
  1198. return this;
  1199. }
  1200. public StringBuilder Insert(int index, char[] value)
  1201. {
  1202. if ((uint)index > (uint)Length)
  1203. {
  1204. throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
  1205. }
  1206. if (value != null)
  1207. Insert(index, value, 0, value.Length);
  1208. return this;
  1209. }
  1210. public StringBuilder Insert(int index, char[] value, int startIndex, int charCount)
  1211. {
  1212. int currentLength = Length;
  1213. if ((uint)index > (uint)currentLength)
  1214. {
  1215. throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
  1216. }
  1217. if (value == null)
  1218. {
  1219. if (startIndex == 0 && charCount == 0)
  1220. {
  1221. return this;
  1222. }
  1223. throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String);
  1224. }
  1225. if (startIndex < 0)
  1226. {
  1227. throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
  1228. }
  1229. if (charCount < 0)
  1230. {
  1231. throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GenericPositive);
  1232. }
  1233. if (startIndex > value.Length - charCount)
  1234. {
  1235. throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
  1236. }
  1237. if (charCount > 0)
  1238. {
  1239. unsafe
  1240. {
  1241. fixed (char* sourcePtr = &value[startIndex])
  1242. Insert(index, sourcePtr, charCount);
  1243. }
  1244. }
  1245. return this;
  1246. }
  1247. public StringBuilder Insert(int index, int value) => Insert(index, value.ToString(), 1);
  1248. public StringBuilder Insert(int index, long value) => Insert(index, value.ToString(), 1);
  1249. public StringBuilder Insert(int index, float value) => Insert(index, value.ToString(), 1);
  1250. public StringBuilder Insert(int index, double value) => Insert(index, value.ToString(), 1);
  1251. public StringBuilder Insert(int index, decimal value) => Insert(index, value.ToString(), 1);
  1252. [CLSCompliant(false)]
  1253. public StringBuilder Insert(int index, ushort value) => Insert(index, value.ToString(), 1);
  1254. [CLSCompliant(false)]
  1255. public StringBuilder Insert(int index, uint value) => Insert(index, value.ToString(), 1);
  1256. [CLSCompliant(false)]
  1257. public StringBuilder Insert(int index, ulong value) => Insert(index, value.ToString(), 1);
  1258. public StringBuilder Insert(int index, object value) => (value == null) ? this : Insert(index, value.ToString(), 1);
  1259. public StringBuilder Insert(int index, ReadOnlySpan<char> value)
  1260. {
  1261. if ((uint)index > (uint)Length)
  1262. {
  1263. throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
  1264. }
  1265. if (value.Length > 0)
  1266. {
  1267. unsafe
  1268. {
  1269. fixed (char* sourcePtr = &MemoryMarshal.GetReference(value))
  1270. Insert(index, sourcePtr, value.Length);
  1271. }
  1272. }
  1273. return this;
  1274. }
  1275. public StringBuilder AppendFormat(string format, object arg0) => AppendFormatHelper(null, format, new ParamsArray(arg0));
  1276. public StringBuilder AppendFormat(string format, object arg0, object arg1) => AppendFormatHelper(null, format, new ParamsArray(arg0, arg1));
  1277. public StringBuilder AppendFormat(string format, object arg0, object arg1, object arg2) => AppendFormatHelper(null, format, new ParamsArray(arg0, arg1, arg2));
  1278. public StringBuilder AppendFormat(string format, params object[] args)
  1279. {
  1280. if (args == null)
  1281. {
  1282. // To preserve the original exception behavior, throw an exception about format if both
  1283. // args and format are null. The actual null check for format is in AppendFormatHelper.
  1284. string paramName = (format == null) ? nameof(format) : nameof(args);
  1285. throw new ArgumentNullException(paramName);
  1286. }
  1287. return AppendFormatHelper(null, format, new ParamsArray(args));
  1288. }
  1289. public StringBuilder AppendFormat(IFormatProvider provider, string format, object arg0) => AppendFormatHelper(provider, format, new ParamsArray(arg0));
  1290. public StringBuilder AppendFormat(IFormatProvider provider, string format, object arg0, object arg1) => AppendFormatHelper(provider, format, new ParamsArray(arg0, arg1));
  1291. public StringBuilder AppendFormat(IFormatProvider provider, string format, object arg0, object arg1, object arg2) => AppendFormatHelper(provider, format, new ParamsArray(arg0, arg1, arg2));
  1292. public StringBuilder AppendFormat(IFormatProvider provider, string format, params object[] args)
  1293. {
  1294. if (args == null)
  1295. {
  1296. // To preserve the original exception behavior, throw an exception about format if both
  1297. // args and format are null. The actual null check for format is in AppendFormatHelper.
  1298. string paramName = (format == null) ? nameof(format) : nameof(args);
  1299. throw new ArgumentNullException(paramName);
  1300. }
  1301. return AppendFormatHelper(provider, format, new ParamsArray(args));
  1302. }
  1303. private static void FormatError()
  1304. {
  1305. throw new FormatException(SR.Format_InvalidString);
  1306. }
  1307. // Undocumented exclusive limits on the range for Argument Hole Index and Argument Hole Alignment.
  1308. private const int IndexLimit = 1000000; // Note: 0 <= ArgIndex < IndexLimit
  1309. private const int WidthLimit = 1000000; // Note: -WidthLimit < ArgAlign < WidthLimit
  1310. internal StringBuilder AppendFormatHelper(IFormatProvider provider, string format, ParamsArray args)
  1311. {
  1312. if (format == null)
  1313. {
  1314. throw new ArgumentNullException(nameof(format));
  1315. }
  1316. int pos = 0;
  1317. int len = format.Length;
  1318. char ch = '\x0';
  1319. StringBuilder unescapedItemFormat = null;
  1320. ICustomFormatter cf = null;
  1321. if (provider != null)
  1322. {
  1323. cf = (ICustomFormatter)provider.GetFormat(typeof(ICustomFormatter));
  1324. }
  1325. while (true)
  1326. {
  1327. while (pos < len)
  1328. {
  1329. ch = format[pos];
  1330. pos++;
  1331. // Is it a closing brace?
  1332. if (ch == '}')
  1333. {
  1334. // Check next character (if there is one) to see if it is escaped. eg }}
  1335. if (pos < len && format[pos] == '}')
  1336. pos++;
  1337. else
  1338. // Otherwise treat it as an error (Mismatched closing brace)
  1339. FormatError();
  1340. }
  1341. // Is it a opening brace?
  1342. if (ch == '{')
  1343. {
  1344. // Check next character (if there is one) to see if it is escaped. eg {{
  1345. if (pos < len && format[pos] == '{')
  1346. pos++;
  1347. else
  1348. {
  1349. // Otherwise treat it as the opening brace of an Argument Hole.
  1350. pos--;
  1351. break;
  1352. }
  1353. }
  1354. // If it neither then treat the character as just text.
  1355. Append(ch);
  1356. }
  1357. //
  1358. // Start of parsing of Argument Hole.
  1359. // Argument Hole ::= { Index (, WS* Alignment WS*)? (: Formatting)? }
  1360. //
  1361. if (pos == len) break;
  1362. //
  1363. // Start of parsing required Index parameter.
  1364. // Index ::= ('0'-'9')+ WS*
  1365. //
  1366. pos++;
  1367. // If reached end of text then error (Unexpected end of text)
  1368. // or character is not a digit then error (Unexpected Character)
  1369. if (pos == len || (ch = format[pos]) < '0' || ch > '9') FormatError();
  1370. int index = 0;
  1371. do
  1372. {
  1373. index = index * 10 + ch - '0';
  1374. pos++;
  1375. // If reached end of text then error (Unexpected end of text)
  1376. if (pos == len) FormatError();
  1377. ch = format[pos];
  1378. // so long as character is digit and value of the index is less than 1000000 ( index limit )
  1379. }
  1380. while (ch >= '0' && ch <= '9' && index < IndexLimit);
  1381. // If value of index is not within the range of the arguments passed in then error (Index out of range)
  1382. if (index >= args.Length) throw new FormatException(SR.Format_IndexOutOfRange);
  1383. // Consume optional whitespace.
  1384. while (pos < len && (ch = format[pos]) == ' ') pos++;
  1385. // End of parsing index parameter.
  1386. //
  1387. // Start of parsing of optional Alignment
  1388. // Alignment ::= comma WS* minus? ('0'-'9')+ WS*
  1389. //
  1390. bool leftJustify = false;
  1391. int width = 0;
  1392. // Is the character a comma, which indicates the start of alignment parameter.
  1393. if (ch == ',')
  1394. {
  1395. pos++;
  1396. // Consume Optional whitespace
  1397. while (pos < len && format[pos] == ' ') pos++;
  1398. // If reached the end of the text then error (Unexpected end of text)
  1399. if (pos == len) FormatError();
  1400. // Is there a minus sign?
  1401. ch = format[pos];
  1402. if (ch == '-')
  1403. {
  1404. // Yes, then alignment is left justified.
  1405. leftJustify = true;
  1406. pos++;
  1407. // If reached end of text then error (Unexpected end of text)
  1408. if (pos == len) FormatError();
  1409. ch = format[pos];
  1410. }
  1411. // If current character is not a digit then error (Unexpected character)
  1412. if (ch < '0' || ch > '9') FormatError();
  1413. // Parse alignment digits.
  1414. do
  1415. {
  1416. width = width * 10 + ch - '0';
  1417. pos++;
  1418. // If reached end of text then error. (Unexpected end of text)
  1419. if (pos == len) FormatError();
  1420. ch = format[pos];
  1421. // So long a current character is a digit and the value of width is less than 100000 ( width limit )
  1422. }
  1423. while (ch >= '0' && ch <= '9' && width < WidthLimit);
  1424. // end of parsing Argument Alignment
  1425. }
  1426. // Consume optional whitespace
  1427. while (pos < len && (ch = format[pos]) == ' ') pos++;
  1428. //
  1429. // Start of parsing of optional formatting parameter.
  1430. //
  1431. object arg = args[index];
  1432. string itemFormat = null;
  1433. ReadOnlySpan<char> itemFormatSpan = default; // used if itemFormat is null
  1434. // Is current character a colon? which indicates start of formatting parameter.
  1435. if (ch == ':')
  1436. {
  1437. pos++;
  1438. int startPos = pos;
  1439. while (true)
  1440. {
  1441. // If reached end of text then error. (Unexpected end of text)
  1442. if (pos == len) FormatError();
  1443. ch = format[pos];
  1444. pos++;
  1445. // Is character a opening or closing brace?
  1446. if (ch == '}' || ch == '{')
  1447. {
  1448. if (ch == '{')
  1449. {
  1450. // Yes, is next character also a opening brace, then treat as escaped. eg {{
  1451. if (pos < len && format[pos] == '{')
  1452. pos++;
  1453. else
  1454. // Error Argument Holes can not be nested.
  1455. FormatError();
  1456. }
  1457. else
  1458. {
  1459. // Yes, is next character also a closing brace, then treat as escaped. eg }}
  1460. if (pos < len && format[pos] == '}')
  1461. pos++;
  1462. else
  1463. {
  1464. // No, then treat it as the closing brace of an Arg Hole.
  1465. pos--;
  1466. break;
  1467. }
  1468. }
  1469. // Reaching here means the brace has been escaped
  1470. // so we need to build up the format string in segments
  1471. if (unescapedItemFormat == null)
  1472. {
  1473. unescapedItemFormat = new StringBuilder();
  1474. }
  1475. unescapedItemFormat.Append(format, startPos, pos - startPos - 1);
  1476. startPos = pos;
  1477. }
  1478. }
  1479. if (unescapedItemFormat == null || unescapedItemFormat.Length == 0)
  1480. {
  1481. if (startPos != pos)
  1482. {
  1483. // There was no brace escaping, extract the item format as a single string
  1484. itemFormatSpan = format.AsSpan(startPos, pos - startPos);
  1485. }
  1486. }
  1487. else
  1488. {
  1489. unescapedItemFormat.Append(format, startPos, pos - startPos);
  1490. itemFormatSpan = itemFormat = unescapedItemFormat.ToString();
  1491. unescapedItemFormat.Clear();
  1492. }
  1493. }
  1494. // If current character is not a closing brace then error. (Unexpected Character)
  1495. if (ch != '}') FormatError();
  1496. // Construct the output for this arg hole.
  1497. pos++;
  1498. string s = null;
  1499. if (cf != null)
  1500. {
  1501. if (itemFormatSpan.Length != 0 && itemFormat == null)
  1502. {
  1503. itemFormat = new string(itemFormatSpan);
  1504. }
  1505. s = cf.Format(itemFormat, arg, provider);
  1506. }
  1507. if (s == null)
  1508. {
  1509. // If arg is ISpanFormattable and the beginning doesn't need padding,
  1510. // try formatting it into the remaining current chunk.
  1511. if (arg is ISpanFormattable spanFormattableArg &&
  1512. (leftJustify || width == 0) &&
  1513. spanFormattableArg.TryFormat(RemainingCurrentChunk, out int charsWritten, itemFormatSpan, provider))
  1514. {
  1515. m_ChunkLength += charsWritten;
  1516. // Pad the end, if needed.
  1517. int padding = width - charsWritten;
  1518. if (leftJustify && padding > 0) Append(' ', padding);
  1519. // Continue to parse other characters.
  1520. continue;
  1521. }
  1522. // Otherwise, fallback to trying IFormattable or calling ToString.
  1523. if (arg is IFormattable formattableArg)
  1524. {
  1525. if (itemFormatSpan.Length != 0 && itemFormat == null)
  1526. {
  1527. itemFormat = new string(itemFormatSpan);
  1528. }
  1529. s = formattableArg.ToString(itemFormat, provider);
  1530. }
  1531. else if (arg != null)
  1532. {
  1533. s = arg.ToString();
  1534. }
  1535. }
  1536. // Append it to the final output of the Format String.
  1537. if (s == null) s = string.Empty;
  1538. int pad = width - s.Length;
  1539. if (!leftJustify && pad > 0) Append(' ', pad);
  1540. Append(s);
  1541. if (leftJustify && pad > 0) Append(' ', pad);
  1542. // Continue to parse other characters.
  1543. }
  1544. return this;
  1545. }
  1546. /// <summary>
  1547. /// Replaces all instances of one string with another in this builder.
  1548. /// </summary>
  1549. /// <param name="oldValue">The string to replace.</param>
  1550. /// <param name="newValue">The string to replace <paramref name="oldValue"/> with.</param>
  1551. /// <remarks>
  1552. /// If <paramref name="newValue"/> is <c>null</c>, instances of <paramref name="oldValue"/>
  1553. /// are removed from this builder.
  1554. /// </remarks>
  1555. public StringBuilder Replace(string oldValue, string newValue) => Replace(oldValue, newValue, 0, Length);
  1556. /// <summary>
  1557. /// Determines if the contents of this builder are equal to the contents of another builder.
  1558. /// </summary>
  1559. /// <param name="sb">The other builder.</param>
  1560. public bool Equals(StringBuilder sb)
  1561. {
  1562. if (sb == null)
  1563. return false;
  1564. if (Length != sb.Length)
  1565. return false;
  1566. if (sb == this)
  1567. return true;
  1568. StringBuilder thisChunk = this;
  1569. int thisChunkIndex = thisChunk.m_ChunkLength;
  1570. StringBuilder sbChunk = sb;
  1571. int sbChunkIndex = sbChunk.m_ChunkLength;
  1572. for (;;)
  1573. {
  1574. --thisChunkIndex;
  1575. --sbChunkIndex;
  1576. while (thisChunkIndex < 0)
  1577. {
  1578. thisChunk = thisChunk.m_ChunkPrevious;
  1579. if (thisChunk == null)
  1580. break;
  1581. thisChunkIndex = thisChunk.m_ChunkLength + thisChunkIndex;
  1582. }
  1583. while (sbChunkIndex < 0)
  1584. {
  1585. sbChunk = sbChunk.m_ChunkPrevious;
  1586. if (sbChunk == null)
  1587. break;
  1588. sbChunkIndex = sbChunk.m_ChunkLength + sbChunkIndex;
  1589. }
  1590. if (thisChunkIndex < 0)
  1591. return sbChunkIndex < 0;
  1592. if (sbChunkIndex < 0)
  1593. return false;
  1594. if (thisChunk.m_ChunkChars[thisChunkIndex] != sbChunk.m_ChunkChars[sbChunkIndex])
  1595. return false;
  1596. }
  1597. }
  1598. /// <summary>
  1599. /// Determines if the contents of this builder are equal to the contents of <see cref="ReadOnlySpan{Char}"/>.
  1600. /// </summary>
  1601. /// <param name="span">The <see cref="ReadOnlySpan{Char}"/>.</param>
  1602. public bool Equals(ReadOnlySpan<char> span)
  1603. {
  1604. if (span.Length != Length)
  1605. return false;
  1606. StringBuilder sbChunk = this;
  1607. int offset = 0;
  1608. do
  1609. {
  1610. int chunk_length = sbChunk.m_ChunkLength;
  1611. offset += chunk_length;
  1612. ReadOnlySpan<char> chunk = new ReadOnlySpan<char>(sbChunk.m_ChunkChars, 0, chunk_length);
  1613. if (!chunk.EqualsOrdinal(span.Slice(span.Length - offset, chunk_length)))
  1614. return false;
  1615. sbChunk = sbChunk.m_ChunkPrevious;
  1616. } while (sbChunk != null);
  1617. Debug.Assert(offset == Length);
  1618. return true;
  1619. }
  1620. /// <summary>
  1621. /// Replaces all instances of one string with another in part of this builder.
  1622. /// </summary>
  1623. /// <param name="oldValue">The string to replace.</param>
  1624. /// <param name="newValue">The string to replace <paramref name="oldValue"/> with.</param>
  1625. /// <param name="startIndex">The index to start in this builder.</param>
  1626. /// <param name="count">The number of characters to read in this builder.</param>
  1627. /// <remarks>
  1628. /// If <paramref name="newValue"/> is <c>null</c>, instances of <paramref name="oldValue"/>
  1629. /// are removed from this builder.
  1630. /// </remarks>
  1631. public StringBuilder Replace(string oldValue, string newValue, int startIndex, int count)
  1632. {
  1633. int currentLength = Length;
  1634. if ((uint)startIndex > (uint)currentLength)
  1635. {
  1636. throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
  1637. }
  1638. if (count < 0 || startIndex > currentLength - count)
  1639. {
  1640. throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Index);
  1641. }
  1642. if (oldValue == null)
  1643. {
  1644. throw new ArgumentNullException(nameof(oldValue));
  1645. }
  1646. if (oldValue.Length == 0)
  1647. {
  1648. throw new ArgumentException(SR.Argument_EmptyName, nameof(oldValue));
  1649. }
  1650. newValue = newValue ?? string.Empty;
  1651. int deltaLength = newValue.Length - oldValue.Length;
  1652. int[] replacements = null; // A list of replacement positions in a chunk to apply
  1653. int replacementsCount = 0;
  1654. // Find the chunk, indexInChunk for the starting point
  1655. StringBuilder chunk = FindChunkForIndex(startIndex);
  1656. int indexInChunk = startIndex - chunk.m_ChunkOffset;
  1657. while (count > 0)
  1658. {
  1659. // Look for a match in the chunk,indexInChunk pointer
  1660. if (StartsWith(chunk, indexInChunk, count, oldValue))
  1661. {
  1662. // Push it on the replacements array (with growth), we will do all replacements in a
  1663. // given chunk in one operation below (see ReplaceAllInChunk) so we don't have to slide
  1664. // many times.
  1665. if (replacements == null)
  1666. {
  1667. replacements = new int[5];
  1668. }
  1669. else if (replacementsCount >= replacements.Length)
  1670. {
  1671. Array.Resize(ref replacements, replacements.Length * 3 / 2 + 4); // Grow by ~1.5x, but more in the begining
  1672. }
  1673. replacements[replacementsCount++] = indexInChunk;
  1674. indexInChunk += oldValue.Length;
  1675. count -= oldValue.Length;
  1676. }
  1677. else
  1678. {
  1679. indexInChunk++;
  1680. --count;
  1681. }
  1682. if (indexInChunk >= chunk.m_ChunkLength || count == 0) // Have we moved out of the current chunk?
  1683. {
  1684. // Replacing mutates the blocks, so we need to convert to a logical index and back afterwards.
  1685. int index = indexInChunk + chunk.m_ChunkOffset;
  1686. int indexBeforeAdjustment = index;
  1687. // See if we accumulated any replacements, if so apply them.
  1688. ReplaceAllInChunk(replacements, replacementsCount, chunk, oldValue.Length, newValue);
  1689. // The replacement has affected the logical index. Adjust it.
  1690. index += ((newValue.Length - oldValue.Length) * replacementsCount);
  1691. replacementsCount = 0;
  1692. chunk = FindChunkForIndex(index);
  1693. indexInChunk = index - chunk.m_ChunkOffset;
  1694. Debug.Assert(chunk != null || count == 0, "Chunks ended prematurely!");
  1695. }
  1696. }
  1697. AssertInvariants();
  1698. return this;
  1699. }
  1700. /// <summary>
  1701. /// Replaces all instances of one character with another in this builder.
  1702. /// </summary>
  1703. /// <param name="oldChar">The character to replace.</param>
  1704. /// <param name="newChar">The character to replace <paramref name="oldChar"/> with.</param>
  1705. public StringBuilder Replace(char oldChar, char newChar)
  1706. {
  1707. return Replace(oldChar, newChar, 0, Length);
  1708. }
  1709. /// <summary>
  1710. /// Replaces all instances of one character with another in this builder.
  1711. /// </summary>
  1712. /// <param name="oldChar">The character to replace.</param>
  1713. /// <param name="newChar">The character to replace <paramref name="oldChar"/> with.</param>
  1714. /// <param name="startIndex">The index to start in this builder.</param>
  1715. /// <param name="count">The number of characters to read in this builder.</param>
  1716. public StringBuilder Replace(char oldChar, char newChar, int startIndex, int count)
  1717. {
  1718. int currentLength = Length;
  1719. if ((uint)startIndex > (uint)currentLength)
  1720. {
  1721. throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
  1722. }
  1723. if (count < 0 || startIndex > currentLength - count)
  1724. {
  1725. throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Index);
  1726. }
  1727. int endIndex = startIndex + count;
  1728. StringBuilder chunk = this;
  1729. for (;;)
  1730. {
  1731. int endIndexInChunk = endIndex - chunk.m_ChunkOffset;
  1732. int startIndexInChunk = startIndex - chunk.m_ChunkOffset;
  1733. if (endIndexInChunk >= 0)
  1734. {
  1735. int curInChunk = Math.Max(startIndexInChunk, 0);
  1736. int endInChunk = Math.Min(chunk.m_ChunkLength, endIndexInChunk);
  1737. while (curInChunk < endInChunk)
  1738. {
  1739. if (chunk.m_ChunkChars[curInChunk] == oldChar)
  1740. chunk.m_ChunkChars[curInChunk] = newChar;
  1741. curInChunk++;
  1742. }
  1743. }
  1744. if (startIndexInChunk >= 0)
  1745. break;
  1746. chunk = chunk.m_ChunkPrevious;
  1747. }
  1748. AssertInvariants();
  1749. return this;
  1750. }
  1751. /// <summary>
  1752. /// Appends a character buffer to this builder.
  1753. /// </summary>
  1754. /// <param name="value">The pointer to the start of the buffer.</param>
  1755. /// <param name="valueCount">The number of characters in the buffer.</param>
  1756. [CLSCompliant(false)]
  1757. public unsafe StringBuilder Append(char* value, int valueCount)
  1758. {
  1759. // We don't check null value as this case will throw null reference exception anyway
  1760. if (valueCount < 0)
  1761. {
  1762. throw new ArgumentOutOfRangeException(nameof(valueCount), SR.ArgumentOutOfRange_NegativeCount);
  1763. }
  1764. // this is where we can check if the valueCount will put us over m_MaxCapacity
  1765. // We are doing the check here to prevent the corruption of the StringBuilder.
  1766. int newLength = Length + valueCount;
  1767. if (newLength > m_MaxCapacity || newLength < valueCount)
  1768. {
  1769. throw new ArgumentOutOfRangeException(nameof(valueCount), SR.ArgumentOutOfRange_LengthGreaterThanCapacity);
  1770. }
  1771. // This case is so common we want to optimize for it heavily.
  1772. int newIndex = valueCount + m_ChunkLength;
  1773. if (newIndex <= m_ChunkChars.Length)
  1774. {
  1775. ThreadSafeCopy(value, m_ChunkChars, m_ChunkLength, valueCount);
  1776. m_ChunkLength = newIndex;
  1777. }
  1778. else
  1779. {
  1780. // Copy the first chunk
  1781. int firstLength = m_ChunkChars.Length - m_ChunkLength;
  1782. if (firstLength > 0)
  1783. {
  1784. ThreadSafeCopy(value, m_ChunkChars, m_ChunkLength, firstLength);
  1785. m_ChunkLength = m_ChunkChars.Length;
  1786. }
  1787. // Expand the builder to add another chunk.
  1788. int restLength = valueCount - firstLength;
  1789. ExpandByABlock(restLength);
  1790. Debug.Assert(m_ChunkLength == 0, "A new block was not created.");
  1791. // Copy the second chunk
  1792. ThreadSafeCopy(value + firstLength, m_ChunkChars, 0, restLength);
  1793. m_ChunkLength = restLength;
  1794. }
  1795. AssertInvariants();
  1796. return this;
  1797. }
  1798. /// <summary>
  1799. /// Inserts a character buffer into this builder at the specified position.
  1800. /// </summary>
  1801. /// <param name="index">The index to insert in this builder.</param>
  1802. /// <param name="value">The pointer to the start of the buffer.</param>
  1803. /// <param name="valueCount">The number of characters in the buffer.</param>
  1804. private unsafe void Insert(int index, char* value, int valueCount)
  1805. {
  1806. if ((uint)index > (uint)Length)
  1807. {
  1808. throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
  1809. }
  1810. if (valueCount > 0)
  1811. {
  1812. StringBuilder chunk;
  1813. int indexInChunk;
  1814. MakeRoom(index, valueCount, out chunk, out indexInChunk, false);
  1815. ReplaceInPlaceAtChunk(ref chunk, ref indexInChunk, value, valueCount);
  1816. }
  1817. }
  1818. /// <summary>
  1819. /// Replaces strings at specified indices with a new string in a chunk.
  1820. /// </summary>
  1821. /// <param name="replacements">The list of indices, relative to the beginning of the chunk, to remove at.</param>
  1822. /// <param name="replacementsCount">The number of replacements to make.</param>
  1823. /// <param name="sourceChunk">The source chunk.</param>
  1824. /// <param name="removeCount">The number of characters to remove at each replacement.</param>
  1825. /// <param name="value">The string to insert at each replacement.</param>
  1826. /// <remarks>
  1827. /// This routine is very efficient because it does replacements in bulk.
  1828. /// </remarks>
  1829. private void ReplaceAllInChunk(int[] replacements, int replacementsCount, StringBuilder sourceChunk, int removeCount, string value)
  1830. {
  1831. if (replacementsCount <= 0)
  1832. {
  1833. return;
  1834. }
  1835. unsafe
  1836. {
  1837. fixed (char* valuePtr = value)
  1838. {
  1839. // calculate the total amount of extra space or space needed for all the replacements.
  1840. long longDelta = (value.Length - removeCount) * (long)replacementsCount;
  1841. int delta = (int)longDelta;
  1842. if (delta != longDelta)
  1843. throw new OutOfMemoryException();
  1844. StringBuilder targetChunk = sourceChunk; // the target as we copy chars down
  1845. int targetIndexInChunk = replacements[0];
  1846. // Make the room needed for all the new characters if needed.
  1847. if (delta > 0)
  1848. MakeRoom(targetChunk.m_ChunkOffset + targetIndexInChunk, delta, out targetChunk, out targetIndexInChunk, true);
  1849. // We made certain that characters after the insertion point are not moved,
  1850. int i = 0;
  1851. for (;;)
  1852. {
  1853. // Copy in the new string for the ith replacement
  1854. ReplaceInPlaceAtChunk(ref targetChunk, ref targetIndexInChunk, valuePtr, value.Length);
  1855. int gapStart = replacements[i] + removeCount;
  1856. i++;
  1857. if (i >= replacementsCount)
  1858. {
  1859. break;
  1860. }
  1861. int gapEnd = replacements[i];
  1862. Debug.Assert(gapStart < sourceChunk.m_ChunkChars.Length, "gap starts at end of buffer. Should not happen");
  1863. Debug.Assert(gapStart <= gapEnd, "negative gap size");
  1864. Debug.Assert(gapEnd <= sourceChunk.m_ChunkLength, "gap too big");
  1865. if (delta != 0) // can skip the sliding of gaps if source an target string are the same size.
  1866. {
  1867. // Copy the gap data between the current replacement and the next replacement
  1868. fixed (char* sourcePtr = &sourceChunk.m_ChunkChars[gapStart])
  1869. ReplaceInPlaceAtChunk(ref targetChunk, ref targetIndexInChunk, sourcePtr, gapEnd - gapStart);
  1870. }
  1871. else
  1872. {
  1873. targetIndexInChunk += gapEnd - gapStart;
  1874. Debug.Assert(targetIndexInChunk <= targetChunk.m_ChunkLength, "gap not in chunk");
  1875. }
  1876. }
  1877. // Remove extra space if necessary.
  1878. if (delta < 0)
  1879. Remove(targetChunk.m_ChunkOffset + targetIndexInChunk, -delta, out targetChunk, out targetIndexInChunk);
  1880. }
  1881. }
  1882. }
  1883. /// <summary>
  1884. /// Returns a value indicating whether a substring of a builder starts with a specified prefix.
  1885. /// </summary>
  1886. /// <param name="chunk">The chunk in which the substring starts.</param>
  1887. /// <param name="indexInChunk">The index in <paramref name="chunk"/> at which the substring starts.</param>
  1888. /// <param name="count">The logical count of the substring.</param>
  1889. /// <param name="value">The prefix.</param>
  1890. private bool StartsWith(StringBuilder chunk, int indexInChunk, int count, string value)
  1891. {
  1892. for (int i = 0; i < value.Length; i++)
  1893. {
  1894. if (count == 0)
  1895. {
  1896. return false;
  1897. }
  1898. if (indexInChunk >= chunk.m_ChunkLength)
  1899. {
  1900. chunk = Next(chunk);
  1901. if (chunk == null)
  1902. return false;
  1903. indexInChunk = 0;
  1904. }
  1905. if (value[i] != chunk.m_ChunkChars[indexInChunk])
  1906. {
  1907. return false;
  1908. }
  1909. indexInChunk++;
  1910. --count;
  1911. }
  1912. return true;
  1913. }
  1914. /// <summary>
  1915. /// Replaces characters at a specified location with the contents of a character buffer.
  1916. /// This function is the logical equivalent of memcpy.
  1917. /// </summary>
  1918. /// <param name="chunk">
  1919. /// The chunk in which to start replacing characters.
  1920. /// Receives the chunk in which character replacement ends.
  1921. /// </param>
  1922. /// <param name="indexInChunk">
  1923. /// The index in <paramref name="chunk"/> to start replacing characters at.
  1924. /// Receives the index at which character replacement ends.
  1925. /// </param>
  1926. /// <param name="value">The pointer to the start of the character buffer.</param>
  1927. /// <param name="count">The number of characters in the buffer.</param>
  1928. private unsafe void ReplaceInPlaceAtChunk(ref StringBuilder chunk, ref int indexInChunk, char* value, int count)
  1929. {
  1930. if (count != 0)
  1931. {
  1932. for (;;)
  1933. {
  1934. int lengthInChunk = chunk.m_ChunkLength - indexInChunk;
  1935. Debug.Assert(lengthInChunk >= 0, "Index isn't in the chunk.");
  1936. int lengthToCopy = Math.Min(lengthInChunk, count);
  1937. ThreadSafeCopy(value, chunk.m_ChunkChars, indexInChunk, lengthToCopy);
  1938. // Advance the index.
  1939. indexInChunk += lengthToCopy;
  1940. if (indexInChunk >= chunk.m_ChunkLength)
  1941. {
  1942. chunk = Next(chunk);
  1943. indexInChunk = 0;
  1944. }
  1945. count -= lengthToCopy;
  1946. if (count == 0)
  1947. {
  1948. break;
  1949. }
  1950. value += lengthToCopy;
  1951. }
  1952. }
  1953. }
  1954. /// <remarks>
  1955. /// This method prevents out-of-bounds writes in the case a different thread updates a field in the builder just before a copy begins.
  1956. /// All interesting variables are copied out of the heap into the parameters of this method, and then bounds checks are run.
  1957. /// </remarks>
  1958. private static unsafe void ThreadSafeCopy(char* sourcePtr, char[] destination, int destinationIndex, int count)
  1959. {
  1960. if (count > 0)
  1961. {
  1962. if ((uint)destinationIndex <= (uint)destination.Length && (destinationIndex + count) <= destination.Length)
  1963. {
  1964. fixed (char* destinationPtr = &destination[destinationIndex])
  1965. string.wstrcpy(destinationPtr, sourcePtr, count);
  1966. }
  1967. else
  1968. {
  1969. throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_Index);
  1970. }
  1971. }
  1972. }
  1973. private static unsafe void ThreadSafeCopy(char[] source, int sourceIndex, Span<char> destination, int destinationIndex, int count)
  1974. {
  1975. if (count > 0)
  1976. {
  1977. if ((uint)sourceIndex > (uint)source.Length || count > source.Length - sourceIndex)
  1978. {
  1979. throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_Index);
  1980. }
  1981. if ((uint)destinationIndex > (uint)destination.Length || count > destination.Length - destinationIndex)
  1982. {
  1983. throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_Index);
  1984. }
  1985. fixed (char* sourcePtr = &source[sourceIndex])
  1986. fixed (char* destinationPtr = &MemoryMarshal.GetReference(destination))
  1987. string.wstrcpy(destinationPtr + destinationIndex, sourcePtr, count);
  1988. }
  1989. }
  1990. /// <summary>
  1991. /// Gets the chunk corresponding to the logical index in this builder.
  1992. /// </summary>
  1993. /// <param name="index">The logical index in this builder.</param>
  1994. /// <remarks>
  1995. /// After calling this method, you can obtain the actual index within the chunk by
  1996. /// subtracting <see cref="m_ChunkOffset"/> from <paramref name="index"/>.
  1997. /// </remarks>
  1998. private StringBuilder FindChunkForIndex(int index)
  1999. {
  2000. Debug.Assert(0 <= index && index <= Length);
  2001. StringBuilder result = this;
  2002. while (result.m_ChunkOffset > index)
  2003. {
  2004. result = result.m_ChunkPrevious;
  2005. }
  2006. Debug.Assert(result != null);
  2007. return result;
  2008. }
  2009. /// <summary>
  2010. /// Gets the chunk corresponding to the logical byte index in this builder.
  2011. /// </summary>
  2012. /// <param name="byteIndex">The logical byte index in this builder.</param>
  2013. private StringBuilder FindChunkForByte(int byteIndex)
  2014. {
  2015. Debug.Assert(0 <= byteIndex && byteIndex <= Length * sizeof(char));
  2016. StringBuilder result = this;
  2017. while (result.m_ChunkOffset * sizeof(char) > byteIndex)
  2018. {
  2019. result = result.m_ChunkPrevious;
  2020. }
  2021. Debug.Assert(result != null);
  2022. return result;
  2023. }
  2024. /// <summary>Gets a span representing the remaining space available in the current chunk.</summary>
  2025. private Span<char> RemainingCurrentChunk
  2026. {
  2027. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2028. get => new Span<char>(m_ChunkChars, m_ChunkLength, m_ChunkChars.Length - m_ChunkLength);
  2029. }
  2030. /// <summary>
  2031. /// Finds the chunk that logically succeeds the specified chunk.
  2032. /// </summary>
  2033. /// <param name="chunk">The chunk whose successor should be found.</param>
  2034. /// <remarks>
  2035. /// Each chunk only stores the pointer to its logical predecessor, so this routine has to start
  2036. /// from the 'this' pointer (which is assumed to represent the whole StringBuilder) and work its
  2037. /// way down until it finds the specified chunk (which is O(n)). Thus, it is more expensive than
  2038. /// a field fetch.
  2039. /// </remarks>
  2040. private StringBuilder Next(StringBuilder chunk) => chunk == this ? null : FindChunkForIndex(chunk.m_ChunkOffset + chunk.m_ChunkLength);
  2041. /// <summary>
  2042. /// Transfers the character buffer from this chunk to a new chunk, and allocates a new buffer with a minimum size for this chunk.
  2043. /// </summary>
  2044. /// <param name="minBlockCharCount">The minimum size of the new buffer to be allocated for this chunk.</param>
  2045. /// <remarks>
  2046. /// This method requires that the current chunk is full. Otherwise, there's no point in shifting the characters over.
  2047. /// It also assumes that 'this' is the last chunk in the linked list.
  2048. /// </remarks>
  2049. private void ExpandByABlock(int minBlockCharCount)
  2050. {
  2051. Debug.Assert(Capacity == Length, nameof(ExpandByABlock) + " should only be called when there is no space left.");
  2052. Debug.Assert(minBlockCharCount > 0);
  2053. AssertInvariants();
  2054. if ((minBlockCharCount + Length) > m_MaxCapacity || minBlockCharCount + Length < minBlockCharCount)
  2055. {
  2056. throw new ArgumentOutOfRangeException("requiredLength", SR.ArgumentOutOfRange_SmallCapacity);
  2057. }
  2058. // - We always need to make the new chunk at least as big as was requested (`minBlockCharCount`).
  2059. // - We'd also prefer to make it at least at big as the current length (thus doubling capacity).
  2060. // - But this is only up to a maximum, so we stay in the small object heap, and never allocate
  2061. // really big chunks even if the string gets really big.
  2062. int newBlockLength = Math.Max(minBlockCharCount, Math.Min(Length, MaxChunkSize));
  2063. // Check for integer overflow (logical buffer size > int.MaxValue)
  2064. if (m_ChunkOffset + m_ChunkLength + newBlockLength < newBlockLength)
  2065. throw new OutOfMemoryException();
  2066. // Allocate the array before updating any state to avoid leaving inconsistent state behind in case of out of memory exception
  2067. char[] chunkChars = new char[newBlockLength];
  2068. // Move all of the data from this chunk to a new one, via a few O(1) pointer adjustments.
  2069. // Then, have this chunk point to the new one as its predecessor.
  2070. m_ChunkPrevious = new StringBuilder(this);
  2071. m_ChunkOffset += m_ChunkLength;
  2072. m_ChunkLength = 0;
  2073. m_ChunkChars = chunkChars;
  2074. AssertInvariants();
  2075. }
  2076. /// <summary>
  2077. /// Creates a new chunk with fields copied from an existing chunk.
  2078. /// </summary>
  2079. /// <param name="from">The chunk from which to copy fields.</param>
  2080. /// <remarks>
  2081. /// <para>
  2082. /// This method runs in O(1) time. It does not copy data within the character buffer
  2083. /// <paramref name="from"/> holds, but copies the reference to the character buffer itself
  2084. /// (plus a few other fields).
  2085. /// </para>
  2086. /// <para>
  2087. /// Callers are expected to update <paramref name="from"/> subsequently to point to this
  2088. /// chunk as its predecessor.
  2089. /// </para>
  2090. /// </remarks>
  2091. private StringBuilder(StringBuilder from)
  2092. {
  2093. m_ChunkLength = from.m_ChunkLength;
  2094. m_ChunkOffset = from.m_ChunkOffset;
  2095. m_ChunkChars = from.m_ChunkChars;
  2096. m_ChunkPrevious = from.m_ChunkPrevious;
  2097. m_MaxCapacity = from.m_MaxCapacity;
  2098. AssertInvariants();
  2099. }
  2100. /// <summary>
  2101. /// Creates a gap at a logical index with the specified count.
  2102. /// </summary>
  2103. /// <param name="index">The logical index in this builder.</param>
  2104. /// <param name="count">The number of characters in the gap.</param>
  2105. /// <param name="chunk">Receives the chunk containing the gap.</param>
  2106. /// <param name="indexInChunk">The index in <paramref name="chunk"/> that points to the gap.</param>
  2107. /// <param name="doNotMoveFollowingChars">
  2108. /// - If <c>true</c>, then room must be made by inserting a chunk before the current chunk.
  2109. /// - If <c>false</c>, then room can be made by shifting characters ahead of <paramref name="index"/>
  2110. /// in this block forward by <paramref name="count"/> provided the characters will still fit in
  2111. /// the current chunk after being shifted.
  2112. /// - Providing <c>false</c> does not make a difference most of the time, but it can matter when someone
  2113. /// inserts lots of small strings at a position in the buffer.
  2114. /// </param>
  2115. /// <remarks>
  2116. /// <para>
  2117. /// Since chunks do not contain references to their successors, it is not always possible for us to make room
  2118. /// by inserting space after <paramref name="index"/> in case this chunk runs out of space. Thus, we make room
  2119. /// by inserting space before the specified index, and having logical indices refer to new locations by the end
  2120. /// of this method.
  2121. /// </para>
  2122. /// <para>
  2123. /// <see cref="ReplaceInPlaceAtChunk"/> can be used in conjunction with this method to fill in the newly created gap.
  2124. /// </para>
  2125. /// </remarks>
  2126. private void MakeRoom(int index, int count, out StringBuilder chunk, out int indexInChunk, bool doNotMoveFollowingChars)
  2127. {
  2128. AssertInvariants();
  2129. Debug.Assert(count > 0);
  2130. Debug.Assert(index >= 0);
  2131. if (count + Length > m_MaxCapacity || count + Length < count)
  2132. {
  2133. throw new ArgumentOutOfRangeException("requiredLength", SR.ArgumentOutOfRange_SmallCapacity);
  2134. }
  2135. chunk = this;
  2136. while (chunk.m_ChunkOffset > index)
  2137. {
  2138. chunk.m_ChunkOffset += count;
  2139. chunk = chunk.m_ChunkPrevious;
  2140. }
  2141. indexInChunk = index - chunk.m_ChunkOffset;
  2142. // 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 it.
  2143. // This typically happens when someone repeatedly inserts small strings at a spot (usually the absolute front) of the buffer.
  2144. if (!doNotMoveFollowingChars && chunk.m_ChunkLength <= DefaultCapacity * 2 && chunk.m_ChunkChars.Length - chunk.m_ChunkLength >= count)
  2145. {
  2146. for (int i = chunk.m_ChunkLength; i > indexInChunk; )
  2147. {
  2148. --i;
  2149. chunk.m_ChunkChars[i + count] = chunk.m_ChunkChars[i];
  2150. }
  2151. chunk.m_ChunkLength += count;
  2152. return;
  2153. }
  2154. // Allocate space for the new chunk, which will go before the current one.
  2155. StringBuilder newChunk = new StringBuilder(Math.Max(count, DefaultCapacity), chunk.m_MaxCapacity, chunk.m_ChunkPrevious);
  2156. newChunk.m_ChunkLength = count;
  2157. // Copy the head of the current buffer to the new buffer.
  2158. int copyCount1 = Math.Min(count, indexInChunk);
  2159. if (copyCount1 > 0)
  2160. {
  2161. unsafe
  2162. {
  2163. fixed (char* chunkCharsPtr = &chunk.m_ChunkChars[0])
  2164. {
  2165. ThreadSafeCopy(chunkCharsPtr, newChunk.m_ChunkChars, 0, copyCount1);
  2166. // Slide characters over in the current buffer to make room.
  2167. int copyCount2 = indexInChunk - copyCount1;
  2168. if (copyCount2 >= 0)
  2169. {
  2170. ThreadSafeCopy(chunkCharsPtr + copyCount1, chunk.m_ChunkChars, 0, copyCount2);
  2171. indexInChunk = copyCount2;
  2172. }
  2173. }
  2174. }
  2175. }
  2176. // Wire in the new chunk.
  2177. chunk.m_ChunkPrevious = newChunk;
  2178. chunk.m_ChunkOffset += count;
  2179. if (copyCount1 < count)
  2180. {
  2181. chunk = newChunk;
  2182. indexInChunk = copyCount1;
  2183. }
  2184. AssertInvariants();
  2185. }
  2186. /// <summary>
  2187. /// Used by <see cref="MakeRoom"/> to allocate another chunk.
  2188. /// </summary>
  2189. /// <param name="size">The size of the character buffer for this chunk.</param>
  2190. /// <param name="maxCapacity">The maximum capacity, to be stored in this chunk.</param>
  2191. /// <param name="previousBlock">The predecessor of this chunk.</param>
  2192. private StringBuilder(int size, int maxCapacity, StringBuilder previousBlock)
  2193. {
  2194. Debug.Assert(size > 0);
  2195. Debug.Assert(maxCapacity > 0);
  2196. m_ChunkChars = new char[size];
  2197. m_MaxCapacity = maxCapacity;
  2198. m_ChunkPrevious = previousBlock;
  2199. if (previousBlock != null)
  2200. {
  2201. m_ChunkOffset = previousBlock.m_ChunkOffset + previousBlock.m_ChunkLength;
  2202. }
  2203. AssertInvariants();
  2204. }
  2205. /// <summary>
  2206. /// Removes a specified number of characters beginning at a logical index in this builder.
  2207. /// </summary>
  2208. /// <param name="startIndex">The logical index in this builder to start removing characters.</param>
  2209. /// <param name="count">The number of characters to remove.</param>
  2210. /// <param name="chunk">Receives the new chunk containing the logical index.</param>
  2211. /// <param name="indexInChunk">
  2212. /// Receives the new index in <paramref name="chunk"/> that is associated with the logical index.
  2213. /// </param>
  2214. private void Remove(int startIndex, int count, out StringBuilder chunk, out int indexInChunk)
  2215. {
  2216. AssertInvariants();
  2217. Debug.Assert(startIndex >= 0 && startIndex < Length);
  2218. int endIndex = startIndex + count;
  2219. // Find the chunks for the start and end of the block to delete.
  2220. chunk = this;
  2221. StringBuilder endChunk = null;
  2222. int endIndexInChunk = 0;
  2223. for (;;)
  2224. {
  2225. if (endIndex - chunk.m_ChunkOffset >= 0)
  2226. {
  2227. if (endChunk == null)
  2228. {
  2229. endChunk = chunk;
  2230. endIndexInChunk = endIndex - endChunk.m_ChunkOffset;
  2231. }
  2232. if (startIndex - chunk.m_ChunkOffset >= 0)
  2233. {
  2234. indexInChunk = startIndex - chunk.m_ChunkOffset;
  2235. break;
  2236. }
  2237. }
  2238. else
  2239. {
  2240. chunk.m_ChunkOffset -= count;
  2241. }
  2242. chunk = chunk.m_ChunkPrevious;
  2243. }
  2244. Debug.Assert(chunk != null, "We fell off the beginning of the string!");
  2245. int copyTargetIndexInChunk = indexInChunk;
  2246. int copyCount = endChunk.m_ChunkLength - endIndexInChunk;
  2247. if (endChunk != chunk)
  2248. {
  2249. copyTargetIndexInChunk = 0;
  2250. // Remove the characters after `startIndex` to the end of the chunk.
  2251. chunk.m_ChunkLength = indexInChunk;
  2252. // Remove the characters in chunks between the start and the end chunk.
  2253. endChunk.m_ChunkPrevious = chunk;
  2254. endChunk.m_ChunkOffset = chunk.m_ChunkOffset + chunk.m_ChunkLength;
  2255. // If the start is 0, then we can throw away the whole start chunk.
  2256. if (indexInChunk == 0)
  2257. {
  2258. endChunk.m_ChunkPrevious = chunk.m_ChunkPrevious;
  2259. chunk = endChunk;
  2260. }
  2261. }
  2262. endChunk.m_ChunkLength -= (endIndexInChunk - copyTargetIndexInChunk);
  2263. // SafeCritical: We ensure that `endIndexInChunk + copyCount` is within range of `m_ChunkChars`, and
  2264. // also ensure that `copyTargetIndexInChunk + copyCount` is within the chunk.
  2265. // Remove any characters in the end chunk, by sliding the characters down.
  2266. if (copyTargetIndexInChunk != endIndexInChunk) // Sometimes no move is necessary
  2267. {
  2268. ThreadSafeCopy(endChunk.m_ChunkChars, endIndexInChunk, endChunk.m_ChunkChars, copyTargetIndexInChunk, copyCount);
  2269. }
  2270. Debug.Assert(chunk != null, "We fell off the beginning of the string!");
  2271. AssertInvariants();
  2272. }
  2273. }
  2274. }