ValueStringBuilder.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. #nullable enable
  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. // This is not expected to be called this with negative capacity
  41. Debug.Assert(capacity >= 0);
  42. // If the caller has a bug and calls this with negative capacity, make sure to call Grow to throw an exception.
  43. if ((uint)capacity > (uint)_chars.Length)
  44. Grow(capacity - _pos);
  45. }
  46. /// <summary>
  47. /// Get a pinnable reference to the builder.
  48. /// Does not ensure there is a null char after <see cref="Length"/>
  49. /// This overload is pattern matched in the C# 7.3+ compiler so you can omit
  50. /// the explicit method call, and write eg "fixed (char* c = builder)"
  51. /// </summary>
  52. public ref char GetPinnableReference()
  53. {
  54. return ref MemoryMarshal.GetReference(_chars);
  55. }
  56. /// <summary>
  57. /// Get a pinnable reference to the builder.
  58. /// </summary>
  59. /// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param>
  60. public ref char GetPinnableReference(bool terminate)
  61. {
  62. if (terminate)
  63. {
  64. EnsureCapacity(Length + 1);
  65. _chars[Length] = '\0';
  66. }
  67. return ref MemoryMarshal.GetReference(_chars);
  68. }
  69. public ref char this[int index]
  70. {
  71. get
  72. {
  73. Debug.Assert(index < _pos);
  74. return ref _chars[index];
  75. }
  76. }
  77. public override string ToString()
  78. {
  79. string s = _chars.Slice(0, _pos).ToString();
  80. Dispose();
  81. return s;
  82. }
  83. /// <summary>Returns the underlying storage of the builder.</summary>
  84. public Span<char> RawChars => _chars;
  85. /// <summary>
  86. /// Returns a span around the contents of the builder.
  87. /// </summary>
  88. /// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param>
  89. public ReadOnlySpan<char> AsSpan(bool terminate)
  90. {
  91. if (terminate)
  92. {
  93. EnsureCapacity(Length + 1);
  94. _chars[Length] = '\0';
  95. }
  96. return _chars.Slice(0, _pos);
  97. }
  98. public ReadOnlySpan<char> AsSpan() => _chars.Slice(0, _pos);
  99. public ReadOnlySpan<char> AsSpan(int start) => _chars.Slice(start, _pos - start);
  100. public ReadOnlySpan<char> AsSpan(int start, int length) => _chars.Slice(start, length);
  101. public bool TryCopyTo(Span<char> destination, out int charsWritten)
  102. {
  103. if (_chars.Slice(0, _pos).TryCopyTo(destination))
  104. {
  105. charsWritten = _pos;
  106. Dispose();
  107. return true;
  108. }
  109. else
  110. {
  111. charsWritten = 0;
  112. Dispose();
  113. return false;
  114. }
  115. }
  116. public void Insert(int index, char value, int count)
  117. {
  118. if (_pos > _chars.Length - count)
  119. {
  120. Grow(count);
  121. }
  122. int remaining = _pos - index;
  123. _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));
  124. _chars.Slice(index, count).Fill(value);
  125. _pos += count;
  126. }
  127. public void Insert(int index, string? s)
  128. {
  129. if (s == null)
  130. {
  131. return;
  132. }
  133. int count = s.Length;
  134. if (_pos > (_chars.Length - count))
  135. {
  136. Grow(count);
  137. }
  138. int remaining = _pos - index;
  139. _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));
  140. s
  141. #if !NET
  142. .AsSpan()
  143. #endif
  144. .CopyTo(_chars.Slice(index));
  145. _pos += count;
  146. }
  147. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  148. public void Append(char c)
  149. {
  150. int pos = _pos;
  151. Span<char> chars = _chars;
  152. if ((uint)pos < (uint)chars.Length)
  153. {
  154. chars[pos] = c;
  155. _pos = pos + 1;
  156. }
  157. else
  158. {
  159. GrowAndAppend(c);
  160. }
  161. }
  162. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  163. public void Append(string? s)
  164. {
  165. if (s == null)
  166. {
  167. return;
  168. }
  169. int pos = _pos;
  170. if (s.Length == 1 && (uint)pos < (uint)_chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc.
  171. {
  172. _chars[pos] = s[0];
  173. _pos = pos + 1;
  174. }
  175. else
  176. {
  177. AppendSlow(s);
  178. }
  179. }
  180. private void AppendSlow(string s)
  181. {
  182. int pos = _pos;
  183. if (pos > _chars.Length - s.Length)
  184. {
  185. Grow(s.Length);
  186. }
  187. s
  188. #if !NET
  189. .AsSpan()
  190. #endif
  191. .CopyTo(_chars.Slice(pos));
  192. _pos += s.Length;
  193. }
  194. public void Append(char c, int count)
  195. {
  196. if (_pos > _chars.Length - count)
  197. {
  198. Grow(count);
  199. }
  200. Span<char> dst = _chars.Slice(_pos, count);
  201. for (int i = 0; i < dst.Length; i++)
  202. {
  203. dst[i] = c;
  204. }
  205. _pos += count;
  206. }
  207. public unsafe void Append(char* value, int length)
  208. {
  209. int pos = _pos;
  210. if (pos > _chars.Length - length)
  211. {
  212. Grow(length);
  213. }
  214. Span<char> dst = _chars.Slice(_pos, length);
  215. for (int i = 0; i < dst.Length; i++)
  216. {
  217. dst[i] = *value++;
  218. }
  219. _pos += length;
  220. }
  221. public void Append(scoped ReadOnlySpan<char> value)
  222. {
  223. int pos = _pos;
  224. if (pos > _chars.Length - value.Length)
  225. {
  226. Grow(value.Length);
  227. }
  228. value.CopyTo(_chars.Slice(_pos));
  229. _pos += value.Length;
  230. }
  231. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  232. public Span<char> AppendSpan(int length)
  233. {
  234. int origPos = _pos;
  235. if (origPos > _chars.Length - length)
  236. {
  237. Grow(length);
  238. }
  239. _pos = origPos + length;
  240. return _chars.Slice(origPos, length);
  241. }
  242. [MethodImpl(MethodImplOptions.NoInlining)]
  243. private void GrowAndAppend(char c)
  244. {
  245. Grow(1);
  246. Append(c);
  247. }
  248. /// <summary>
  249. /// Resize the internal buffer either by doubling current buffer size or
  250. /// by adding <paramref name="additionalCapacityBeyondPos"/> to
  251. /// <see cref="_pos"/> whichever is greater.
  252. /// </summary>
  253. /// <param name="additionalCapacityBeyondPos">
  254. /// Number of chars requested beyond current position.
  255. /// </param>
  256. [MethodImpl(MethodImplOptions.NoInlining)]
  257. private void Grow(int additionalCapacityBeyondPos)
  258. {
  259. Debug.Assert(additionalCapacityBeyondPos > 0);
  260. Debug.Assert(_pos > _chars.Length - additionalCapacityBeyondPos, "Grow called incorrectly, no resize is needed.");
  261. const uint ArrayMaxLength = 0x7FFFFFC7; // same as Array.MaxLength
  262. // Increase to at least the required size (_pos + additionalCapacityBeyondPos), but try
  263. // to double the size if possible, bounding the doubling to not go beyond the max array length.
  264. int newCapacity = (int)Math.Max(
  265. (uint)(_pos + additionalCapacityBeyondPos),
  266. Math.Min((uint)_chars.Length * 2, ArrayMaxLength));
  267. // Make sure to let Rent throw an exception if the caller has a bug and the desired capacity is negative.
  268. // This could also go negative if the actual required length wraps around.
  269. char[] poolArray = ArrayPool<char>.Shared.Rent(newCapacity);
  270. _chars.Slice(0, _pos).CopyTo(poolArray);
  271. char[]? toReturn = _arrayToReturnToPool;
  272. _chars = _arrayToReturnToPool = poolArray;
  273. if (toReturn != null)
  274. {
  275. ArrayPool<char>.Shared.Return(toReturn);
  276. }
  277. }
  278. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  279. public void Dispose()
  280. {
  281. char[]? toReturn = _arrayToReturnToPool;
  282. this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again
  283. if (toReturn != null)
  284. {
  285. ArrayPool<char>.Shared.Return(toReturn);
  286. }
  287. }
  288. }
  289. }