ValueStringBuilder.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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 Append(string? s)
  167. {
  168. if (s == null)
  169. {
  170. return;
  171. }
  172. int pos = _pos;
  173. if (s.Length == 1 && (uint)pos < (uint)_chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc.
  174. {
  175. _chars[pos] = s[0];
  176. _pos = pos + 1;
  177. }
  178. else
  179. {
  180. AppendSlow(s);
  181. }
  182. }
  183. private void AppendSlow(string s)
  184. {
  185. int pos = _pos;
  186. if (pos > _chars.Length - s.Length)
  187. {
  188. Grow(s.Length);
  189. }
  190. s
  191. #if !NETCOREAPP
  192. .AsSpan()
  193. #endif
  194. .CopyTo(_chars.Slice(pos));
  195. _pos += s.Length;
  196. }
  197. public void Append(char c, int count)
  198. {
  199. if (_pos > _chars.Length - count)
  200. {
  201. Grow(count);
  202. }
  203. Span<char> dst = _chars.Slice(_pos, count);
  204. for (int i = 0; i < dst.Length; i++)
  205. {
  206. dst[i] = c;
  207. }
  208. _pos += count;
  209. }
  210. public unsafe void Append(char* value, int length)
  211. {
  212. int pos = _pos;
  213. if (pos > _chars.Length - length)
  214. {
  215. Grow(length);
  216. }
  217. Span<char> dst = _chars.Slice(_pos, length);
  218. for (int i = 0; i < dst.Length; i++)
  219. {
  220. dst[i] = *value++;
  221. }
  222. _pos += length;
  223. }
  224. public void Append(scoped ReadOnlySpan<char> value)
  225. {
  226. int pos = _pos;
  227. if (pos > _chars.Length - value.Length)
  228. {
  229. Grow(value.Length);
  230. }
  231. value.CopyTo(_chars.Slice(_pos));
  232. _pos += value.Length;
  233. }
  234. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  235. public Span<char> AppendSpan(int length)
  236. {
  237. int origPos = _pos;
  238. if (origPos > _chars.Length - length)
  239. {
  240. Grow(length);
  241. }
  242. _pos = origPos + length;
  243. return _chars.Slice(origPos, length);
  244. }
  245. [MethodImpl(MethodImplOptions.NoInlining)]
  246. private void GrowAndAppend(char c)
  247. {
  248. Grow(1);
  249. Append(c);
  250. }
  251. /// <summary>
  252. /// Resize the internal buffer either by doubling current buffer size or
  253. /// by adding <paramref name="additionalCapacityBeyondPos"/> to
  254. /// <see cref="_pos"/> whichever is greater.
  255. /// </summary>
  256. /// <param name="additionalCapacityBeyondPos">
  257. /// Number of chars requested beyond current position.
  258. /// </param>
  259. [MethodImpl(MethodImplOptions.NoInlining)]
  260. private void Grow(int additionalCapacityBeyondPos)
  261. {
  262. Debug.Assert(additionalCapacityBeyondPos > 0);
  263. Debug.Assert(_pos > _chars.Length - additionalCapacityBeyondPos, "Grow called incorrectly, no resize is needed.");
  264. const uint ArrayMaxLength = 0x7FFFFFC7; // same as Array.MaxLength
  265. // Increase to at least the required size (_pos + additionalCapacityBeyondPos), but try
  266. // to double the size if possible, bounding the doubling to not go beyond the max array length.
  267. int newCapacity = (int)Math.Max(
  268. (uint)(_pos + additionalCapacityBeyondPos),
  269. Math.Min((uint)_chars.Length * 2, ArrayMaxLength));
  270. // Make sure to let Rent throw an exception if the caller has a bug and the desired capacity is negative.
  271. // This could also go negative if the actual required length wraps around.
  272. char[] poolArray = ArrayPool<char>.Shared.Rent(newCapacity);
  273. _chars.Slice(0, _pos).CopyTo(poolArray);
  274. char[]? toReturn = _arrayToReturnToPool;
  275. _chars = _arrayToReturnToPool = poolArray;
  276. if (toReturn != null)
  277. {
  278. ArrayPool<char>.Shared.Return(toReturn);
  279. }
  280. }
  281. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  282. public void Dispose()
  283. {
  284. char[]? toReturn = _arrayToReturnToPool;
  285. this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again
  286. if (toReturn != null)
  287. {
  288. ArrayPool<char>.Shared.Return(toReturn);
  289. }
  290. }
  291. }