ValueStringBuilder.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. var 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. int count = s.Length;
  128. if (_pos > (_chars.Length - count))
  129. {
  130. Grow(count);
  131. }
  132. int remaining = _pos - index;
  133. _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));
  134. s.AsSpan().CopyTo(_chars.Slice(index));
  135. _pos += count;
  136. }
  137. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  138. public void Append(char c)
  139. {
  140. int pos = _pos;
  141. if ((uint)pos < (uint)_chars.Length)
  142. {
  143. _chars[pos] = c;
  144. _pos = pos + 1;
  145. }
  146. else
  147. {
  148. GrowAndAppend(c);
  149. }
  150. }
  151. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  152. public void Append(string s)
  153. {
  154. int pos = _pos;
  155. if (s.Length == 1 && (uint)pos < (uint)_chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc.
  156. {
  157. _chars[pos] = s[0];
  158. _pos = pos + 1;
  159. }
  160. else
  161. {
  162. AppendSlow(s);
  163. }
  164. }
  165. private void AppendSlow(string s)
  166. {
  167. int pos = _pos;
  168. if (pos > _chars.Length - s.Length)
  169. {
  170. Grow(s.Length);
  171. }
  172. s.AsSpan().CopyTo(_chars.Slice(pos));
  173. _pos += s.Length;
  174. }
  175. public void Append(char c, int count)
  176. {
  177. if (_pos > _chars.Length - count)
  178. {
  179. Grow(count);
  180. }
  181. Span<char> dst = _chars.Slice(_pos, count);
  182. for (int i = 0; i < dst.Length; i++)
  183. {
  184. dst[i] = c;
  185. }
  186. _pos += count;
  187. }
  188. public unsafe void Append(char* value, int length)
  189. {
  190. int pos = _pos;
  191. if (pos > _chars.Length - length)
  192. {
  193. Grow(length);
  194. }
  195. Span<char> dst = _chars.Slice(_pos, length);
  196. for (int i = 0; i < dst.Length; i++)
  197. {
  198. dst[i] = *value++;
  199. }
  200. _pos += length;
  201. }
  202. public void Append(ReadOnlySpan<char> value)
  203. {
  204. int pos = _pos;
  205. if (pos > _chars.Length - value.Length)
  206. {
  207. Grow(value.Length);
  208. }
  209. value.CopyTo(_chars.Slice(_pos));
  210. _pos += value.Length;
  211. }
  212. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  213. public Span<char> AppendSpan(int length)
  214. {
  215. int origPos = _pos;
  216. if (origPos > _chars.Length - length)
  217. {
  218. Grow(length);
  219. }
  220. _pos = origPos + length;
  221. return _chars.Slice(origPos, length);
  222. }
  223. [MethodImpl(MethodImplOptions.NoInlining)]
  224. private void GrowAndAppend(char c)
  225. {
  226. Grow(1);
  227. Append(c);
  228. }
  229. /// <summary>
  230. /// Resize the internal buffer either by doubling current buffer size or
  231. /// by adding <paramref name="additionalCapacityBeyondPos"/> to
  232. /// <see cref="_pos"/> whichever is greater.
  233. /// </summary>
  234. /// <param name="additionalCapacityBeyondPos">
  235. /// Number of chars requested beyond current position.
  236. /// </param>
  237. [MethodImpl(MethodImplOptions.NoInlining)]
  238. private void Grow(int additionalCapacityBeyondPos)
  239. {
  240. Debug.Assert(additionalCapacityBeyondPos > 0);
  241. Debug.Assert(_pos > _chars.Length - additionalCapacityBeyondPos, "Grow called incorrectly, no resize is needed.");
  242. char[] poolArray = ArrayPool<char>.Shared.Rent(Math.Max(_pos + additionalCapacityBeyondPos, _chars.Length * 2));
  243. _chars.CopyTo(poolArray);
  244. char[]? toReturn = _arrayToReturnToPool;
  245. _chars = _arrayToReturnToPool = poolArray;
  246. if (toReturn != null)
  247. {
  248. ArrayPool<char>.Shared.Return(toReturn);
  249. }
  250. }
  251. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  252. public void Dispose()
  253. {
  254. char[]? toReturn = _arrayToReturnToPool;
  255. this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again
  256. if (toReturn != null)
  257. {
  258. ArrayPool<char>.Shared.Return(toReturn);
  259. }
  260. }
  261. }
  262. }