StringBuilder.cs 104 KB

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