ValueStringBuilder.cs 8.3 KB

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