Span.Fast.cs 17 KB

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