ArraySegment.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. /*============================================================
  5. **
  6. **
  7. **
  8. ** Purpose: Convenient wrapper for an array, an offset, and
  9. ** a count. Ideally used in streams & collections.
  10. ** Net Classes will consume an array of these.
  11. **
  12. **
  13. ===========================================================*/
  14. using System.Collections;
  15. using System.Collections.Generic;
  16. using System.Diagnostics;
  17. namespace System
  18. {
  19. // Note: users should make sure they copy the fields out of an ArraySegment onto their stack
  20. // then validate that the fields describe valid bounds within the array. This must be done
  21. // because assignments to value types are not atomic, and also because one thread reading
  22. // three fields from an ArraySegment may not see the same ArraySegment from one call to another
  23. // (ie, users could assign a new value to the old location).
  24. [Serializable]
  25. [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
  26. public readonly struct ArraySegment<T> : IList<T>, IReadOnlyList<T>
  27. {
  28. // Do not replace the array allocation with Array.Empty. We don't want to have the overhead of
  29. // instantiating another generic type in addition to ArraySegment<T> for new type parameters.
  30. #pragma warning disable CA1825
  31. public static ArraySegment<T> Empty { get; } = new ArraySegment<T>(new T[0]);
  32. #pragma warning restore CA1825
  33. private readonly T[]? _array; // Do not rename (binary serialization)
  34. private readonly int _offset; // Do not rename (binary serialization)
  35. private readonly int _count; // Do not rename (binary serialization)
  36. public ArraySegment(T[] array)
  37. {
  38. if (array == null)
  39. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  40. _array = array;
  41. _offset = 0;
  42. _count = array.Length;
  43. }
  44. public ArraySegment(T[] array, int offset, int count)
  45. {
  46. // Validate arguments, check is minimal instructions with reduced branching for inlinable fast-path
  47. // Negative values discovered though conversion to high values when converted to unsigned
  48. // Failure should be rare and location determination and message is delegated to failure functions
  49. if (array == null || (uint)offset > (uint)array.Length || (uint)count > (uint)(array.Length - offset))
  50. ThrowHelper.ThrowArraySegmentCtorValidationFailedExceptions(array, offset, count);
  51. _array = array;
  52. _offset = offset;
  53. _count = count;
  54. }
  55. public T[]? Array => _array;
  56. public int Offset => _offset;
  57. public int Count => _count;
  58. public T this[int index]
  59. {
  60. get
  61. {
  62. if ((uint)index >= (uint)_count)
  63. {
  64. ThrowHelper.ThrowArgumentOutOfRange_IndexException();
  65. }
  66. return _array![_offset + index];
  67. }
  68. set
  69. {
  70. if ((uint)index >= (uint)_count)
  71. {
  72. ThrowHelper.ThrowArgumentOutOfRange_IndexException();
  73. }
  74. _array![_offset + index] = value;
  75. }
  76. }
  77. public Enumerator GetEnumerator()
  78. {
  79. ThrowInvalidOperationIfDefault();
  80. return new Enumerator(this);
  81. }
  82. public override int GetHashCode() =>
  83. _array is null ? 0 : HashCode.Combine(_offset, _count, _array.GetHashCode());
  84. public void CopyTo(T[] destination) => CopyTo(destination, 0);
  85. public void CopyTo(T[] destination, int destinationIndex)
  86. {
  87. ThrowInvalidOperationIfDefault();
  88. System.Array.Copy(_array!, _offset, destination, destinationIndex, _count);
  89. }
  90. public void CopyTo(ArraySegment<T> destination)
  91. {
  92. ThrowInvalidOperationIfDefault();
  93. destination.ThrowInvalidOperationIfDefault();
  94. if (_count > destination._count)
  95. {
  96. ThrowHelper.ThrowArgumentException_DestinationTooShort();
  97. }
  98. System.Array.Copy(_array!, _offset, destination._array!, destination._offset, _count);
  99. }
  100. public override bool Equals(object? obj) =>
  101. obj is ArraySegment<T> && Equals((ArraySegment<T>)obj);
  102. public bool Equals(ArraySegment<T> obj) =>
  103. obj._array == _array && obj._offset == _offset && obj._count == _count;
  104. public ArraySegment<T> Slice(int index)
  105. {
  106. ThrowInvalidOperationIfDefault();
  107. if ((uint)index > (uint)_count)
  108. {
  109. ThrowHelper.ThrowArgumentOutOfRange_IndexException();
  110. }
  111. return new ArraySegment<T>(_array!, _offset + index, _count - index);
  112. }
  113. public ArraySegment<T> Slice(int index, int count)
  114. {
  115. ThrowInvalidOperationIfDefault();
  116. if ((uint)index > (uint)_count || (uint)count > (uint)(_count - index))
  117. {
  118. ThrowHelper.ThrowArgumentOutOfRange_IndexException();
  119. }
  120. return new ArraySegment<T>(_array!, _offset + index, count);
  121. }
  122. public T[] ToArray()
  123. {
  124. ThrowInvalidOperationIfDefault();
  125. if (_count == 0)
  126. {
  127. return Empty._array!;
  128. }
  129. var array = new T[_count];
  130. System.Array.Copy(_array!, _offset, array, 0, _count);
  131. return array;
  132. }
  133. public static bool operator ==(ArraySegment<T> a, ArraySegment<T> b) => a.Equals(b);
  134. public static bool operator !=(ArraySegment<T> a, ArraySegment<T> b) => !(a == b);
  135. public static implicit operator ArraySegment<T>(T[] array) => array != null ? new ArraySegment<T>(array) : default;
  136. #region IList<T>
  137. T IList<T>.this[int index]
  138. {
  139. get
  140. {
  141. ThrowInvalidOperationIfDefault();
  142. if (index < 0 || index >= _count)
  143. ThrowHelper.ThrowArgumentOutOfRange_IndexException();
  144. return _array![_offset + index];
  145. }
  146. set
  147. {
  148. ThrowInvalidOperationIfDefault();
  149. if (index < 0 || index >= _count)
  150. ThrowHelper.ThrowArgumentOutOfRange_IndexException();
  151. _array![_offset + index] = value;
  152. }
  153. }
  154. int IList<T>.IndexOf(T item)
  155. {
  156. ThrowInvalidOperationIfDefault();
  157. int index = System.Array.IndexOf<T>(_array!, item, _offset, _count);
  158. Debug.Assert(index == -1 ||
  159. (index >= _offset && index < _offset + _count));
  160. return index >= 0 ? index - _offset : -1;
  161. }
  162. void IList<T>.Insert(int index, T item) => ThrowHelper.ThrowNotSupportedException();
  163. void IList<T>.RemoveAt(int index) => ThrowHelper.ThrowNotSupportedException();
  164. #endregion
  165. #region IReadOnlyList<T>
  166. T IReadOnlyList<T>.this[int index]
  167. {
  168. get
  169. {
  170. ThrowInvalidOperationIfDefault();
  171. if (index < 0 || index >= _count)
  172. ThrowHelper.ThrowArgumentOutOfRange_IndexException();
  173. return _array![_offset + index];
  174. }
  175. }
  176. #endregion IReadOnlyList<T>
  177. #region ICollection<T>
  178. bool ICollection<T>.IsReadOnly =>
  179. // the indexer setter does not throw an exception although IsReadOnly is true.
  180. // This is to match the behavior of arrays.
  181. true;
  182. void ICollection<T>.Add(T item) => ThrowHelper.ThrowNotSupportedException();
  183. void ICollection<T>.Clear() => ThrowHelper.ThrowNotSupportedException();
  184. bool ICollection<T>.Contains(T item)
  185. {
  186. ThrowInvalidOperationIfDefault();
  187. int index = System.Array.IndexOf<T>(_array!, item, _offset, _count);
  188. Debug.Assert(index == -1 ||
  189. (index >= _offset && index < _offset + _count));
  190. return index >= 0;
  191. }
  192. bool ICollection<T>.Remove(T item)
  193. {
  194. ThrowHelper.ThrowNotSupportedException();
  195. return default;
  196. }
  197. #endregion
  198. #region IEnumerable<T>
  199. IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
  200. #endregion
  201. #region IEnumerable
  202. IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
  203. #endregion
  204. private void ThrowInvalidOperationIfDefault()
  205. {
  206. if (_array == null)
  207. {
  208. ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray);
  209. }
  210. }
  211. public struct Enumerator : IEnumerator<T>
  212. {
  213. private readonly T[]? _array;
  214. private readonly int _start;
  215. private readonly int _end; // cache Offset + Count, since it's a little slow
  216. private int _current;
  217. internal Enumerator(ArraySegment<T> arraySegment)
  218. {
  219. Debug.Assert(arraySegment.Array != null);
  220. Debug.Assert(arraySegment.Offset >= 0);
  221. Debug.Assert(arraySegment.Count >= 0);
  222. Debug.Assert(arraySegment.Offset + arraySegment.Count <= arraySegment.Array.Length);
  223. _array = arraySegment.Array;
  224. _start = arraySegment.Offset;
  225. _end = arraySegment.Offset + arraySegment.Count;
  226. _current = arraySegment.Offset - 1;
  227. }
  228. public bool MoveNext()
  229. {
  230. if (_current < _end)
  231. {
  232. _current++;
  233. return _current < _end;
  234. }
  235. return false;
  236. }
  237. public T Current
  238. {
  239. get
  240. {
  241. if (_current < _start)
  242. ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
  243. if (_current >= _end)
  244. ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
  245. return _array![_current];
  246. }
  247. }
  248. object? IEnumerator.Current => Current;
  249. void IEnumerator.Reset()
  250. {
  251. _current = _start - 1;
  252. }
  253. public void Dispose()
  254. {
  255. }
  256. }
  257. }
  258. }