ValueStringBuilder.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. #nullable enable
  5. using System.Buffers;
  6. using System.Diagnostics;
  7. using System.Runtime.CompilerServices;
  8. using System.Runtime.InteropServices;
  9. namespace System.Text
  10. {
  11. internal ref partial struct ValueStringBuilder
  12. {
  13. private char[]? _arrayToReturnToPool;
  14. private Span<char> _chars;
  15. private int _pos;
  16. public ValueStringBuilder(Span<char> initialBuffer)
  17. {
  18. _arrayToReturnToPool = null;
  19. _chars = initialBuffer;
  20. _pos = 0;
  21. }
  22. public ValueStringBuilder(int initialCapacity)
  23. {
  24. _arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity);
  25. _chars = _arrayToReturnToPool;
  26. _pos = 0;
  27. }
  28. public int Length
  29. {
  30. get => _pos;
  31. set
  32. {
  33. Debug.Assert(value >= 0);
  34. Debug.Assert(value <= _chars.Length);
  35. _pos = value;
  36. }
  37. }
  38. public int Capacity => _chars.Length;
  39. public void EnsureCapacity(int capacity)
  40. {
  41. if (capacity > _chars.Length)
  42. Grow(capacity - _pos);
  43. }
  44. /// <summary>
  45. /// Get a pinnable reference to the builder.
  46. /// Does not ensure there is a null char after <see cref="Length"/>
  47. /// This overload is pattern matched in the C# 7.3+ compiler so you can omit
  48. /// the explicit method call, and write eg "fixed (char* c = builder)"
  49. /// </summary>
  50. public ref char GetPinnableReference()
  51. {
  52. return ref MemoryMarshal.GetReference(_chars);
  53. }
  54. /// <summary>
  55. /// Get a pinnable reference to the builder.
  56. /// </summary>
  57. /// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param>
  58. public ref char GetPinnableReference(bool terminate)
  59. {
  60. if (terminate)
  61. {
  62. EnsureCapacity(Length + 1);
  63. _chars[Length] = '\0';
  64. }
  65. return ref MemoryMarshal.GetReference(_chars);
  66. }
  67. public ref char this[int index]
  68. {
  69. get
  70. {
  71. Debug.Assert(index < _pos);
  72. return ref _chars[index];
  73. }
  74. }
  75. public override string ToString()
  76. {
  77. string s = _chars.Slice(0, _pos).ToString();
  78. Dispose();
  79. return s;
  80. }
  81. /// <summary>Returns the underlying storage of the builder.</summary>
  82. public Span<char> RawChars => _chars;
  83. /// <summary>
  84. /// Returns a span around the contents of the builder.
  85. /// </summary>
  86. /// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param>
  87. public ReadOnlySpan<char> AsSpan(bool terminate)
  88. {
  89. if (terminate)
  90. {
  91. EnsureCapacity(Length + 1);
  92. _chars[Length] = '\0';
  93. }
  94. return _chars.Slice(0, _pos);
  95. }
  96. public ReadOnlySpan<char> AsSpan() => _chars.Slice(0, _pos);
  97. public ReadOnlySpan<char> AsSpan(int start) => _chars.Slice(start, _pos - start);
  98. public ReadOnlySpan<char> AsSpan(int start, int length) => _chars.Slice(start, length);
  99. public bool TryCopyTo(Span<char> destination, out int charsWritten)
  100. {
  101. if (_chars.Slice(0, _pos).TryCopyTo(destination))
  102. {
  103. charsWritten = _pos;
  104. Dispose();
  105. return true;
  106. }
  107. else
  108. {
  109. charsWritten = 0;
  110. Dispose();
  111. return false;
  112. }
  113. }
  114. public void Insert(int index, char value, int count)
  115. {
  116. if (_pos > _chars.Length - count)
  117. {
  118. Grow(count);
  119. }
  120. int remaining = _pos - index;
  121. _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));
  122. _chars.Slice(index, count).Fill(value);
  123. _pos += count;
  124. }
  125. public void Insert(int index, string? s)
  126. {
  127. if (s == null)
  128. {
  129. return;
  130. }
  131. int count = s.Length;
  132. if (_pos > (_chars.Length - count))
  133. {
  134. Grow(count);
  135. }
  136. int remaining = _pos - index;
  137. _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));
  138. s.AsSpan().CopyTo(_chars.Slice(index));
  139. _pos += count;
  140. }
  141. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  142. public void Append(char c)
  143. {
  144. int pos = _pos;
  145. if ((uint)pos < (uint)_chars.Length)
  146. {
  147. _chars[pos] = c;
  148. _pos = pos + 1;
  149. }
  150. else
  151. {
  152. GrowAndAppend(c);
  153. }
  154. }
  155. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  156. public void Append(string? s)
  157. {
  158. if (s == null)
  159. {
  160. return;
  161. }
  162. int pos = _pos;
  163. if (s.Length == 1 && (uint)pos < (uint)_chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc.
  164. {
  165. _chars[pos] = s[0];
  166. _pos = pos + 1;
  167. }
  168. else
  169. {
  170. AppendSlow(s);
  171. }
  172. }
  173. private void AppendSlow(string s)
  174. {
  175. int pos = _pos;
  176. if (pos > _chars.Length - s.Length)
  177. {
  178. Grow(s.Length);
  179. }
  180. s.AsSpan().CopyTo(_chars.Slice(pos));
  181. _pos += s.Length;
  182. }
  183. public void Append(char c, int count)
  184. {
  185. if (_pos > _chars.Length - count)
  186. {
  187. Grow(count);
  188. }
  189. Span<char> dst = _chars.Slice(_pos, count);
  190. for (int i = 0; i < dst.Length; i++)
  191. {
  192. dst[i] = c;
  193. }
  194. _pos += count;
  195. }
  196. public unsafe void Append(char* value, int length)
  197. {
  198. int pos = _pos;
  199. if (pos > _chars.Length - length)
  200. {
  201. Grow(length);
  202. }
  203. Span<char> dst = _chars.Slice(_pos, length);
  204. for (int i = 0; i < dst.Length; i++)
  205. {
  206. dst[i] = *value++;
  207. }
  208. _pos += length;
  209. }
  210. public void Append(ReadOnlySpan<char> value)
  211. {
  212. int pos = _pos;
  213. if (pos > _chars.Length - value.Length)
  214. {
  215. Grow(value.Length);
  216. }
  217. value.CopyTo(_chars.Slice(_pos));
  218. _pos += value.Length;
  219. }
  220. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  221. public Span<char> AppendSpan(int length)
  222. {
  223. int origPos = _pos;
  224. if (origPos > _chars.Length - length)
  225. {
  226. Grow(length);
  227. }
  228. _pos = origPos + length;
  229. return _chars.Slice(origPos, length);
  230. }
  231. [MethodImpl(MethodImplOptions.NoInlining)]
  232. private void GrowAndAppend(char c)
  233. {
  234. Grow(1);
  235. Append(c);
  236. }
  237. /// <summary>
  238. /// Resize the internal buffer either by doubling current buffer size or
  239. /// by adding <paramref name="additionalCapacityBeyondPos"/> to
  240. /// <see cref="_pos"/> whichever is greater.
  241. /// </summary>
  242. /// <param name="additionalCapacityBeyondPos">
  243. /// Number of chars requested beyond current position.
  244. /// </param>
  245. [MethodImpl(MethodImplOptions.NoInlining)]
  246. private void Grow(int additionalCapacityBeyondPos)
  247. {
  248. Debug.Assert(additionalCapacityBeyondPos > 0);
  249. Debug.Assert(_pos > _chars.Length - additionalCapacityBeyondPos, "Grow called incorrectly, no resize is needed.");
  250. char[] poolArray = ArrayPool<char>.Shared.Rent(Math.Max(_pos + additionalCapacityBeyondPos, _chars.Length * 2));
  251. _chars.Slice(0, _pos).CopyTo(poolArray);
  252. char[]? toReturn = _arrayToReturnToPool;
  253. _chars = _arrayToReturnToPool = poolArray;
  254. if (toReturn != null)
  255. {
  256. ArrayPool<char>.Shared.Return(toReturn);
  257. }
  258. }
  259. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  260. public void Dispose()
  261. {
  262. char[]? toReturn = _arrayToReturnToPool;
  263. this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again
  264. if (toReturn != null)
  265. {
  266. ArrayPool<char>.Shared.Return(toReturn);
  267. }
  268. }
  269. }
  270. }