StringBuilder.cs 103 KB

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