ValueStringBuilder.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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 bool TryCopyTo(Span<char> destination, out int charsWritten)
  101. {
  102. if (_chars.Slice(0, _pos).TryCopyTo(destination))
  103. {
  104. charsWritten = _pos;
  105. Dispose();
  106. return true;
  107. }
  108. else
  109. {
  110. charsWritten = 0;
  111. Dispose();
  112. return false;
  113. }
  114. }
  115. public void Insert(int index, char value, int count)
  116. {
  117. if (_pos > _chars.Length - count)
  118. {
  119. Grow(count);
  120. }
  121. int remaining = _pos - index;
  122. _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));
  123. _chars.Slice(index, count).Fill(value);
  124. _pos += count;
  125. }
  126. public void Insert(int index, string? s)
  127. {
  128. if (s == null)
  129. {
  130. return;
  131. }
  132. int count = s.Length;
  133. if (_pos > (_chars.Length - count))
  134. {
  135. Grow(count);
  136. }
  137. int remaining = _pos - index;
  138. _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));
  139. s
  140. #if !NETCOREAPP
  141. .AsSpan()
  142. #endif
  143. .CopyTo(_chars.Slice(index));
  144. _pos += count;
  145. }
  146. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  147. public void Append(char c)
  148. {
  149. int pos = _pos;
  150. Span<char> chars = _chars;
  151. if ((uint)pos < (uint)chars.Length)
  152. {
  153. chars[pos] = c;
  154. _pos = pos + 1;
  155. }
  156. else
  157. {
  158. GrowAndAppend(c);
  159. }
  160. }
  161. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  162. public void Append(string? s)
  163. {
  164. if (s == null)
  165. {
  166. return;
  167. }
  168. int pos = _pos;
  169. if (s.Length == 1 && (uint)pos < (uint)_chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc.
  170. {
  171. _chars[pos] = s[0];
  172. _pos = pos + 1;
  173. }
  174. else
  175. {
  176. AppendSlow(s);
  177. }
  178. }
  179. private void AppendSlow(string s)
  180. {
  181. int pos = _pos;
  182. if (pos > _chars.Length - s.Length)
  183. {
  184. Grow(s.Length);
  185. }
  186. s
  187. #if !NETCOREAPP
  188. .AsSpan()
  189. #endif
  190. .CopyTo(_chars.Slice(pos));
  191. _pos += s.Length;
  192. }
  193. public void Append(char c, int count)
  194. {
  195. if (_pos > _chars.Length - count)
  196. {
  197. Grow(count);
  198. }
  199. Span<char> dst = _chars.Slice(_pos, count);
  200. for (int i = 0; i < dst.Length; i++)
  201. {
  202. dst[i] = c;
  203. }
  204. _pos += count;
  205. }
  206. public unsafe void Append(char* value, int length)
  207. {
  208. int pos = _pos;
  209. if (pos > _chars.Length - length)
  210. {
  211. Grow(length);
  212. }
  213. Span<char> dst = _chars.Slice(_pos, length);
  214. for (int i = 0; i < dst.Length; i++)
  215. {
  216. dst[i] = *value++;
  217. }
  218. _pos += length;
  219. }
  220. public void Append(scoped ReadOnlySpan<char> value)
  221. {
  222. int pos = _pos;
  223. if (pos > _chars.Length - value.Length)
  224. {
  225. Grow(value.Length);
  226. }
  227. value.CopyTo(_chars.Slice(_pos));
  228. _pos += value.Length;
  229. }
  230. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  231. public Span<char> AppendSpan(int length)
  232. {
  233. int origPos = _pos;
  234. if (origPos > _chars.Length - length)
  235. {
  236. Grow(length);
  237. }
  238. _pos = origPos + length;
  239. return _chars.Slice(origPos, length);
  240. }
  241. [MethodImpl(MethodImplOptions.NoInlining)]
  242. private void GrowAndAppend(char c)
  243. {
  244. Grow(1);
  245. Append(c);
  246. }
  247. /// <summary>
  248. /// Resize the internal buffer either by doubling current buffer size or
  249. /// by adding <paramref name="additionalCapacityBeyondPos"/> to
  250. /// <see cref="_pos"/> whichever is greater.
  251. /// </summary>
  252. /// <param name="additionalCapacityBeyondPos">
  253. /// Number of chars requested beyond current position.
  254. /// </param>
  255. [MethodImpl(MethodImplOptions.NoInlining)]
  256. private void Grow(int additionalCapacityBeyondPos)
  257. {
  258. Debug.Assert(additionalCapacityBeyondPos > 0);
  259. Debug.Assert(_pos > _chars.Length - additionalCapacityBeyondPos, "Grow called incorrectly, no resize is needed.");
  260. const uint ArrayMaxLength = 0x7FFFFFC7; // same as Array.MaxLength
  261. // Increase to at least the required size (_pos + additionalCapacityBeyondPos), but try
  262. // to double the size if possible, bounding the doubling to not go beyond the max array length.
  263. int newCapacity = (int)Math.Max(
  264. (uint)(_pos + additionalCapacityBeyondPos),
  265. Math.Min((uint)_chars.Length * 2, ArrayMaxLength));
  266. // Make sure to let Rent throw an exception if the caller has a bug and the desired capacity is negative.
  267. // This could also go negative if the actual required length wraps around.
  268. char[] poolArray = ArrayPool<char>.Shared.Rent(newCapacity);
  269. _chars.Slice(0, _pos).CopyTo(poolArray);
  270. char[]? toReturn = _arrayToReturnToPool;
  271. _chars = _arrayToReturnToPool = poolArray;
  272. if (toReturn != null)
  273. {
  274. ArrayPool<char>.Shared.Return(toReturn);
  275. }
  276. }
  277. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  278. public void Dispose()
  279. {
  280. char[]? toReturn = _arrayToReturnToPool;
  281. this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again
  282. if (toReturn != null)
  283. {
  284. ArrayPool<char>.Shared.Return(toReturn);
  285. }
  286. }
  287. }