Span.Fast.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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.Diagnostics;
  5. using System.Runtime.CompilerServices;
  6. using System.Runtime.Versioning;
  7. using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
  8. using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
  9. using Internal.Runtime.CompilerServices;
  10. #pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
  11. #if BIT64
  12. using nuint = System.UInt64;
  13. #else
  14. using nuint = System.UInt32;
  15. #endif
  16. namespace System
  17. {
  18. /// <summary>
  19. /// Span represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed
  20. /// or native memory, or to memory allocated on the stack. It is type- and memory-safe.
  21. /// </summary>
  22. [NonVersionable]
  23. public readonly ref partial struct Span<T>
  24. {
  25. /// <summary>A byref or a native ptr.</summary>
  26. internal readonly ByReference<T> _pointer;
  27. /// <summary>The number of elements this Span contains.</summary>
  28. #if PROJECTN
  29. [Bound]
  30. #endif
  31. private readonly int _length;
  32. /// <summary>
  33. /// Creates a new span over the entirety of the target array.
  34. /// </summary>
  35. /// <param name="array">The target array.</param>
  36. /// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
  37. /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
  38. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  39. public Span(T[] array)
  40. {
  41. if (array == null)
  42. {
  43. this = default;
  44. return; // returns default
  45. }
  46. if (default(T) == null && array.GetType() != typeof(T[]))
  47. ThrowHelper.ThrowArrayTypeMismatchException();
  48. _pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()));
  49. _length = array.Length;
  50. }
  51. /// <summary>
  52. /// Creates a new span over the portion of the target array beginning
  53. /// at 'start' index and ending at 'end' index (exclusive).
  54. /// </summary>
  55. /// <param name="array">The target array.</param>
  56. /// <param name="start">The index at which to begin the span.</param>
  57. /// <param name="length">The number of items in the span.</param>
  58. /// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
  59. /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
  60. /// <exception cref="System.ArgumentOutOfRangeException">
  61. /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;=Length).
  62. /// </exception>
  63. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  64. public Span(T[] array, int start, int length)
  65. {
  66. if (array == null)
  67. {
  68. if (start != 0 || length != 0)
  69. ThrowHelper.ThrowArgumentOutOfRangeException();
  70. this = default;
  71. return; // returns default
  72. }
  73. if (default(T) == null && array.GetType() != typeof(T[]))
  74. ThrowHelper.ThrowArrayTypeMismatchException();
  75. #if BIT64
  76. // See comment in Span<T>.Slice for how this works.
  77. if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)array.Length)
  78. ThrowHelper.ThrowArgumentOutOfRangeException();
  79. #else
  80. if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
  81. ThrowHelper.ThrowArgumentOutOfRangeException();
  82. #endif
  83. _pointer = new ByReference<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start));
  84. _length = length;
  85. }
  86. /// <summary>
  87. /// Creates a new span over the target unmanaged buffer. Clearly this
  88. /// is quite dangerous, because we are creating arbitrarily typed T's
  89. /// out of a void*-typed block of memory. And the length is not checked.
  90. /// But if this creation is correct, then all subsequent uses are correct.
  91. /// </summary>
  92. /// <param name="pointer">An unmanaged pointer to memory.</param>
  93. /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
  94. /// <exception cref="System.ArgumentException">
  95. /// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory.
  96. /// </exception>
  97. /// <exception cref="System.ArgumentOutOfRangeException">
  98. /// Thrown when the specified <paramref name="length"/> is negative.
  99. /// </exception>
  100. [CLSCompliant(false)]
  101. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  102. public unsafe Span(void* pointer, int length)
  103. {
  104. if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
  105. ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
  106. if (length < 0)
  107. ThrowHelper.ThrowArgumentOutOfRangeException();
  108. _pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref *(byte*)pointer));
  109. _length = length;
  110. }
  111. // Constructor for internal use only.
  112. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  113. internal Span(ref T ptr, int length)
  114. {
  115. Debug.Assert(length >= 0);
  116. _pointer = new ByReference<T>(ref ptr);
  117. _length = length;
  118. }
  119. /// <summary>
  120. /// Returns a reference to specified element of the Span.
  121. /// </summary>
  122. /// <param name="index"></param>
  123. /// <returns></returns>
  124. /// <exception cref="System.IndexOutOfRangeException">
  125. /// Thrown when index less than 0 or index greater than or equal to Length
  126. /// </exception>
  127. public ref T this[int index]
  128. {
  129. #if PROJECTN
  130. [BoundsChecking]
  131. get
  132. {
  133. return ref Unsafe.Add(ref _pointer.Value, index);
  134. }
  135. #else
  136. [Intrinsic]
  137. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  138. [NonVersionable]
  139. get
  140. {
  141. if ((uint)index >= (uint)_length)
  142. ThrowHelper.ThrowIndexOutOfRangeException();
  143. return ref Unsafe.Add(ref _pointer.Value, index);
  144. }
  145. #endif
  146. }
  147. public ref T this[Index index]
  148. {
  149. get
  150. {
  151. // Evaluate the actual index first because it helps performance
  152. int actualIndex = index.FromEnd ? _length - index.Value : index.Value;
  153. return ref this [actualIndex];
  154. }
  155. }
  156. public Span<T> this[Range range]
  157. {
  158. get
  159. {
  160. int start = range.Start.FromEnd ? _length - range.Start.Value : range.Start.Value;
  161. int end = range.End.FromEnd ? _length - range.End.Value : range.End.Value;
  162. return Slice(start, end - start);
  163. }
  164. }
  165. /// <summary>
  166. /// Returns a reference to the 0th element of the Span. If the Span is empty, returns null reference.
  167. /// It can be used for pinning and is required to support the use of span within a fixed statement.
  168. /// </summary>
  169. [EditorBrowsable(EditorBrowsableState.Never)]
  170. public unsafe ref T GetPinnableReference()
  171. {
  172. // Ensure that the native code has just one forward branch that is predicted-not-taken.
  173. ref T ret = ref Unsafe.AsRef<T>(null);
  174. if (_length != 0) ret = ref _pointer.Value;
  175. return ref ret;
  176. }
  177. /// <summary>
  178. /// Clears the contents of this span.
  179. /// </summary>
  180. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  181. public void Clear()
  182. {
  183. if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
  184. {
  185. SpanHelpers.ClearWithReferences(ref Unsafe.As<T, IntPtr>(ref _pointer.Value), (nuint)_length * (nuint)(Unsafe.SizeOf<T>() / sizeof(nuint)));
  186. }
  187. else
  188. {
  189. SpanHelpers.ClearWithoutReferences(ref Unsafe.As<T, byte>(ref _pointer.Value), (nuint)_length * (nuint)Unsafe.SizeOf<T>());
  190. }
  191. }
  192. /// <summary>
  193. /// Fills the contents of this span with the given value.
  194. /// </summary>
  195. public void Fill(T value)
  196. {
  197. if (Unsafe.SizeOf<T>() == 1)
  198. {
  199. uint length = (uint)_length;
  200. if (length == 0)
  201. return;
  202. T tmp = value; // Avoid taking address of the "value" argument. It would regress performance of the loop below.
  203. Unsafe.InitBlockUnaligned(ref Unsafe.As<T, byte>(ref _pointer.Value), Unsafe.As<T, byte>(ref tmp), length);
  204. }
  205. else
  206. {
  207. // Do all math as nuint to avoid unnecessary 64->32->64 bit integer truncations
  208. nuint length = (uint)_length;
  209. if (length == 0)
  210. return;
  211. ref T r = ref _pointer.Value;
  212. // TODO: Create block fill for value types of power of two sizes e.g. 2,4,8,16
  213. nuint elementSize = (uint)Unsafe.SizeOf<T>();
  214. nuint i = 0;
  215. for (; i < (length & ~(nuint)7); i += 8)
  216. {
  217. Unsafe.AddByteOffset<T>(ref r, (i + 0) * elementSize) = value;
  218. Unsafe.AddByteOffset<T>(ref r, (i + 1) * elementSize) = value;
  219. Unsafe.AddByteOffset<T>(ref r, (i + 2) * elementSize) = value;
  220. Unsafe.AddByteOffset<T>(ref r, (i + 3) * elementSize) = value;
  221. Unsafe.AddByteOffset<T>(ref r, (i + 4) * elementSize) = value;
  222. Unsafe.AddByteOffset<T>(ref r, (i + 5) * elementSize) = value;
  223. Unsafe.AddByteOffset<T>(ref r, (i + 6) * elementSize) = value;
  224. Unsafe.AddByteOffset<T>(ref r, (i + 7) * elementSize) = value;
  225. }
  226. if (i < (length & ~(nuint)3))
  227. {
  228. Unsafe.AddByteOffset<T>(ref r, (i + 0) * elementSize) = value;
  229. Unsafe.AddByteOffset<T>(ref r, (i + 1) * elementSize) = value;
  230. Unsafe.AddByteOffset<T>(ref r, (i + 2) * elementSize) = value;
  231. Unsafe.AddByteOffset<T>(ref r, (i + 3) * elementSize) = value;
  232. i += 4;
  233. }
  234. for (; i < length; i++)
  235. {
  236. Unsafe.AddByteOffset<T>(ref r, i * elementSize) = value;
  237. }
  238. }
  239. }
  240. /// <summary>
  241. /// Copies the contents of this span into destination span. If the source
  242. /// and destinations overlap, this method behaves as if the original values in
  243. /// a temporary location before the destination is overwritten.
  244. /// </summary>
  245. /// <param name="destination">The span to copy items into.</param>
  246. /// <exception cref="System.ArgumentException">
  247. /// Thrown when the destination Span is shorter than the source Span.
  248. /// </exception>
  249. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  250. public void CopyTo(Span<T> destination)
  251. {
  252. // Using "if (!TryCopyTo(...))" results in two branches: one for the length
  253. // check, and one for the result of TryCopyTo. Since these checks are equivalent,
  254. // we can optimize by performing the check once ourselves then calling Memmove directly.
  255. if ((uint)_length <= (uint)destination.Length)
  256. {
  257. Buffer.Memmove(ref destination._pointer.Value, ref _pointer.Value, (nuint)_length);
  258. }
  259. else
  260. {
  261. ThrowHelper.ThrowArgumentException_DestinationTooShort();
  262. }
  263. }
  264. /// <summary>
  265. /// Copies the contents of this span into destination span. If the source
  266. /// and destinations overlap, this method behaves as if the original values in
  267. /// a temporary location before the destination is overwritten.
  268. /// </summary>
  269. /// <param name="destination">The span to copy items into.</param>
  270. /// <returns>If the destination span is shorter than the source span, this method
  271. /// return false and no data is written to the destination.</returns>
  272. public bool TryCopyTo(Span<T> destination)
  273. {
  274. bool retVal = false;
  275. if ((uint)_length <= (uint)destination.Length)
  276. {
  277. Buffer.Memmove(ref destination._pointer.Value, ref _pointer.Value, (nuint)_length);
  278. retVal = true;
  279. }
  280. return retVal;
  281. }
  282. /// <summary>
  283. /// Returns true if left and right point at the same memory and have the same length. Note that
  284. /// this does *not* check to see if the *contents* are equal.
  285. /// </summary>
  286. public static bool operator ==(Span<T> left, Span<T> right)
  287. {
  288. return left._length == right._length && Unsafe.AreSame<T>(ref left._pointer.Value, ref right._pointer.Value);
  289. }
  290. /// <summary>
  291. /// Defines an implicit conversion of a <see cref="Span{T}"/> to a <see cref="ReadOnlySpan{T}"/>
  292. /// </summary>
  293. public static implicit operator ReadOnlySpan<T>(Span<T> span) => new ReadOnlySpan<T>(ref span._pointer.Value, span._length);
  294. /// <summary>
  295. /// For <see cref="Span{Char}"/>, returns a new instance of string that represents the characters pointed to by the span.
  296. /// Otherwise, returns a <see cref="string"/> with the name of the type and the number of elements.
  297. /// </summary>
  298. public override string ToString()
  299. {
  300. if (typeof(T) == typeof(char))
  301. {
  302. unsafe
  303. {
  304. fixed (char* src = &Unsafe.As<T, char>(ref _pointer.Value))
  305. return new string(src, 0, _length);
  306. }
  307. }
  308. return string.Format("System.Span<{0}>[{1}]", typeof(T).Name, _length);
  309. }
  310. /// <summary>
  311. /// Forms a slice out of the given span, beginning at 'start'.
  312. /// </summary>
  313. /// <param name="start">The index at which to begin this slice.</param>
  314. /// <exception cref="System.ArgumentOutOfRangeException">
  315. /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;=Length).
  316. /// </exception>
  317. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  318. public Span<T> Slice(int start)
  319. {
  320. if ((uint)start > (uint)_length)
  321. ThrowHelper.ThrowArgumentOutOfRangeException();
  322. return new Span<T>(ref Unsafe.Add(ref _pointer.Value, start), _length - start);
  323. }
  324. /// <summary>
  325. /// Forms a slice out of the given span, beginning at 'start', of given length
  326. /// </summary>
  327. /// <param name="start">The index at which to begin this slice.</param>
  328. /// <param name="length">The desired length for the slice (exclusive).</param>
  329. /// <exception cref="System.ArgumentOutOfRangeException">
  330. /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;=Length).
  331. /// </exception>
  332. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  333. public Span<T> Slice(int start, int length)
  334. {
  335. #if BIT64
  336. // Since start and length are both 32-bit, their sum can be computed across a 64-bit domain
  337. // without loss of fidelity. The cast to uint before the cast to ulong ensures that the
  338. // extension from 32- to 64-bit is zero-extending rather than sign-extending. The end result
  339. // of this is that if either input is negative or if the input sum overflows past Int32.MaxValue,
  340. // that information is captured correctly in the comparison against the backing _length field.
  341. // We don't use this same mechanism in a 32-bit process due to the overhead of 64-bit arithmetic.
  342. if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)_length)
  343. ThrowHelper.ThrowArgumentOutOfRangeException();
  344. #else
  345. if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
  346. ThrowHelper.ThrowArgumentOutOfRangeException();
  347. #endif
  348. return new Span<T>(ref Unsafe.Add(ref _pointer.Value, start), length);
  349. }
  350. /// <summary>
  351. /// Copies the contents of this span into a new array. This heap
  352. /// allocates, so should generally be avoided, however it is sometimes
  353. /// necessary to bridge the gap with APIs written in terms of arrays.
  354. /// </summary>
  355. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  356. public T[] ToArray()
  357. {
  358. if (_length == 0)
  359. return Array.Empty<T>();
  360. var destination = new T[_length];
  361. Buffer.Memmove(ref Unsafe.As<byte, T>(ref destination.GetRawSzArrayData()), ref _pointer.Value, (nuint)_length);
  362. return destination;
  363. }
  364. }
  365. }