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.
5 using System.ComponentModel;
6 using System.Diagnostics;
7 using System.Runtime.CompilerServices;
8 using System.Runtime.Versioning;
9 using Internal.Runtime.CompilerServices;
11 #pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
16 /// ReadOnlySpan represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed
17 /// or native memory, or to memory allocated on the stack. It is type- and memory-safe.
19 [DebuggerTypeProxy(typeof(SpanDebugView<>))]
20 [DebuggerDisplay("{DebuggerDisplay,nq}")]
22 public readonly ref struct ReadOnlySpan<T>
24 /// <summary>A byref or a native ptr.</summary>
25 internal readonly ByReference<T> _pointer;
26 /// <summary>The number of elements this ReadOnlySpan contains.</summary>
30 private readonly int _length;
33 /// Creates a new read-only span over the entirety of the target array.
35 /// <param name="array">The target array.</param>
36 /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
37 /// reference (Nothing in Visual Basic).</exception>
38 [MethodImpl(MethodImplOptions.AggressiveInlining)]
39 public ReadOnlySpan(T[] array)
42 ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
44 _pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()));
45 _length = array.Length;
49 /// Creates a new read-only span over the portion of the target array beginning
50 /// at 'start' index and ending at 'end' index (exclusive).
52 /// <param name="array">The target array.</param>
53 /// <param name="start">The index at which to begin the read-only span.</param>
54 /// <param name="length">The number of items in the read-only span.</param>
55 /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
56 /// reference (Nothing in Visual Basic).</exception>
57 /// <exception cref="System.ArgumentOutOfRangeException">
58 /// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
60 [MethodImpl(MethodImplOptions.AggressiveInlining)]
61 public ReadOnlySpan(T[] array, int start, int length)
64 ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
65 if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
66 ThrowHelper.ThrowArgumentOutOfRangeException();
68 _pointer = new ByReference<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start));
73 /// Creates a new read-only span over the target unmanaged buffer. Clearly this
74 /// is quite dangerous, because we are creating arbitrarily typed T's
75 /// out of a void*-typed block of memory. And the length is not checked.
76 /// But if this creation is correct, then all subsequent uses are correct.
78 /// <param name="pointer">An unmanaged pointer to memory.</param>
79 /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
80 /// <exception cref="System.ArgumentException">
81 /// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory.
83 /// <exception cref="System.ArgumentOutOfRangeException">
84 /// Thrown when the specified <paramref name="length"/> is negative.
87 [MethodImpl(MethodImplOptions.AggressiveInlining)]
88 public unsafe ReadOnlySpan(void* pointer, int length)
90 if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
91 ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
93 ThrowHelper.ThrowArgumentOutOfRangeException();
95 _pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref *(byte*)pointer));
100 /// Create a new read-only span over a portion of a regular managed object. This can be useful
101 /// if part of a managed object represents a "fixed array." This is dangerous because neither the
102 /// <paramref name="length"/> is checked, nor <paramref name="obj"/> being null, nor the fact that
103 /// "rawPointer" actually lies within <paramref name="obj"/>.
105 /// <param name="obj">The managed object that contains the data to span over.</param>
106 /// <param name="objectData">A reference to data within that object.</param>
107 /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
108 [MethodImpl(MethodImplOptions.AggressiveInlining)]
109 [EditorBrowsable(EditorBrowsableState.Never)]
110 public static ReadOnlySpan<T> DangerousCreate(object obj, ref T objectData, int length) => new ReadOnlySpan<T>(ref objectData, length);
112 // Constructor for internal use only.
113 [MethodImpl(MethodImplOptions.AggressiveInlining)]
114 internal ReadOnlySpan(ref T ptr, int length)
116 Debug.Assert(length >= 0);
118 _pointer = new ByReference<T>(ref ptr);
122 //Debugger Display = {T[length]}
123 private string DebuggerDisplay => string.Format("{{{0}[{1}]}}", typeof(T).Name, _length);
126 /// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element
127 /// would have been stored. Such a reference can be used for pinning but must never be dereferenced.
129 [MethodImpl(MethodImplOptions.AggressiveInlining)]
130 [EditorBrowsable(EditorBrowsableState.Never)]
131 internal ref readonly T DangerousGetPinnableReference()
133 return ref _pointer.Value;
137 /// The number of items in the read-only span.
149 /// Returns true if Length is 0.
161 /// Returns the specified element of the read-only span.
163 /// <param name="index"></param>
164 /// <returns></returns>
165 /// <exception cref="System.IndexOutOfRangeException">
166 /// Thrown when index less than 0 or index greater than or equal to Length
168 public ref readonly T this[int index]
174 return ref Unsafe.Add(ref _pointer.Value, index);
178 [MethodImpl(MethodImplOptions.AggressiveInlining)]
182 if ((uint)index >= (uint)_length)
183 ThrowHelper.ThrowIndexOutOfRangeException();
184 return ref Unsafe.Add(ref _pointer.Value, index);
190 /// Copies the contents of this read-only span into destination span. If the source
191 /// and destinations overlap, this method behaves as if the original values in
192 /// a temporary location before the destination is overwritten.
194 /// <param name="destination">The span to copy items into.</param>
195 /// <exception cref="System.ArgumentException">
196 /// Thrown when the destination Span is shorter than the source Span.
199 public void CopyTo(Span<T> destination)
201 if (!TryCopyTo(destination))
202 ThrowHelper.ThrowArgumentException_DestinationTooShort();
205 /// Copies the contents of this read-only span into destination span. If the source
206 /// and destinations overlap, this method behaves as if the original values in
207 /// a temporary location before the destination is overwritten.
209 /// <returns>If the destination span is shorter than the source span, this method
210 /// return false and no data is written to the destination.</returns>
211 /// <param name="destination">The span to copy items into.</param>
212 public bool TryCopyTo(Span<T> destination)
214 if ((uint)_length > (uint)destination.Length)
217 Span.CopyTo<T>(ref destination.DangerousGetPinnableReference(), ref _pointer.Value, _length);
222 /// Returns true if left and right point at the same memory and have the same length. Note that
223 /// this does *not* check to see if the *contents* are equal.
225 public static bool operator ==(ReadOnlySpan<T> left, ReadOnlySpan<T> right)
227 return left._length == right._length && Unsafe.AreSame<T>(ref left._pointer.Value, ref right._pointer.Value);
231 /// Returns false if left and right point at the same memory and have the same length. Note that
232 /// this does *not* check to see if the *contents* are equal.
234 public static bool operator !=(ReadOnlySpan<T> left, ReadOnlySpan<T> right) => !(left == right);
237 /// This method is not supported as spans cannot be boxed. To compare two spans, use operator==.
238 /// <exception cref="System.NotSupportedException">
239 /// Always thrown by this method.
242 [Obsolete("Equals() on ReadOnlySpan will always throw an exception. Use == instead.")]
243 [EditorBrowsable(EditorBrowsableState.Never)]
244 public override bool Equals(object obj)
246 throw new NotSupportedException(SR.NotSupported_CannotCallEqualsOnSpan);
250 /// This method is not supported as spans cannot be boxed.
251 /// <exception cref="System.NotSupportedException">
252 /// Always thrown by this method.
255 [Obsolete("GetHashCode() on ReadOnlySpan will always throw an exception.")]
256 [EditorBrowsable(EditorBrowsableState.Never)]
257 public override int GetHashCode()
259 throw new NotSupportedException(SR.NotSupported_CannotCallGetHashCodeOnSpan);
263 /// Returns a <see cref="String"/> with the name of the type and the number of elements
265 public override string ToString() => "System.Span[" + Length.ToString() + "]";
268 /// Defines an implicit conversion of an array to a <see cref="ReadOnlySpan{T}"/>
270 public static implicit operator ReadOnlySpan<T>(T[] array) => array != null ? new ReadOnlySpan<T>(array) : default;
273 /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="ReadOnlySpan{T}"/>
275 public static implicit operator ReadOnlySpan<T>(ArraySegment<T> arraySegment)
276 => arraySegment.Array != null ? new ReadOnlySpan<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count) : default;
279 /// Forms a slice out of the given read-only span, beginning at 'start'.
281 /// <param name="start">The index at which to begin this slice.</param>
282 /// <exception cref="System.ArgumentOutOfRangeException">
283 /// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >=Length).
285 [MethodImpl(MethodImplOptions.AggressiveInlining)]
286 public ReadOnlySpan<T> Slice(int start)
288 if ((uint)start > (uint)_length)
289 ThrowHelper.ThrowArgumentOutOfRangeException();
291 return new ReadOnlySpan<T>(ref Unsafe.Add(ref _pointer.Value, start), _length - start);
295 /// Forms a slice out of the given read-only span, beginning at 'start', of given length
297 /// <param name="start">The index at which to begin this slice.</param>
298 /// <param name="length">The desired length for the slice (exclusive).</param>
299 /// <exception cref="System.ArgumentOutOfRangeException">
300 /// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
302 [MethodImpl(MethodImplOptions.AggressiveInlining)]
303 public ReadOnlySpan<T> Slice(int start, int length)
305 if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
306 ThrowHelper.ThrowArgumentOutOfRangeException();
308 return new ReadOnlySpan<T>(ref Unsafe.Add(ref _pointer.Value, start), length);
312 /// Copies the contents of this read-only span into a new array. This heap
313 /// allocates, so should generally be avoided, however it is sometimes
314 /// necessary to bridge the gap with APIs written in terms of arrays.
319 return Array.Empty<T>();
321 var destination = new T[_length];
322 Span.CopyTo<T>(ref Unsafe.As<byte, T>(ref destination.GetRawSzArrayData()), ref _pointer.Value, _length);
327 /// Returns a 0-length read-only span whose base is the null pointer.
329 public static ReadOnlySpan<T> Empty => default(ReadOnlySpan<T>);
331 /// <summary>Gets an enumerator for this span.</summary>
332 public Enumerator GetEnumerator() => new Enumerator(this);
334 /// <summary>Enumerates the elements of a <see cref="ReadOnlySpan{T}"/>.</summary>
335 public ref struct Enumerator
337 /// <summary>The span being enumerated.</summary>
338 private readonly ReadOnlySpan<T> _span;
339 /// <summary>The next index to yield.</summary>
342 /// <summary>Initialize the enumerator.</summary>
343 /// <param name="span">The span to enumerate.</param>
344 [MethodImpl(MethodImplOptions.AggressiveInlining)]
345 internal Enumerator(ReadOnlySpan<T> span)
351 /// <summary>Advances the enumerator to the next element of the span.</summary>
352 [MethodImpl(MethodImplOptions.AggressiveInlining)]
353 public bool MoveNext()
355 int index = _index + 1;
356 if (index < _span.Length)
365 /// <summary>Gets the element at the current position of the enumerator.</summary>
366 public ref readonly T Current
368 [MethodImpl(MethodImplOptions.AggressiveInlining)]
369 get => ref _span[_index];