ValueStringBuilder.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. using System.Buffers;
  4. using System.Diagnostics;
  5. using System.Runtime.CompilerServices;
  6. using System.Runtime.InteropServices;
  7. // ReSharper disable once CheckNamespace
  8. namespace System.Text;
  9. internal ref struct ValueStringBuilder
  10. {
  11. private char[]? _arrayToReturnToPool;
  12. private Span<char> _chars;
  13. private int _pos;
  14. public ValueStringBuilder(Span<char> initialBuffer)
  15. {
  16. _arrayToReturnToPool = null;
  17. _chars = initialBuffer;
  18. _pos = 0;
  19. }
  20. public ValueStringBuilder(int initialCapacity)
  21. {
  22. _arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity);
  23. _chars = _arrayToReturnToPool;
  24. _pos = 0;
  25. }
  26. public int Length
  27. {
  28. get => _pos;
  29. set
  30. {
  31. Debug.Assert(value >= 0);
  32. Debug.Assert(value <= _chars.Length);
  33. _pos = value;
  34. }
  35. }
  36. public int Capacity => _chars.Length;
  37. public void EnsureCapacity(int capacity)
  38. {
  39. // This is not expected to be called this with negative capacity
  40. Debug.Assert(capacity >= 0);
  41. // If the caller has a bug and calls this with negative capacity, make sure to call Grow to throw an exception.
  42. if ((uint) capacity > (uint) _chars.Length)
  43. Grow(capacity - _pos);
  44. }
  45. /// <summary>
  46. /// Get a pinnable reference to the builder.
  47. /// Does not ensure there is a null char after <see cref="Length"/>
  48. /// This overload is pattern matched in the C# 7.3+ compiler so you can omit
  49. /// the explicit method call, and write eg "fixed (char* c = builder)"
  50. /// </summary>
  51. public ref char GetPinnableReference()
  52. {
  53. return ref MemoryMarshal.GetReference(_chars);
  54. }
  55. /// <summary>
  56. /// Get a pinnable reference to the builder.
  57. /// </summary>
  58. /// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param>
  59. public ref char GetPinnableReference(bool terminate)
  60. {
  61. if (terminate)
  62. {
  63. EnsureCapacity(Length + 1);
  64. _chars[Length] = '\0';
  65. }
  66. return ref MemoryMarshal.GetReference(_chars);
  67. }
  68. public ref char this[int index]
  69. {
  70. get
  71. {
  72. Debug.Assert(index < _pos);
  73. return ref _chars[index];
  74. }
  75. }
  76. public override string ToString()
  77. {
  78. string s = _chars.Slice(0, _pos).ToString();
  79. Dispose();
  80. return s;
  81. }
  82. /// <summary>Returns the underlying storage of the builder.</summary>
  83. public Span<char> RawChars => _chars;
  84. /// <summary>
  85. /// Returns a span around the contents of the builder.
  86. /// </summary>
  87. /// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param>
  88. public ReadOnlySpan<char> AsSpan(bool terminate)
  89. {
  90. if (terminate)
  91. {
  92. EnsureCapacity(Length + 1);
  93. _chars[Length] = '\0';
  94. }
  95. return _chars.Slice(0, _pos);
  96. }
  97. public ReadOnlySpan<char> AsSpan() => _chars.Slice(0, _pos);
  98. public ReadOnlySpan<char> AsSpan(int start) => _chars.Slice(start, _pos - start);
  99. public ReadOnlySpan<char> AsSpan(int start, int length) => _chars.Slice(start, length);
  100. public void Reverse()
  101. {
  102. _chars.Slice(0, _pos).Reverse();
  103. }
  104. public bool TryCopyTo(Span<char> destination, out int charsWritten)
  105. {
  106. if (_chars.Slice(0, _pos).TryCopyTo(destination))
  107. {
  108. charsWritten = _pos;
  109. Dispose();
  110. return true;
  111. }
  112. else
  113. {
  114. charsWritten = 0;
  115. Dispose();
  116. return false;
  117. }
  118. }
  119. public void Insert(int index, char value, int count)
  120. {
  121. if (_pos > _chars.Length - count)
  122. {
  123. Grow(count);
  124. }
  125. int remaining = _pos - index;
  126. _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));
  127. _chars.Slice(index, count).Fill(value);
  128. _pos += count;
  129. }
  130. public void Insert(int index, string? s)
  131. {
  132. if (s == null)
  133. {
  134. return;
  135. }
  136. int count = s.Length;
  137. if (_pos > (_chars.Length - count))
  138. {
  139. Grow(count);
  140. }
  141. int remaining = _pos - index;
  142. _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));
  143. s
  144. #if !NETCOREAPP
  145. .AsSpan()
  146. #endif
  147. .CopyTo(_chars.Slice(index));
  148. _pos += count;
  149. }
  150. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  151. public void Append(char c)
  152. {
  153. int pos = _pos;
  154. Span<char> chars = _chars;
  155. if ((uint) pos < (uint) chars.Length)
  156. {
  157. chars[pos] = c;
  158. _pos = pos + 1;
  159. }
  160. else
  161. {
  162. GrowAndAppend(c);
  163. }
  164. }
  165. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  166. public void AppendHex(byte b)
  167. {
  168. const string Map = "0123456789ABCDEF";
  169. ReadOnlySpan<char> data =
  170. [
  171. Map[b / 16],
  172. Map[b % 16]
  173. ];
  174. Append(data);
  175. }
  176. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  177. public void Append(string? s)
  178. {
  179. if (s == null)
  180. {
  181. return;
  182. }
  183. int pos = _pos;
  184. if (s.Length == 1 && (uint) pos < (uint) _chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc.
  185. {
  186. _chars[pos] = s[0];
  187. _pos = pos + 1;
  188. }
  189. else
  190. {
  191. AppendSlow(s);
  192. }
  193. }
  194. #if NET6_0_OR_GREATER
  195. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  196. public void Append<T>(T value) where T : ISpanFormattable
  197. {
  198. if (value.TryFormat(_chars.Slice(_pos), out var charsWritten, format: default, provider: null))
  199. {
  200. _pos += charsWritten;
  201. }
  202. else
  203. {
  204. Append(value.ToString());
  205. }
  206. }
  207. #else
  208. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  209. public void Append(int value)
  210. {
  211. Append(value.ToString(System.Globalization.CultureInfo.InvariantCulture));
  212. }
  213. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  214. public void Append(long value)
  215. {
  216. Append(value.ToString(System.Globalization.CultureInfo.InvariantCulture));
  217. }
  218. #endif
  219. private void AppendSlow(string s)
  220. {
  221. int pos = _pos;
  222. if (pos > _chars.Length - s.Length)
  223. {
  224. Grow(s.Length);
  225. }
  226. s
  227. #if !NETCOREAPP
  228. .AsSpan()
  229. #endif
  230. .CopyTo(_chars.Slice(pos));
  231. _pos += s.Length;
  232. }
  233. public void Append(char c, int count)
  234. {
  235. if (_pos > _chars.Length - count)
  236. {
  237. Grow(count);
  238. }
  239. Span<char> dst = _chars.Slice(_pos, count);
  240. for (int i = 0; i < dst.Length; i++)
  241. {
  242. dst[i] = c;
  243. }
  244. _pos += count;
  245. }
  246. public unsafe void Append(char* value, int length)
  247. {
  248. int pos = _pos;
  249. if (pos > _chars.Length - length)
  250. {
  251. Grow(length);
  252. }
  253. Span<char> dst = _chars.Slice(_pos, length);
  254. for (int i = 0; i < dst.Length; i++)
  255. {
  256. dst[i] = *value++;
  257. }
  258. _pos += length;
  259. }
  260. public void Append(scoped ReadOnlySpan<char> value)
  261. {
  262. int pos = _pos;
  263. if (pos > _chars.Length - value.Length)
  264. {
  265. Grow(value.Length);
  266. }
  267. value.CopyTo(_chars.Slice(_pos));
  268. _pos += value.Length;
  269. }
  270. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  271. public Span<char> AppendSpan(int length)
  272. {
  273. int origPos = _pos;
  274. if (origPos > _chars.Length - length)
  275. {
  276. Grow(length);
  277. }
  278. _pos = origPos + length;
  279. return _chars.Slice(origPos, length);
  280. }
  281. [MethodImpl(MethodImplOptions.NoInlining)]
  282. private void GrowAndAppend(char c)
  283. {
  284. Grow(1);
  285. Append(c);
  286. }
  287. /// <summary>
  288. /// Resize the internal buffer either by doubling current buffer size or
  289. /// by adding <paramref name="additionalCapacityBeyondPos"/> to
  290. /// <see cref="_pos"/> whichever is greater.
  291. /// </summary>
  292. /// <param name="additionalCapacityBeyondPos">
  293. /// Number of chars requested beyond current position.
  294. /// </param>
  295. [MethodImpl(MethodImplOptions.NoInlining)]
  296. private void Grow(int additionalCapacityBeyondPos)
  297. {
  298. Debug.Assert(additionalCapacityBeyondPos > 0);
  299. Debug.Assert(_pos > _chars.Length - additionalCapacityBeyondPos, "Grow called incorrectly, no resize is needed.");
  300. const uint ArrayMaxLength = 0x7FFFFFC7; // same as Array.MaxLength
  301. // Increase to at least the required size (_pos + additionalCapacityBeyondPos), but try
  302. // to double the size if possible, bounding the doubling to not go beyond the max array length.
  303. int newCapacity = (int) Math.Max(
  304. (uint) (_pos + additionalCapacityBeyondPos),
  305. Math.Min((uint) _chars.Length * 2, ArrayMaxLength));
  306. // Make sure to let Rent throw an exception if the caller has a bug and the desired capacity is negative.
  307. // This could also go negative if the actual required length wraps around.
  308. char[] poolArray = ArrayPool<char>.Shared.Rent(newCapacity);
  309. _chars.Slice(0, _pos).CopyTo(poolArray);
  310. char[]? toReturn = _arrayToReturnToPool;
  311. _chars = _arrayToReturnToPool = poolArray;
  312. if (toReturn != null)
  313. {
  314. ArrayPool<char>.Shared.Return(toReturn);
  315. }
  316. }
  317. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  318. public void Dispose()
  319. {
  320. char[]? toReturn = _arrayToReturnToPool;
  321. this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again
  322. if (toReturn != null)
  323. {
  324. ArrayPool<char>.Shared.Return(toReturn);
  325. }
  326. }
  327. }