Buffer.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. // RichTextKit
  2. // Copyright © 2019-2020 Topten Software. All Rights Reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. // not use this product except in compliance with the License. You may obtain
  6. // a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. // License for the specific language governing permissions and limitations
  14. // under the License.
  15. using System;
  16. using System.Collections;
  17. using System.Collections.Generic;
  18. using System.Diagnostics;
  19. using System.Runtime.CompilerServices;
  20. namespace Topten.RichTextKit.Utils
  21. {
  22. /// <summary>
  23. /// A growable array of elements of type `T`
  24. /// </summary>
  25. /// <typeparam name="T">The buffer element type</typeparam>
  26. [DebuggerDisplay("Length = {Length}")]
  27. public class Buffer<T> : IEnumerable<T>, IEnumerable
  28. {
  29. /// <summary>
  30. /// Constructs a new buffer.
  31. /// </summary>
  32. public Buffer()
  33. {
  34. // Create initial array
  35. _data = new T[32];
  36. }
  37. /// <summary>
  38. /// The data held by this buffer
  39. /// </summary>
  40. T[] _data;
  41. /// <summary>
  42. /// The data held by this buffer
  43. /// </summary>
  44. public T[] Underlying => _data;
  45. /// <summary>
  46. /// The used length of the buffer
  47. /// </summary>
  48. [DebuggerBrowsable(DebuggerBrowsableState.Never)]
  49. int _length;
  50. /// <summary>
  51. /// Gets or sets the length of the buffer
  52. /// </summary>
  53. /// <remarks>
  54. /// The internal buffer will be grown if the new length is larger
  55. /// than the current buffer size.
  56. /// </remarks>
  57. public int Length
  58. {
  59. get => _length;
  60. set
  61. {
  62. // Now grow buffer
  63. if (!GrowBuffer(value))
  64. {
  65. // If the length is increasing, but we didn't re-size the buffer
  66. // then we need to clear the new elements.
  67. if (value > _length)
  68. {
  69. Array.Clear(_data, _length, value - _length);
  70. }
  71. }
  72. // Store new length
  73. _length = value;
  74. }
  75. }
  76. /// <summary>
  77. /// Ensures the buffer has sufficient capacity
  78. /// </summary>
  79. /// <param name="requiredLength"></param>
  80. /// <returns></returns>
  81. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  82. bool GrowBuffer(int requiredLength)
  83. {
  84. if (requiredLength <= _data.Length)
  85. return false;
  86. // Work out new length
  87. int newLength;
  88. if (_data.Length < 1048576)
  89. {
  90. // Below 1MB, grow by doubling...
  91. newLength = _data.Length * 2;
  92. }
  93. else
  94. {
  95. // otherwise grow by 1mb at a time...
  96. newLength = _data.Length + 1048576;
  97. }
  98. // Make sure we're allocating enough
  99. if (newLength < requiredLength)
  100. newLength = requiredLength;
  101. // Allocate new buffer, only copying _length, not Data.Length
  102. var newData = new T[requiredLength];
  103. Array.Copy(_data, 0, newData, 0, _length);
  104. _data = newData;
  105. return true;
  106. }
  107. /// <summary>
  108. /// Clears the buffer, keeping the internally allocated array.
  109. /// </summary>
  110. public void Clear()
  111. {
  112. _length = 0;
  113. }
  114. /// <summary>
  115. /// Inserts room into the buffer
  116. /// </summary>
  117. /// <param name="position">The position to insert at</param>
  118. /// <param name="length">The length to insert</param>
  119. /// <param name="clear">Whether to clear the inserted part of the buffer</param>
  120. /// <returns>The new buffer area as a slice</returns>
  121. public Slice<T> Insert(int position, int length, bool clear = true)
  122. {
  123. // Grow internal buffer?
  124. GrowBuffer(_length + length);
  125. // Shuffle existing to make room for inserted data
  126. if (position < _length)
  127. {
  128. Array.Copy(_data, position, _data, position + length, _length - position);
  129. }
  130. // Update the length
  131. _length += length;
  132. // Clear it?
  133. if (clear)
  134. Array.Clear(_data, position, length);
  135. // Return slice
  136. return SubSlice(position, length);
  137. }
  138. /// <summary>
  139. /// Insert a slice of data into this buffer
  140. /// </summary>
  141. /// <param name="position">The position to insert at</param>
  142. /// <param name="data">The data to insert</param>
  143. /// <returns>The newly inserted data as a slice</returns>
  144. public Slice<T> Insert(int position, Slice<T> data)
  145. {
  146. // Make room
  147. var slice = Insert(position, data.Length, false);
  148. // Copy in the source slice
  149. Array.Copy(data.Underlying, data.Start, _data, position, data.Length);
  150. // Return slice
  151. return slice;
  152. }
  153. /// <summary>
  154. /// Adds to the buffer, returning a slice of requested size
  155. /// </summary>
  156. /// <param name="length">Number of elements to add</param>
  157. /// <param name="clear">True to clear the content; otherwise false</param>
  158. /// <returns>A slice representing the allocated elements.</returns>
  159. public Slice<T> Add(int length, bool clear = true)
  160. {
  161. return Insert(_length, length, clear);
  162. }
  163. /// <summary>
  164. /// Add a slice of data to this buffer.
  165. /// </summary>
  166. /// <param name="slice">The slice to be added</param>
  167. /// <returns>A slice representing the added elements.</returns>
  168. public Slice<T> Add(Slice<T> slice)
  169. {
  170. var pos = _length;
  171. // Grow internal buffer?
  172. GrowBuffer(_length + slice.Length);
  173. _length += slice.Length;
  174. // Copy in the slice
  175. Array.Copy(slice.Underlying, slice.Start, _data, pos, slice.Length);
  176. // Return position
  177. return SubSlice(pos, slice.Length);
  178. }
  179. /// <summary>
  180. /// Delete a section of the buffer
  181. /// </summary>
  182. /// <param name="from">The position to delete from</param>
  183. /// <param name="length">The length to of the deletion</param>
  184. public void Delete(int from, int length)
  185. {
  186. // Clamp to buffer size
  187. if (from >= _length)
  188. return;
  189. if (from + length >= _length)
  190. length = _length - from;
  191. // Shuffle trailing data
  192. if (from + length < _length)
  193. {
  194. Array.Copy(_data, from + length, _data, from, _length - (from + length));
  195. }
  196. // Update length
  197. _length -= length;
  198. }
  199. /// <summary>
  200. /// Gets a reference to an element in the buffer
  201. /// </summary>
  202. /// <param name="index">The element index</param>
  203. /// <returns>A reference to the element value.</returns>
  204. public ref T this[int index]
  205. {
  206. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  207. get
  208. {
  209. if (index < 0 || index >= _length)
  210. throw new ArgumentOutOfRangeException(nameof(index));
  211. return ref _data[index];
  212. }
  213. }
  214. /// <summary>
  215. /// Returns a range within this buffer as a <see cref="Slice{T}"/>
  216. /// </summary>
  217. /// <param name="start">Start offset of the slice</param>
  218. /// <param name="length">Length of the slice</param>
  219. /// <returns>A slice for the specified sub-range</returns>
  220. public Slice<T> SubSlice(int start, int length)
  221. {
  222. if (start < 0 || start + length > _length)
  223. {
  224. throw new ArgumentOutOfRangeException($"Invalid buffer slice range ({start},{length}) with buffer length of {_length}");
  225. }
  226. return new Slice<T>(_data, start, length);
  227. }
  228. /// <summary>
  229. /// Returns the entire buffer contents as a <see cref="Slice{T}"/>
  230. /// </summary>
  231. /// <returns>A Slice</returns>
  232. public Slice<T> AsSlice()
  233. {
  234. return SubSlice(0, _length);
  235. }
  236. /// <summary>
  237. /// Split the utf32 buffer on a codepoint type
  238. /// </summary>
  239. /// <param name="delim">The delimiter</param>
  240. /// <returns>An enumeration of slices</returns>
  241. public IEnumerable<Slice<T>> Split(T delim)
  242. {
  243. int start = 0;
  244. for (int i = 0; i < Length; i++)
  245. {
  246. if (_data[i].Equals(delim))
  247. {
  248. yield return SubSlice(start, i - start);
  249. start = i + 1;
  250. }
  251. }
  252. yield return SubSlice(start, Length - start);
  253. }
  254. /// <summary>
  255. /// Split the utf32 buffer on a codepoint type
  256. /// </summary>
  257. /// <param name="delim">The delimiter to split on</param>
  258. /// <returns>An enumeration of offset/length for each range</returns>
  259. public IEnumerable<(int Offset, int Length)> GetRanges(T delim)
  260. {
  261. int start = 0;
  262. for (int i = 0; i < Length; i++)
  263. {
  264. if (_data[i].Equals(delim))
  265. {
  266. yield return (start, i - start);
  267. start = i + 1;
  268. }
  269. }
  270. yield return (start, Length - start);
  271. }
  272. /// <summary>
  273. /// Replaces all instances of a value in the buffer with another value
  274. /// </summary>
  275. /// <param name="oldValue">The value to replace</param>
  276. /// <param name="newValue">The new value</param>
  277. /// <returns>The number of replacements made</returns>
  278. public int Replace(T oldValue, T newValue)
  279. {
  280. int count = 0;
  281. for (int i = 0; i < Length; i++)
  282. {
  283. if (_data[i].Equals(oldValue))
  284. {
  285. _data[i] = newValue;
  286. count++;
  287. }
  288. }
  289. return count;
  290. }
  291. IEnumerator<T> IEnumerable<T>.GetEnumerator()
  292. {
  293. return new ArraySliceEnumerator<T>(_data, 0, _length);
  294. }
  295. IEnumerator IEnumerable.GetEnumerator()
  296. {
  297. return new ArraySliceEnumerator<T>(_data, 0, _length);
  298. }
  299. }
  300. }