StringBuilder.cs 102 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583
  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. public StringBuilder Append(object value) => (value == null) ? this : Append(value.ToString());
  1040. public StringBuilder Append(char[] value)
  1041. {
  1042. if (value?.Length > 0)
  1043. {
  1044. unsafe
  1045. {
  1046. fixed (char* valueChars = &value[0])
  1047. {
  1048. Append(valueChars, value.Length);
  1049. }
  1050. }
  1051. }
  1052. return this;
  1053. }
  1054. public StringBuilder Append(ReadOnlySpan<char> value)
  1055. {
  1056. if (value.Length > 0)
  1057. {
  1058. unsafe
  1059. {
  1060. fixed (char* valueChars = &MemoryMarshal.GetReference(value))
  1061. {
  1062. Append(valueChars, value.Length);
  1063. }
  1064. }
  1065. }
  1066. return this;
  1067. }
  1068. public StringBuilder Append(ReadOnlyMemory<char> value) => Append(value.Span);
  1069. #region AppendJoin
  1070. public unsafe StringBuilder AppendJoin(string separator, params object[] values)
  1071. {
  1072. separator = separator ?? string.Empty;
  1073. fixed (char* pSeparator = separator)
  1074. {
  1075. return AppendJoinCore(pSeparator, separator.Length, values);
  1076. }
  1077. }
  1078. public unsafe StringBuilder AppendJoin<T>(string separator, IEnumerable<T> values)
  1079. {
  1080. separator = separator ?? string.Empty;
  1081. fixed (char* pSeparator = separator)
  1082. {
  1083. return AppendJoinCore(pSeparator, separator.Length, values);
  1084. }
  1085. }
  1086. public unsafe StringBuilder AppendJoin(string separator, params string[] values)
  1087. {
  1088. separator = separator ?? string.Empty;
  1089. fixed (char* pSeparator = separator)
  1090. {
  1091. return AppendJoinCore(pSeparator, separator.Length, values);
  1092. }
  1093. }
  1094. public unsafe StringBuilder AppendJoin(char separator, params object[] values)
  1095. {
  1096. return AppendJoinCore(&separator, 1, values);
  1097. }
  1098. public unsafe StringBuilder AppendJoin<T>(char separator, IEnumerable<T> values)
  1099. {
  1100. return AppendJoinCore(&separator, 1, values);
  1101. }
  1102. public unsafe StringBuilder AppendJoin(char separator, params string[] values)
  1103. {
  1104. return AppendJoinCore(&separator, 1, values);
  1105. }
  1106. private unsafe StringBuilder AppendJoinCore<T>(char* separator, int separatorLength, IEnumerable<T> values)
  1107. {
  1108. Debug.Assert(separator != null);
  1109. Debug.Assert(separatorLength >= 0);
  1110. if (values == null)
  1111. {
  1112. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values);
  1113. }
  1114. using (IEnumerator<T> en = values.GetEnumerator())
  1115. {
  1116. if (!en.MoveNext())
  1117. {
  1118. return this;
  1119. }
  1120. var value = en.Current;
  1121. if (value != null)
  1122. {
  1123. Append(value.ToString());
  1124. }
  1125. while (en.MoveNext())
  1126. {
  1127. Append(separator, separatorLength);
  1128. value = en.Current;
  1129. if (value != null)
  1130. {
  1131. Append(value.ToString());
  1132. }
  1133. }
  1134. }
  1135. return this;
  1136. }
  1137. private unsafe StringBuilder AppendJoinCore<T>(char* separator, int separatorLength, T[] values)
  1138. {
  1139. if (values == null)
  1140. {
  1141. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values);
  1142. }
  1143. if (values.Length == 0)
  1144. {
  1145. return this;
  1146. }
  1147. if (values[0] != null)
  1148. {
  1149. Append(values[0].ToString());
  1150. }
  1151. for (int i = 1; i < values.Length; i++)
  1152. {
  1153. Append(separator, separatorLength);
  1154. if (values[i] != null)
  1155. {
  1156. Append(values[i].ToString());
  1157. }
  1158. }
  1159. return this;
  1160. }
  1161. #endregion
  1162. public StringBuilder Insert(int index, string value)
  1163. {
  1164. if ((uint)index > (uint)Length)
  1165. {
  1166. throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
  1167. }
  1168. if (value != null)
  1169. {
  1170. unsafe
  1171. {
  1172. fixed (char* sourcePtr = value)
  1173. Insert(index, sourcePtr, value.Length);
  1174. }
  1175. }
  1176. return this;
  1177. }
  1178. public StringBuilder Insert(int index, bool value) => Insert(index, value.ToString(), 1);
  1179. [CLSCompliant(false)]
  1180. public StringBuilder Insert(int index, sbyte value) => Insert(index, value.ToString(), 1);
  1181. public StringBuilder Insert(int index, byte value) => Insert(index, value.ToString(), 1);
  1182. public StringBuilder Insert(int index, short value) => Insert(index, value.ToString(), 1);
  1183. public StringBuilder Insert(int index, char value)
  1184. {
  1185. unsafe
  1186. {
  1187. Insert(index, &value, 1);
  1188. }
  1189. return this;
  1190. }
  1191. public StringBuilder Insert(int index, char[] value)
  1192. {
  1193. if ((uint)index > (uint)Length)
  1194. {
  1195. throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
  1196. }
  1197. if (value != null)
  1198. Insert(index, value, 0, value.Length);
  1199. return this;
  1200. }
  1201. public StringBuilder Insert(int index, char[] value, int startIndex, int charCount)
  1202. {
  1203. int currentLength = Length;
  1204. if ((uint)index > (uint)currentLength)
  1205. {
  1206. throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
  1207. }
  1208. if (value == null)
  1209. {
  1210. if (startIndex == 0 && charCount == 0)
  1211. {
  1212. return this;
  1213. }
  1214. throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String);
  1215. }
  1216. if (startIndex < 0)
  1217. {
  1218. throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
  1219. }
  1220. if (charCount < 0)
  1221. {
  1222. throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GenericPositive);
  1223. }
  1224. if (startIndex > value.Length - charCount)
  1225. {
  1226. throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
  1227. }
  1228. if (charCount > 0)
  1229. {
  1230. unsafe
  1231. {
  1232. fixed (char* sourcePtr = &value[startIndex])
  1233. Insert(index, sourcePtr, charCount);
  1234. }
  1235. }
  1236. return this;
  1237. }
  1238. public StringBuilder Insert(int index, int value) => Insert(index, value.ToString(), 1);
  1239. public StringBuilder Insert(int index, long value) => Insert(index, value.ToString(), 1);
  1240. public StringBuilder Insert(int index, float value) => Insert(index, value.ToString(), 1);
  1241. public StringBuilder Insert(int index, double value) => Insert(index, value.ToString(), 1);
  1242. public StringBuilder Insert(int index, decimal value) => Insert(index, value.ToString(), 1);
  1243. [CLSCompliant(false)]
  1244. public StringBuilder Insert(int index, ushort value) => Insert(index, value.ToString(), 1);
  1245. [CLSCompliant(false)]
  1246. public StringBuilder Insert(int index, uint value) => Insert(index, value.ToString(), 1);
  1247. [CLSCompliant(false)]
  1248. public StringBuilder Insert(int index, ulong value) => Insert(index, value.ToString(), 1);
  1249. public StringBuilder Insert(int index, object value) => (value == null) ? this : Insert(index, value.ToString(), 1);
  1250. public StringBuilder Insert(int index, ReadOnlySpan<char> value)
  1251. {
  1252. if ((uint)index > (uint)Length)
  1253. {
  1254. throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
  1255. }
  1256. if (value.Length > 0)
  1257. {
  1258. unsafe
  1259. {
  1260. fixed (char* sourcePtr = &MemoryMarshal.GetReference(value))
  1261. Insert(index, sourcePtr, value.Length);
  1262. }
  1263. }
  1264. return this;
  1265. }
  1266. public StringBuilder AppendFormat(string format, object arg0) => AppendFormatHelper(null, format, new ParamsArray(arg0));
  1267. public StringBuilder AppendFormat(string format, object arg0, object arg1) => AppendFormatHelper(null, format, new ParamsArray(arg0, arg1));
  1268. public StringBuilder AppendFormat(string format, object arg0, object arg1, object arg2) => AppendFormatHelper(null, format, new ParamsArray(arg0, arg1, arg2));
  1269. public StringBuilder AppendFormat(string format, params object[] args)
  1270. {
  1271. if (args == null)
  1272. {
  1273. // To preserve the original exception behavior, throw an exception about format if both
  1274. // args and format are null. The actual null check for format is in AppendFormatHelper.
  1275. string paramName = (format == null) ? nameof(format) : nameof(args);
  1276. throw new ArgumentNullException(paramName);
  1277. }
  1278. return AppendFormatHelper(null, format, new ParamsArray(args));
  1279. }
  1280. public StringBuilder AppendFormat(IFormatProvider provider, string format, object arg0) => AppendFormatHelper(provider, format, new ParamsArray(arg0));
  1281. public StringBuilder AppendFormat(IFormatProvider provider, string format, object arg0, object arg1) => AppendFormatHelper(provider, format, new ParamsArray(arg0, arg1));
  1282. public StringBuilder AppendFormat(IFormatProvider provider, string format, object arg0, object arg1, object arg2) => AppendFormatHelper(provider, format, new ParamsArray(arg0, arg1, arg2));
  1283. public StringBuilder AppendFormat(IFormatProvider provider, string format, params object[] args)
  1284. {
  1285. if (args == null)
  1286. {
  1287. // To preserve the original exception behavior, throw an exception about format if both
  1288. // args and format are null. The actual null check for format is in AppendFormatHelper.
  1289. string paramName = (format == null) ? nameof(format) : nameof(args);
  1290. throw new ArgumentNullException(paramName);
  1291. }
  1292. return AppendFormatHelper(provider, format, new ParamsArray(args));
  1293. }
  1294. private static void FormatError()
  1295. {
  1296. throw new FormatException(SR.Format_InvalidString);
  1297. }
  1298. // Undocumented exclusive limits on the range for Argument Hole Index and Argument Hole Alignment.
  1299. private const int IndexLimit = 1000000; // Note: 0 <= ArgIndex < IndexLimit
  1300. private const int WidthLimit = 1000000; // Note: -WidthLimit < ArgAlign < WidthLimit
  1301. internal StringBuilder AppendFormatHelper(IFormatProvider provider, string format, ParamsArray args)
  1302. {
  1303. if (format == null)
  1304. {
  1305. throw new ArgumentNullException(nameof(format));
  1306. }
  1307. int pos = 0;
  1308. int len = format.Length;
  1309. char ch = '\x0';
  1310. StringBuilder unescapedItemFormat = null;
  1311. ICustomFormatter cf = null;
  1312. if (provider != null)
  1313. {
  1314. cf = (ICustomFormatter)provider.GetFormat(typeof(ICustomFormatter));
  1315. }
  1316. while (true)
  1317. {
  1318. while (pos < len)
  1319. {
  1320. ch = format[pos];
  1321. pos++;
  1322. // Is it a closing brace?
  1323. if (ch == '}')
  1324. {
  1325. // Check next character (if there is one) to see if it is escaped. eg }}
  1326. if (pos < len && format[pos] == '}')
  1327. pos++;
  1328. else
  1329. // Otherwise treat it as an error (Mismatched closing brace)
  1330. FormatError();
  1331. }
  1332. // Is it a opening brace?
  1333. if (ch == '{')
  1334. {
  1335. // Check next character (if there is one) to see if it is escaped. eg {{
  1336. if (pos < len && format[pos] == '{')
  1337. pos++;
  1338. else
  1339. {
  1340. // Otherwise treat it as the opening brace of an Argument Hole.
  1341. pos--;
  1342. break;
  1343. }
  1344. }
  1345. // If it neither then treat the character as just text.
  1346. Append(ch);
  1347. }
  1348. //
  1349. // Start of parsing of Argument Hole.
  1350. // Argument Hole ::= { Index (, WS* Alignment WS*)? (: Formatting)? }
  1351. //
  1352. if (pos == len) break;
  1353. //
  1354. // Start of parsing required Index parameter.
  1355. // Index ::= ('0'-'9')+ WS*
  1356. //
  1357. pos++;
  1358. // If reached end of text then error (Unexpected end of text)
  1359. // or character is not a digit then error (Unexpected Character)
  1360. if (pos == len || (ch = format[pos]) < '0' || ch > '9') FormatError();
  1361. int index = 0;
  1362. do
  1363. {
  1364. index = index * 10 + ch - '0';
  1365. pos++;
  1366. // If reached end of text then error (Unexpected end of text)
  1367. if (pos == len) FormatError();
  1368. ch = format[pos];
  1369. // so long as character is digit and value of the index is less than 1000000 ( index limit )
  1370. }
  1371. while (ch >= '0' && ch <= '9' && index < IndexLimit);
  1372. // If value of index is not within the range of the arguments passed in then error (Index out of range)
  1373. if (index >= args.Length) throw new FormatException(SR.Format_IndexOutOfRange);
  1374. // Consume optional whitespace.
  1375. while (pos < len && (ch = format[pos]) == ' ') pos++;
  1376. // End of parsing index parameter.
  1377. //
  1378. // Start of parsing of optional Alignment
  1379. // Alignment ::= comma WS* minus? ('0'-'9')+ WS*
  1380. //
  1381. bool leftJustify = false;
  1382. int width = 0;
  1383. // Is the character a comma, which indicates the start of alignment parameter.
  1384. if (ch == ',')
  1385. {
  1386. pos++;
  1387. // Consume Optional whitespace
  1388. while (pos < len && format[pos] == ' ') pos++;
  1389. // If reached the end of the text then error (Unexpected end of text)
  1390. if (pos == len) FormatError();
  1391. // Is there a minus sign?
  1392. ch = format[pos];
  1393. if (ch == '-')
  1394. {
  1395. // Yes, then alignment is left justified.
  1396. leftJustify = true;
  1397. pos++;
  1398. // If reached end of text then error (Unexpected end of text)
  1399. if (pos == len) FormatError();
  1400. ch = format[pos];
  1401. }
  1402. // If current character is not a digit then error (Unexpected character)
  1403. if (ch < '0' || ch > '9') FormatError();
  1404. // Parse alignment digits.
  1405. do
  1406. {
  1407. width = width * 10 + ch - '0';
  1408. pos++;
  1409. // If reached end of text then error. (Unexpected end of text)
  1410. if (pos == len) FormatError();
  1411. ch = format[pos];
  1412. // So long a current character is a digit and the value of width is less than 100000 ( width limit )
  1413. }
  1414. while (ch >= '0' && ch <= '9' && width < WidthLimit);
  1415. // end of parsing Argument Alignment
  1416. }
  1417. // Consume optional whitespace
  1418. while (pos < len && (ch = format[pos]) == ' ') pos++;
  1419. //
  1420. // Start of parsing of optional formatting parameter.
  1421. //
  1422. object arg = args[index];
  1423. string itemFormat = null;
  1424. ReadOnlySpan<char> itemFormatSpan = default; // used if itemFormat is null
  1425. // Is current character a colon? which indicates start of formatting parameter.
  1426. if (ch == ':')
  1427. {
  1428. pos++;
  1429. int startPos = pos;
  1430. while (true)
  1431. {
  1432. // If reached end of text then error. (Unexpected end of text)
  1433. if (pos == len) FormatError();
  1434. ch = format[pos];
  1435. pos++;
  1436. // Is character a opening or closing brace?
  1437. if (ch == '}' || ch == '{')
  1438. {
  1439. if (ch == '{')
  1440. {
  1441. // Yes, is next character also a opening brace, then treat as escaped. eg {{
  1442. if (pos < len && format[pos] == '{')
  1443. pos++;
  1444. else
  1445. // Error Argument Holes can not be nested.
  1446. FormatError();
  1447. }
  1448. else
  1449. {
  1450. // Yes, is next character also a closing brace, then treat as escaped. eg }}
  1451. if (pos < len && format[pos] == '}')
  1452. pos++;
  1453. else
  1454. {
  1455. // No, then treat it as the closing brace of an Arg Hole.
  1456. pos--;
  1457. break;
  1458. }
  1459. }
  1460. // Reaching here means the brace has been escaped
  1461. // so we need to build up the format string in segments
  1462. if (unescapedItemFormat == null)
  1463. {
  1464. unescapedItemFormat = new StringBuilder();
  1465. }
  1466. unescapedItemFormat.Append(format, startPos, pos - startPos - 1);
  1467. startPos = pos;
  1468. }
  1469. }
  1470. if (unescapedItemFormat == null || unescapedItemFormat.Length == 0)
  1471. {
  1472. if (startPos != pos)
  1473. {
  1474. // There was no brace escaping, extract the item format as a single string
  1475. itemFormatSpan = format.AsSpan(startPos, pos - startPos);
  1476. }
  1477. }
  1478. else
  1479. {
  1480. unescapedItemFormat.Append(format, startPos, pos - startPos);
  1481. itemFormatSpan = itemFormat = unescapedItemFormat.ToString();
  1482. unescapedItemFormat.Clear();
  1483. }
  1484. }
  1485. // If current character is not a closing brace then error. (Unexpected Character)
  1486. if (ch != '}') FormatError();
  1487. // Construct the output for this arg hole.
  1488. pos++;
  1489. string s = null;
  1490. if (cf != null)
  1491. {
  1492. if (itemFormatSpan.Length != 0 && itemFormat == null)
  1493. {
  1494. itemFormat = new string(itemFormatSpan);
  1495. }
  1496. s = cf.Format(itemFormat, arg, provider);
  1497. }
  1498. if (s == null)
  1499. {
  1500. // If arg is ISpanFormattable and the beginning doesn't need padding,
  1501. // try formatting it into the remaining current chunk.
  1502. if (arg is ISpanFormattable spanFormattableArg &&
  1503. (leftJustify || width == 0) &&
  1504. spanFormattableArg.TryFormat(RemainingCurrentChunk, out int charsWritten, itemFormatSpan, provider))
  1505. {
  1506. m_ChunkLength += charsWritten;
  1507. // Pad the end, if needed.
  1508. int padding = width - charsWritten;
  1509. if (leftJustify && padding > 0) Append(' ', padding);
  1510. // Continue to parse other characters.
  1511. continue;
  1512. }
  1513. // Otherwise, fallback to trying IFormattable or calling ToString.
  1514. if (arg is IFormattable formattableArg)
  1515. {
  1516. if (itemFormatSpan.Length != 0 && itemFormat == null)
  1517. {
  1518. itemFormat = new string(itemFormatSpan);
  1519. }
  1520. s = formattableArg.ToString(itemFormat, provider);
  1521. }
  1522. else if (arg != null)
  1523. {
  1524. s = arg.ToString();
  1525. }
  1526. }
  1527. // Append it to the final output of the Format String.
  1528. if (s == null) s = string.Empty;
  1529. int pad = width - s.Length;
  1530. if (!leftJustify && pad > 0) Append(' ', pad);
  1531. Append(s);
  1532. if (leftJustify && pad > 0) Append(' ', pad);
  1533. // Continue to parse other characters.
  1534. }
  1535. return this;
  1536. }
  1537. /// <summary>
  1538. /// Replaces all instances of one string with another in this builder.
  1539. /// </summary>
  1540. /// <param name="oldValue">The string to replace.</param>
  1541. /// <param name="newValue">The string to replace <paramref name="oldValue"/> with.</param>
  1542. /// <remarks>
  1543. /// If <paramref name="newValue"/> is <c>null</c>, instances of <paramref name="oldValue"/>
  1544. /// are removed from this builder.
  1545. /// </remarks>
  1546. public StringBuilder Replace(string oldValue, string newValue) => Replace(oldValue, newValue, 0, Length);
  1547. /// <summary>
  1548. /// Determines if the contents of this builder are equal to the contents of another builder.
  1549. /// </summary>
  1550. /// <param name="sb">The other builder.</param>
  1551. public bool Equals(StringBuilder sb)
  1552. {
  1553. if (sb == null)
  1554. return false;
  1555. if (Length != sb.Length)
  1556. return false;
  1557. if (sb == this)
  1558. return true;
  1559. StringBuilder thisChunk = this;
  1560. int thisChunkIndex = thisChunk.m_ChunkLength;
  1561. StringBuilder sbChunk = sb;
  1562. int sbChunkIndex = sbChunk.m_ChunkLength;
  1563. for (;;)
  1564. {
  1565. --thisChunkIndex;
  1566. --sbChunkIndex;
  1567. while (thisChunkIndex < 0)
  1568. {
  1569. thisChunk = thisChunk.m_ChunkPrevious;
  1570. if (thisChunk == null)
  1571. break;
  1572. thisChunkIndex = thisChunk.m_ChunkLength + thisChunkIndex;
  1573. }
  1574. while (sbChunkIndex < 0)
  1575. {
  1576. sbChunk = sbChunk.m_ChunkPrevious;
  1577. if (sbChunk == null)
  1578. break;
  1579. sbChunkIndex = sbChunk.m_ChunkLength + sbChunkIndex;
  1580. }
  1581. if (thisChunkIndex < 0)
  1582. return sbChunkIndex < 0;
  1583. if (sbChunkIndex < 0)
  1584. return false;
  1585. if (thisChunk.m_ChunkChars[thisChunkIndex] != sbChunk.m_ChunkChars[sbChunkIndex])
  1586. return false;
  1587. }
  1588. }
  1589. /// <summary>
  1590. /// Determines if the contents of this builder are equal to the contents of <see cref="ReadOnlySpan{Char}"/>.
  1591. /// </summary>
  1592. /// <param name="span">The <see cref="ReadOnlySpan{Char}"/>.</param>
  1593. public bool Equals(ReadOnlySpan<char> span)
  1594. {
  1595. if (span.Length != Length)
  1596. return false;
  1597. StringBuilder sbChunk = this;
  1598. int offset = 0;
  1599. do
  1600. {
  1601. int chunk_length = sbChunk.m_ChunkLength;
  1602. offset += chunk_length;
  1603. ReadOnlySpan<char> chunk = new ReadOnlySpan<char>(sbChunk.m_ChunkChars, 0, chunk_length);
  1604. if (!chunk.EqualsOrdinal(span.Slice(span.Length - offset, chunk_length)))
  1605. return false;
  1606. sbChunk = sbChunk.m_ChunkPrevious;
  1607. } while (sbChunk != null);
  1608. Debug.Assert(offset == Length);
  1609. return true;
  1610. }
  1611. /// <summary>
  1612. /// Replaces all instances of one string with another in part of this builder.
  1613. /// </summary>
  1614. /// <param name="oldValue">The string to replace.</param>
  1615. /// <param name="newValue">The string to replace <paramref name="oldValue"/> with.</param>
  1616. /// <param name="startIndex">The index to start in this builder.</param>
  1617. /// <param name="count">The number of characters to read in this builder.</param>
  1618. /// <remarks>
  1619. /// If <paramref name="newValue"/> is <c>null</c>, instances of <paramref name="oldValue"/>
  1620. /// are removed from this builder.
  1621. /// </remarks>
  1622. public StringBuilder Replace(string oldValue, string newValue, int startIndex, int count)
  1623. {
  1624. int currentLength = Length;
  1625. if ((uint)startIndex > (uint)currentLength)
  1626. {
  1627. throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
  1628. }
  1629. if (count < 0 || startIndex > currentLength - count)
  1630. {
  1631. throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Index);
  1632. }
  1633. if (oldValue == null)
  1634. {
  1635. throw new ArgumentNullException(nameof(oldValue));
  1636. }
  1637. if (oldValue.Length == 0)
  1638. {
  1639. throw new ArgumentException(SR.Argument_EmptyName, nameof(oldValue));
  1640. }
  1641. newValue = newValue ?? string.Empty;
  1642. int deltaLength = newValue.Length - oldValue.Length;
  1643. int[] replacements = null; // A list of replacement positions in a chunk to apply
  1644. int replacementsCount = 0;
  1645. // Find the chunk, indexInChunk for the starting point
  1646. StringBuilder chunk = FindChunkForIndex(startIndex);
  1647. int indexInChunk = startIndex - chunk.m_ChunkOffset;
  1648. while (count > 0)
  1649. {
  1650. // Look for a match in the chunk,indexInChunk pointer
  1651. if (StartsWith(chunk, indexInChunk, count, oldValue))
  1652. {
  1653. // Push it on the replacements array (with growth), we will do all replacements in a
  1654. // given chunk in one operation below (see ReplaceAllInChunk) so we don't have to slide
  1655. // many times.
  1656. if (replacements == null)
  1657. {
  1658. replacements = new int[5];
  1659. }
  1660. else if (replacementsCount >= replacements.Length)
  1661. {
  1662. Array.Resize(ref replacements, replacements.Length * 3 / 2 + 4); // Grow by ~1.5x, but more in the begining
  1663. }
  1664. replacements[replacementsCount++] = indexInChunk;
  1665. indexInChunk += oldValue.Length;
  1666. count -= oldValue.Length;
  1667. }
  1668. else
  1669. {
  1670. indexInChunk++;
  1671. --count;
  1672. }
  1673. if (indexInChunk >= chunk.m_ChunkLength || count == 0) // Have we moved out of the current chunk?
  1674. {
  1675. // Replacing mutates the blocks, so we need to convert to a logical index and back afterwards.
  1676. int index = indexInChunk + chunk.m_ChunkOffset;
  1677. int indexBeforeAdjustment = index;
  1678. // See if we accumulated any replacements, if so apply them.
  1679. ReplaceAllInChunk(replacements, replacementsCount, chunk, oldValue.Length, newValue);
  1680. // The replacement has affected the logical index. Adjust it.
  1681. index += ((newValue.Length - oldValue.Length) * replacementsCount);
  1682. replacementsCount = 0;
  1683. chunk = FindChunkForIndex(index);
  1684. indexInChunk = index - chunk.m_ChunkOffset;
  1685. Debug.Assert(chunk != null || count == 0, "Chunks ended prematurely!");
  1686. }
  1687. }
  1688. AssertInvariants();
  1689. return this;
  1690. }
  1691. /// <summary>
  1692. /// Replaces all instances of one character with another in this builder.
  1693. /// </summary>
  1694. /// <param name="oldChar">The character to replace.</param>
  1695. /// <param name="newChar">The character to replace <paramref name="oldChar"/> with.</param>
  1696. public StringBuilder Replace(char oldChar, char newChar)
  1697. {
  1698. return Replace(oldChar, newChar, 0, Length);
  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. /// <param name="startIndex">The index to start in this builder.</param>
  1706. /// <param name="count">The number of characters to read in this builder.</param>
  1707. public StringBuilder Replace(char oldChar, char newChar, int startIndex, int count)
  1708. {
  1709. int currentLength = Length;
  1710. if ((uint)startIndex > (uint)currentLength)
  1711. {
  1712. throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
  1713. }
  1714. if (count < 0 || startIndex > currentLength - count)
  1715. {
  1716. throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Index);
  1717. }
  1718. int endIndex = startIndex + count;
  1719. StringBuilder chunk = this;
  1720. for (;;)
  1721. {
  1722. int endIndexInChunk = endIndex - chunk.m_ChunkOffset;
  1723. int startIndexInChunk = startIndex - chunk.m_ChunkOffset;
  1724. if (endIndexInChunk >= 0)
  1725. {
  1726. int curInChunk = Math.Max(startIndexInChunk, 0);
  1727. int endInChunk = Math.Min(chunk.m_ChunkLength, endIndexInChunk);
  1728. while (curInChunk < endInChunk)
  1729. {
  1730. if (chunk.m_ChunkChars[curInChunk] == oldChar)
  1731. chunk.m_ChunkChars[curInChunk] = newChar;
  1732. curInChunk++;
  1733. }
  1734. }
  1735. if (startIndexInChunk >= 0)
  1736. break;
  1737. chunk = chunk.m_ChunkPrevious;
  1738. }
  1739. AssertInvariants();
  1740. return this;
  1741. }
  1742. /// <summary>
  1743. /// Appends a character buffer to this builder.
  1744. /// </summary>
  1745. /// <param name="value">The pointer to the start of the buffer.</param>
  1746. /// <param name="valueCount">The number of characters in the buffer.</param>
  1747. [CLSCompliant(false)]
  1748. public unsafe StringBuilder Append(char* value, int valueCount)
  1749. {
  1750. // We don't check null value as this case will throw null reference exception anyway
  1751. if (valueCount < 0)
  1752. {
  1753. throw new ArgumentOutOfRangeException(nameof(valueCount), SR.ArgumentOutOfRange_NegativeCount);
  1754. }
  1755. // this is where we can check if the valueCount will put us over m_MaxCapacity
  1756. // We are doing the check here to prevent the corruption of the StringBuilder.
  1757. int newLength = Length + valueCount;
  1758. if (newLength > m_MaxCapacity || newLength < valueCount)
  1759. {
  1760. throw new ArgumentOutOfRangeException(nameof(valueCount), SR.ArgumentOutOfRange_LengthGreaterThanCapacity);
  1761. }
  1762. // This case is so common we want to optimize for it heavily.
  1763. int newIndex = valueCount + m_ChunkLength;
  1764. if (newIndex <= m_ChunkChars.Length)
  1765. {
  1766. ThreadSafeCopy(value, m_ChunkChars, m_ChunkLength, valueCount);
  1767. m_ChunkLength = newIndex;
  1768. }
  1769. else
  1770. {
  1771. // Copy the first chunk
  1772. int firstLength = m_ChunkChars.Length - m_ChunkLength;
  1773. if (firstLength > 0)
  1774. {
  1775. ThreadSafeCopy(value, m_ChunkChars, m_ChunkLength, firstLength);
  1776. m_ChunkLength = m_ChunkChars.Length;
  1777. }
  1778. // Expand the builder to add another chunk.
  1779. int restLength = valueCount - firstLength;
  1780. ExpandByABlock(restLength);
  1781. Debug.Assert(m_ChunkLength == 0, "A new block was not created.");
  1782. // Copy the second chunk
  1783. ThreadSafeCopy(value + firstLength, m_ChunkChars, 0, restLength);
  1784. m_ChunkLength = restLength;
  1785. }
  1786. AssertInvariants();
  1787. return this;
  1788. }
  1789. /// <summary>
  1790. /// Inserts a character buffer into this builder at the specified position.
  1791. /// </summary>
  1792. /// <param name="index">The index to insert in this builder.</param>
  1793. /// <param name="value">The pointer to the start of the buffer.</param>
  1794. /// <param name="valueCount">The number of characters in the buffer.</param>
  1795. private unsafe void Insert(int index, char* value, int valueCount)
  1796. {
  1797. if ((uint)index > (uint)Length)
  1798. {
  1799. throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
  1800. }
  1801. if (valueCount > 0)
  1802. {
  1803. StringBuilder chunk;
  1804. int indexInChunk;
  1805. MakeRoom(index, valueCount, out chunk, out indexInChunk, false);
  1806. ReplaceInPlaceAtChunk(ref chunk, ref indexInChunk, value, valueCount);
  1807. }
  1808. }
  1809. /// <summary>
  1810. /// Replaces strings at specified indices with a new string in a chunk.
  1811. /// </summary>
  1812. /// <param name="replacements">The list of indices, relative to the beginning of the chunk, to remove at.</param>
  1813. /// <param name="replacementsCount">The number of replacements to make.</param>
  1814. /// <param name="sourceChunk">The source chunk.</param>
  1815. /// <param name="removeCount">The number of characters to remove at each replacement.</param>
  1816. /// <param name="value">The string to insert at each replacement.</param>
  1817. /// <remarks>
  1818. /// This routine is very efficient because it does replacements in bulk.
  1819. /// </remarks>
  1820. private void ReplaceAllInChunk(int[] replacements, int replacementsCount, StringBuilder sourceChunk, int removeCount, string value)
  1821. {
  1822. if (replacementsCount <= 0)
  1823. {
  1824. return;
  1825. }
  1826. unsafe
  1827. {
  1828. fixed (char* valuePtr = value)
  1829. {
  1830. // calculate the total amount of extra space or space needed for all the replacements.
  1831. long longDelta = (value.Length - removeCount) * (long)replacementsCount;
  1832. int delta = (int)longDelta;
  1833. if (delta != longDelta)
  1834. throw new OutOfMemoryException();
  1835. StringBuilder targetChunk = sourceChunk; // the target as we copy chars down
  1836. int targetIndexInChunk = replacements[0];
  1837. // Make the room needed for all the new characters if needed.
  1838. if (delta > 0)
  1839. MakeRoom(targetChunk.m_ChunkOffset + targetIndexInChunk, delta, out targetChunk, out targetIndexInChunk, true);
  1840. // We made certain that characters after the insertion point are not moved,
  1841. int i = 0;
  1842. for (;;)
  1843. {
  1844. // Copy in the new string for the ith replacement
  1845. ReplaceInPlaceAtChunk(ref targetChunk, ref targetIndexInChunk, valuePtr, value.Length);
  1846. int gapStart = replacements[i] + removeCount;
  1847. i++;
  1848. if (i >= replacementsCount)
  1849. {
  1850. break;
  1851. }
  1852. int gapEnd = replacements[i];
  1853. Debug.Assert(gapStart < sourceChunk.m_ChunkChars.Length, "gap starts at end of buffer. Should not happen");
  1854. Debug.Assert(gapStart <= gapEnd, "negative gap size");
  1855. Debug.Assert(gapEnd <= sourceChunk.m_ChunkLength, "gap too big");
  1856. if (delta != 0) // can skip the sliding of gaps if source an target string are the same size.
  1857. {
  1858. // Copy the gap data between the current replacement and the next replacement
  1859. fixed (char* sourcePtr = &sourceChunk.m_ChunkChars[gapStart])
  1860. ReplaceInPlaceAtChunk(ref targetChunk, ref targetIndexInChunk, sourcePtr, gapEnd - gapStart);
  1861. }
  1862. else
  1863. {
  1864. targetIndexInChunk += gapEnd - gapStart;
  1865. Debug.Assert(targetIndexInChunk <= targetChunk.m_ChunkLength, "gap not in chunk");
  1866. }
  1867. }
  1868. // Remove extra space if necessary.
  1869. if (delta < 0)
  1870. Remove(targetChunk.m_ChunkOffset + targetIndexInChunk, -delta, out targetChunk, out targetIndexInChunk);
  1871. }
  1872. }
  1873. }
  1874. /// <summary>
  1875. /// Returns a value indicating whether a substring of a builder starts with a specified prefix.
  1876. /// </summary>
  1877. /// <param name="chunk">The chunk in which the substring starts.</param>
  1878. /// <param name="indexInChunk">The index in <paramref name="chunk"/> at which the substring starts.</param>
  1879. /// <param name="count">The logical count of the substring.</param>
  1880. /// <param name="value">The prefix.</param>
  1881. private bool StartsWith(StringBuilder chunk, int indexInChunk, int count, string value)
  1882. {
  1883. for (int i = 0; i < value.Length; i++)
  1884. {
  1885. if (count == 0)
  1886. {
  1887. return false;
  1888. }
  1889. if (indexInChunk >= chunk.m_ChunkLength)
  1890. {
  1891. chunk = Next(chunk);
  1892. if (chunk == null)
  1893. return false;
  1894. indexInChunk = 0;
  1895. }
  1896. if (value[i] != chunk.m_ChunkChars[indexInChunk])
  1897. {
  1898. return false;
  1899. }
  1900. indexInChunk++;
  1901. --count;
  1902. }
  1903. return true;
  1904. }
  1905. /// <summary>
  1906. /// Replaces characters at a specified location with the contents of a character buffer.
  1907. /// This function is the logical equivalent of memcpy.
  1908. /// </summary>
  1909. /// <param name="chunk">
  1910. /// The chunk in which to start replacing characters.
  1911. /// Receives the chunk in which character replacement ends.
  1912. /// </param>
  1913. /// <param name="indexInChunk">
  1914. /// The index in <paramref name="chunk"/> to start replacing characters at.
  1915. /// Receives the index at which character replacement ends.
  1916. /// </param>
  1917. /// <param name="value">The pointer to the start of the character buffer.</param>
  1918. /// <param name="count">The number of characters in the buffer.</param>
  1919. private unsafe void ReplaceInPlaceAtChunk(ref StringBuilder chunk, ref int indexInChunk, char* value, int count)
  1920. {
  1921. if (count != 0)
  1922. {
  1923. for (;;)
  1924. {
  1925. int lengthInChunk = chunk.m_ChunkLength - indexInChunk;
  1926. Debug.Assert(lengthInChunk >= 0, "Index isn't in the chunk.");
  1927. int lengthToCopy = Math.Min(lengthInChunk, count);
  1928. ThreadSafeCopy(value, chunk.m_ChunkChars, indexInChunk, lengthToCopy);
  1929. // Advance the index.
  1930. indexInChunk += lengthToCopy;
  1931. if (indexInChunk >= chunk.m_ChunkLength)
  1932. {
  1933. chunk = Next(chunk);
  1934. indexInChunk = 0;
  1935. }
  1936. count -= lengthToCopy;
  1937. if (count == 0)
  1938. {
  1939. break;
  1940. }
  1941. value += lengthToCopy;
  1942. }
  1943. }
  1944. }
  1945. /// <remarks>
  1946. /// This method prevents out-of-bounds writes in the case a different thread updates a field in the builder just before a copy begins.
  1947. /// All interesting variables are copied out of the heap into the parameters of this method, and then bounds checks are run.
  1948. /// </remarks>
  1949. private static unsafe void ThreadSafeCopy(char* sourcePtr, char[] destination, int destinationIndex, int count)
  1950. {
  1951. if (count > 0)
  1952. {
  1953. if ((uint)destinationIndex <= (uint)destination.Length && (destinationIndex + count) <= destination.Length)
  1954. {
  1955. fixed (char* destinationPtr = &destination[destinationIndex])
  1956. string.wstrcpy(destinationPtr, sourcePtr, count);
  1957. }
  1958. else
  1959. {
  1960. throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_Index);
  1961. }
  1962. }
  1963. }
  1964. private static unsafe void ThreadSafeCopy(char[] source, int sourceIndex, Span<char> destination, int destinationIndex, int count)
  1965. {
  1966. if (count > 0)
  1967. {
  1968. if ((uint)sourceIndex > (uint)source.Length || count > source.Length - sourceIndex)
  1969. {
  1970. throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_Index);
  1971. }
  1972. if ((uint)destinationIndex > (uint)destination.Length || count > destination.Length - destinationIndex)
  1973. {
  1974. throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_Index);
  1975. }
  1976. fixed (char* sourcePtr = &source[sourceIndex])
  1977. fixed (char* destinationPtr = &MemoryMarshal.GetReference(destination))
  1978. string.wstrcpy(destinationPtr + destinationIndex, sourcePtr, count);
  1979. }
  1980. }
  1981. /// <summary>
  1982. /// Gets the chunk corresponding to the logical index in this builder.
  1983. /// </summary>
  1984. /// <param name="index">The logical index in this builder.</param>
  1985. /// <remarks>
  1986. /// After calling this method, you can obtain the actual index within the chunk by
  1987. /// subtracting <see cref="m_ChunkOffset"/> from <paramref name="index"/>.
  1988. /// </remarks>
  1989. private StringBuilder FindChunkForIndex(int index)
  1990. {
  1991. Debug.Assert(0 <= index && index <= Length);
  1992. StringBuilder result = this;
  1993. while (result.m_ChunkOffset > index)
  1994. {
  1995. result = result.m_ChunkPrevious;
  1996. }
  1997. Debug.Assert(result != null);
  1998. return result;
  1999. }
  2000. /// <summary>
  2001. /// Gets the chunk corresponding to the logical byte index in this builder.
  2002. /// </summary>
  2003. /// <param name="byteIndex">The logical byte index in this builder.</param>
  2004. private StringBuilder FindChunkForByte(int byteIndex)
  2005. {
  2006. Debug.Assert(0 <= byteIndex && byteIndex <= Length * sizeof(char));
  2007. StringBuilder result = this;
  2008. while (result.m_ChunkOffset * sizeof(char) > byteIndex)
  2009. {
  2010. result = result.m_ChunkPrevious;
  2011. }
  2012. Debug.Assert(result != null);
  2013. return result;
  2014. }
  2015. /// <summary>Gets a span representing the remaining space available in the current chunk.</summary>
  2016. private Span<char> RemainingCurrentChunk
  2017. {
  2018. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2019. get => new Span<char>(m_ChunkChars, m_ChunkLength, m_ChunkChars.Length - m_ChunkLength);
  2020. }
  2021. /// <summary>
  2022. /// Finds the chunk that logically succeeds the specified chunk.
  2023. /// </summary>
  2024. /// <param name="chunk">The chunk whose successor should be found.</param>
  2025. /// <remarks>
  2026. /// Each chunk only stores the pointer to its logical predecessor, so this routine has to start
  2027. /// from the 'this' pointer (which is assumed to represent the whole StringBuilder) and work its
  2028. /// way down until it finds the specified chunk (which is O(n)). Thus, it is more expensive than
  2029. /// a field fetch.
  2030. /// </remarks>
  2031. private StringBuilder Next(StringBuilder chunk) => chunk == this ? null : FindChunkForIndex(chunk.m_ChunkOffset + chunk.m_ChunkLength);
  2032. /// <summary>
  2033. /// Transfers the character buffer from this chunk to a new chunk, and allocates a new buffer with a minimum size for this chunk.
  2034. /// </summary>
  2035. /// <param name="minBlockCharCount">The minimum size of the new buffer to be allocated for this chunk.</param>
  2036. /// <remarks>
  2037. /// This method requires that the current chunk is full. Otherwise, there's no point in shifting the characters over.
  2038. /// It also assumes that 'this' is the last chunk in the linked list.
  2039. /// </remarks>
  2040. private void ExpandByABlock(int minBlockCharCount)
  2041. {
  2042. Debug.Assert(Capacity == Length, nameof(ExpandByABlock) + " should only be called when there is no space left.");
  2043. Debug.Assert(minBlockCharCount > 0);
  2044. AssertInvariants();
  2045. if ((minBlockCharCount + Length) > m_MaxCapacity || minBlockCharCount + Length < minBlockCharCount)
  2046. {
  2047. throw new ArgumentOutOfRangeException("requiredLength", SR.ArgumentOutOfRange_SmallCapacity);
  2048. }
  2049. // - We always need to make the new chunk at least as big as was requested (`minBlockCharCount`).
  2050. // - We'd also prefer to make it at least at big as the current length (thus doubling capacity).
  2051. // - But this is only up to a maximum, so we stay in the small object heap, and never allocate
  2052. // really big chunks even if the string gets really big.
  2053. int newBlockLength = Math.Max(minBlockCharCount, Math.Min(Length, MaxChunkSize));
  2054. // Check for integer overflow (logical buffer size > int.MaxValue)
  2055. if (m_ChunkOffset + m_ChunkLength + newBlockLength < newBlockLength)
  2056. throw new OutOfMemoryException();
  2057. // Allocate the array before updating any state to avoid leaving inconsistent state behind in case of out of memory exception
  2058. char[] chunkChars = new char[newBlockLength];
  2059. // Move all of the data from this chunk to a new one, via a few O(1) pointer adjustments.
  2060. // Then, have this chunk point to the new one as its predecessor.
  2061. m_ChunkPrevious = new StringBuilder(this);
  2062. m_ChunkOffset += m_ChunkLength;
  2063. m_ChunkLength = 0;
  2064. m_ChunkChars = chunkChars;
  2065. AssertInvariants();
  2066. }
  2067. /// <summary>
  2068. /// Creates a new chunk with fields copied from an existing chunk.
  2069. /// </summary>
  2070. /// <param name="from">The chunk from which to copy fields.</param>
  2071. /// <remarks>
  2072. /// <para>
  2073. /// This method runs in O(1) time. It does not copy data within the character buffer
  2074. /// <paramref name="from"/> holds, but copies the reference to the character buffer itself
  2075. /// (plus a few other fields).
  2076. /// </para>
  2077. /// <para>
  2078. /// Callers are expected to update <paramref name="from"/> subsequently to point to this
  2079. /// chunk as its predecessor.
  2080. /// </para>
  2081. /// </remarks>
  2082. private StringBuilder(StringBuilder from)
  2083. {
  2084. m_ChunkLength = from.m_ChunkLength;
  2085. m_ChunkOffset = from.m_ChunkOffset;
  2086. m_ChunkChars = from.m_ChunkChars;
  2087. m_ChunkPrevious = from.m_ChunkPrevious;
  2088. m_MaxCapacity = from.m_MaxCapacity;
  2089. AssertInvariants();
  2090. }
  2091. /// <summary>
  2092. /// Creates a gap at a logical index with the specified count.
  2093. /// </summary>
  2094. /// <param name="index">The logical index in this builder.</param>
  2095. /// <param name="count">The number of characters in the gap.</param>
  2096. /// <param name="chunk">Receives the chunk containing the gap.</param>
  2097. /// <param name="indexInChunk">The index in <paramref name="chunk"/> that points to the gap.</param>
  2098. /// <param name="doNotMoveFollowingChars">
  2099. /// - If <c>true</c>, then room must be made by inserting a chunk before the current chunk.
  2100. /// - If <c>false</c>, then room can be made by shifting characters ahead of <paramref name="index"/>
  2101. /// in this block forward by <paramref name="count"/> provided the characters will still fit in
  2102. /// the current chunk after being shifted.
  2103. /// - Providing <c>false</c> does not make a difference most of the time, but it can matter when someone
  2104. /// inserts lots of small strings at a position in the buffer.
  2105. /// </param>
  2106. /// <remarks>
  2107. /// <para>
  2108. /// Since chunks do not contain references to their successors, it is not always possible for us to make room
  2109. /// by inserting space after <paramref name="index"/> in case this chunk runs out of space. Thus, we make room
  2110. /// by inserting space before the specified index, and having logical indices refer to new locations by the end
  2111. /// of this method.
  2112. /// </para>
  2113. /// <para>
  2114. /// <see cref="ReplaceInPlaceAtChunk"/> can be used in conjunction with this method to fill in the newly created gap.
  2115. /// </para>
  2116. /// </remarks>
  2117. private void MakeRoom(int index, int count, out StringBuilder chunk, out int indexInChunk, bool doNotMoveFollowingChars)
  2118. {
  2119. AssertInvariants();
  2120. Debug.Assert(count > 0);
  2121. Debug.Assert(index >= 0);
  2122. if (count + Length > m_MaxCapacity || count + Length < count)
  2123. {
  2124. throw new ArgumentOutOfRangeException("requiredLength", SR.ArgumentOutOfRange_SmallCapacity);
  2125. }
  2126. chunk = this;
  2127. while (chunk.m_ChunkOffset > index)
  2128. {
  2129. chunk.m_ChunkOffset += count;
  2130. chunk = chunk.m_ChunkPrevious;
  2131. }
  2132. indexInChunk = index - chunk.m_ChunkOffset;
  2133. // 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.
  2134. // This typically happens when someone repeatedly inserts small strings at a spot (usually the absolute front) of the buffer.
  2135. if (!doNotMoveFollowingChars && chunk.m_ChunkLength <= DefaultCapacity * 2 && chunk.m_ChunkChars.Length - chunk.m_ChunkLength >= count)
  2136. {
  2137. for (int i = chunk.m_ChunkLength; i > indexInChunk; )
  2138. {
  2139. --i;
  2140. chunk.m_ChunkChars[i + count] = chunk.m_ChunkChars[i];
  2141. }
  2142. chunk.m_ChunkLength += count;
  2143. return;
  2144. }
  2145. // Allocate space for the new chunk, which will go before the current one.
  2146. StringBuilder newChunk = new StringBuilder(Math.Max(count, DefaultCapacity), chunk.m_MaxCapacity, chunk.m_ChunkPrevious);
  2147. newChunk.m_ChunkLength = count;
  2148. // Copy the head of the current buffer to the new buffer.
  2149. int copyCount1 = Math.Min(count, indexInChunk);
  2150. if (copyCount1 > 0)
  2151. {
  2152. unsafe
  2153. {
  2154. fixed (char* chunkCharsPtr = &chunk.m_ChunkChars[0])
  2155. {
  2156. ThreadSafeCopy(chunkCharsPtr, newChunk.m_ChunkChars, 0, copyCount1);
  2157. // Slide characters over in the current buffer to make room.
  2158. int copyCount2 = indexInChunk - copyCount1;
  2159. if (copyCount2 >= 0)
  2160. {
  2161. ThreadSafeCopy(chunkCharsPtr + copyCount1, chunk.m_ChunkChars, 0, copyCount2);
  2162. indexInChunk = copyCount2;
  2163. }
  2164. }
  2165. }
  2166. }
  2167. // Wire in the new chunk.
  2168. chunk.m_ChunkPrevious = newChunk;
  2169. chunk.m_ChunkOffset += count;
  2170. if (copyCount1 < count)
  2171. {
  2172. chunk = newChunk;
  2173. indexInChunk = copyCount1;
  2174. }
  2175. AssertInvariants();
  2176. }
  2177. /// <summary>
  2178. /// Used by <see cref="MakeRoom"/> to allocate another chunk.
  2179. /// </summary>
  2180. /// <param name="size">The size of the character buffer for this chunk.</param>
  2181. /// <param name="maxCapacity">The maximum capacity, to be stored in this chunk.</param>
  2182. /// <param name="previousBlock">The predecessor of this chunk.</param>
  2183. private StringBuilder(int size, int maxCapacity, StringBuilder previousBlock)
  2184. {
  2185. Debug.Assert(size > 0);
  2186. Debug.Assert(maxCapacity > 0);
  2187. m_ChunkChars = new char[size];
  2188. m_MaxCapacity = maxCapacity;
  2189. m_ChunkPrevious = previousBlock;
  2190. if (previousBlock != null)
  2191. {
  2192. m_ChunkOffset = previousBlock.m_ChunkOffset + previousBlock.m_ChunkLength;
  2193. }
  2194. AssertInvariants();
  2195. }
  2196. /// <summary>
  2197. /// Removes a specified number of characters beginning at a logical index in this builder.
  2198. /// </summary>
  2199. /// <param name="startIndex">The logical index in this builder to start removing characters.</param>
  2200. /// <param name="count">The number of characters to remove.</param>
  2201. /// <param name="chunk">Receives the new chunk containing the logical index.</param>
  2202. /// <param name="indexInChunk">
  2203. /// Receives the new index in <paramref name="chunk"/> that is associated with the logical index.
  2204. /// </param>
  2205. private void Remove(int startIndex, int count, out StringBuilder chunk, out int indexInChunk)
  2206. {
  2207. AssertInvariants();
  2208. Debug.Assert(startIndex >= 0 && startIndex < Length);
  2209. int endIndex = startIndex + count;
  2210. // Find the chunks for the start and end of the block to delete.
  2211. chunk = this;
  2212. StringBuilder endChunk = null;
  2213. int endIndexInChunk = 0;
  2214. for (;;)
  2215. {
  2216. if (endIndex - chunk.m_ChunkOffset >= 0)
  2217. {
  2218. if (endChunk == null)
  2219. {
  2220. endChunk = chunk;
  2221. endIndexInChunk = endIndex - endChunk.m_ChunkOffset;
  2222. }
  2223. if (startIndex - chunk.m_ChunkOffset >= 0)
  2224. {
  2225. indexInChunk = startIndex - chunk.m_ChunkOffset;
  2226. break;
  2227. }
  2228. }
  2229. else
  2230. {
  2231. chunk.m_ChunkOffset -= count;
  2232. }
  2233. chunk = chunk.m_ChunkPrevious;
  2234. }
  2235. Debug.Assert(chunk != null, "We fell off the beginning of the string!");
  2236. int copyTargetIndexInChunk = indexInChunk;
  2237. int copyCount = endChunk.m_ChunkLength - endIndexInChunk;
  2238. if (endChunk != chunk)
  2239. {
  2240. copyTargetIndexInChunk = 0;
  2241. // Remove the characters after `startIndex` to the end of the chunk.
  2242. chunk.m_ChunkLength = indexInChunk;
  2243. // Remove the characters in chunks between the start and the end chunk.
  2244. endChunk.m_ChunkPrevious = chunk;
  2245. endChunk.m_ChunkOffset = chunk.m_ChunkOffset + chunk.m_ChunkLength;
  2246. // If the start is 0, then we can throw away the whole start chunk.
  2247. if (indexInChunk == 0)
  2248. {
  2249. endChunk.m_ChunkPrevious = chunk.m_ChunkPrevious;
  2250. chunk = endChunk;
  2251. }
  2252. }
  2253. endChunk.m_ChunkLength -= (endIndexInChunk - copyTargetIndexInChunk);
  2254. // SafeCritical: We ensure that `endIndexInChunk + copyCount` is within range of `m_ChunkChars`, and
  2255. // also ensure that `copyTargetIndexInChunk + copyCount` is within the chunk.
  2256. // Remove any characters in the end chunk, by sliding the characters down.
  2257. if (copyTargetIndexInChunk != endIndexInChunk) // Sometimes no move is necessary
  2258. {
  2259. ThreadSafeCopy(endChunk.m_ChunkChars, endIndexInChunk, endChunk.m_ChunkChars, copyTargetIndexInChunk, copyCount);
  2260. }
  2261. Debug.Assert(chunk != null, "We fell off the beginning of the string!");
  2262. AssertInvariants();
  2263. }
  2264. }
  2265. }