ArraySegment.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. public static ArraySegment<T> Empty { get; } = new ArraySegment<T>(new T[0]);
  31. private readonly T[] _array; // Do not rename (binary serialization)
  32. private readonly int _offset; // Do not rename (binary serialization)
  33. private readonly int _count; // Do not rename (binary serialization)
  34. public ArraySegment(T[] array)
  35. {
  36. if (array == null)
  37. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  38. _array = array;
  39. _offset = 0;
  40. _count = array.Length;
  41. }
  42. public ArraySegment(T[] array, int offset, int count)
  43. {
  44. // Validate arguments, check is minimal instructions with reduced branching for inlinable fast-path
  45. // Negative values discovered though conversion to high values when converted to unsigned
  46. // Failure should be rare and location determination and message is delegated to failure functions
  47. if (array == null || (uint)offset > (uint)array.Length || (uint)count > (uint)(array.Length - offset))
  48. ThrowHelper.ThrowArraySegmentCtorValidationFailedExceptions(array, offset, count);
  49. _array = array;
  50. _offset = offset;
  51. _count = count;
  52. }
  53. public T[] Array => _array;
  54. public int Offset => _offset;
  55. public int Count => _count;
  56. public T this[int index]
  57. {
  58. get
  59. {
  60. if ((uint)index >= (uint)_count)
  61. {
  62. ThrowHelper.ThrowArgumentOutOfRange_IndexException();
  63. }
  64. return _array[_offset + index];
  65. }
  66. set
  67. {
  68. if ((uint)index >= (uint)_count)
  69. {
  70. ThrowHelper.ThrowArgumentOutOfRange_IndexException();
  71. }
  72. _array[_offset + index] = value;
  73. }
  74. }
  75. public Enumerator GetEnumerator()
  76. {
  77. ThrowInvalidOperationIfDefault();
  78. return new Enumerator(this);
  79. }
  80. public override int GetHashCode()
  81. {
  82. if (_array == null)
  83. {
  84. return 0;
  85. }
  86. int hash = 5381;
  87. hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _offset);
  88. hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _count);
  89. // The array hash is expected to be an evenly-distributed mixture of bits,
  90. // so rather than adding the cost of another rotation we just xor it.
  91. hash ^= _array.GetHashCode();
  92. return hash;
  93. }
  94. public void CopyTo(T[] destination) => CopyTo(destination, 0);
  95. public void CopyTo(T[] destination, int destinationIndex)
  96. {
  97. ThrowInvalidOperationIfDefault();
  98. System.Array.Copy(_array, _offset, destination, destinationIndex, _count);
  99. }
  100. public void CopyTo(ArraySegment<T> destination)
  101. {
  102. ThrowInvalidOperationIfDefault();
  103. destination.ThrowInvalidOperationIfDefault();
  104. if (_count > destination._count)
  105. {
  106. ThrowHelper.ThrowArgumentException_DestinationTooShort();
  107. }
  108. System.Array.Copy(_array, _offset, destination._array, destination._offset, _count);
  109. }
  110. public override bool Equals(object obj)
  111. {
  112. if (obj is ArraySegment<T>)
  113. return Equals((ArraySegment<T>)obj);
  114. else
  115. return false;
  116. }
  117. public bool Equals(ArraySegment<T> obj)
  118. {
  119. return obj._array == _array && obj._offset == _offset && obj._count == _count;
  120. }
  121. public ArraySegment<T> Slice(int index)
  122. {
  123. ThrowInvalidOperationIfDefault();
  124. if ((uint)index > (uint)_count)
  125. {
  126. ThrowHelper.ThrowArgumentOutOfRange_IndexException();
  127. }
  128. return new ArraySegment<T>(_array, _offset + index, _count - index);
  129. }
  130. public ArraySegment<T> Slice(int index, int count)
  131. {
  132. ThrowInvalidOperationIfDefault();
  133. if ((uint)index > (uint)_count || (uint)count > (uint)(_count - index))
  134. {
  135. ThrowHelper.ThrowArgumentOutOfRange_IndexException();
  136. }
  137. return new ArraySegment<T>(_array, _offset + index, count);
  138. }
  139. public T[] ToArray()
  140. {
  141. ThrowInvalidOperationIfDefault();
  142. if (_count == 0)
  143. {
  144. return Empty._array;
  145. }
  146. var array = new T[_count];
  147. System.Array.Copy(_array, _offset, array, 0, _count);
  148. return array;
  149. }
  150. public static bool operator ==(ArraySegment<T> a, ArraySegment<T> b)
  151. {
  152. return a.Equals(b);
  153. }
  154. public static bool operator !=(ArraySegment<T> a, ArraySegment<T> b)
  155. {
  156. return !(a == b);
  157. }
  158. public static implicit operator ArraySegment<T>(T[] array) => array != null ? new ArraySegment<T>(array) : default;
  159. #region IList<T>
  160. T IList<T>.this[int index]
  161. {
  162. get
  163. {
  164. ThrowInvalidOperationIfDefault();
  165. if (index < 0 || index >= _count)
  166. ThrowHelper.ThrowArgumentOutOfRange_IndexException();
  167. return _array[_offset + index];
  168. }
  169. set
  170. {
  171. ThrowInvalidOperationIfDefault();
  172. if (index < 0 || index >= _count)
  173. ThrowHelper.ThrowArgumentOutOfRange_IndexException();
  174. _array[_offset + index] = value;
  175. }
  176. }
  177. int IList<T>.IndexOf(T item)
  178. {
  179. ThrowInvalidOperationIfDefault();
  180. int index = System.Array.IndexOf<T>(_array, item, _offset, _count);
  181. Debug.Assert(index == -1 ||
  182. (index >= _offset && index < _offset + _count));
  183. return index >= 0 ? index - _offset : -1;
  184. }
  185. void IList<T>.Insert(int index, T item)
  186. {
  187. ThrowHelper.ThrowNotSupportedException();
  188. }
  189. void IList<T>.RemoveAt(int index)
  190. {
  191. ThrowHelper.ThrowNotSupportedException();
  192. }
  193. #endregion
  194. #region IReadOnlyList<T>
  195. T IReadOnlyList<T>.this[int index]
  196. {
  197. get
  198. {
  199. ThrowInvalidOperationIfDefault();
  200. if (index < 0 || index >= _count)
  201. ThrowHelper.ThrowArgumentOutOfRange_IndexException();
  202. return _array[_offset + index];
  203. }
  204. }
  205. #endregion IReadOnlyList<T>
  206. #region ICollection<T>
  207. bool ICollection<T>.IsReadOnly
  208. {
  209. get
  210. {
  211. // the indexer setter does not throw an exception although IsReadOnly is true.
  212. // This is to match the behavior of arrays.
  213. return true;
  214. }
  215. }
  216. void ICollection<T>.Add(T item)
  217. {
  218. ThrowHelper.ThrowNotSupportedException();
  219. }
  220. void ICollection<T>.Clear()
  221. {
  222. ThrowHelper.ThrowNotSupportedException();
  223. }
  224. bool ICollection<T>.Contains(T item)
  225. {
  226. ThrowInvalidOperationIfDefault();
  227. int index = System.Array.IndexOf<T>(_array, item, _offset, _count);
  228. Debug.Assert(index == -1 ||
  229. (index >= _offset && index < _offset + _count));
  230. return index >= 0;
  231. }
  232. bool ICollection<T>.Remove(T item)
  233. {
  234. ThrowHelper.ThrowNotSupportedException();
  235. return default;
  236. }
  237. #endregion
  238. #region IEnumerable<T>
  239. IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
  240. #endregion
  241. #region IEnumerable
  242. IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
  243. #endregion
  244. private void ThrowInvalidOperationIfDefault()
  245. {
  246. if (_array == null)
  247. {
  248. ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray);
  249. }
  250. }
  251. public struct Enumerator : IEnumerator<T>
  252. {
  253. private readonly T[] _array;
  254. private readonly int _start;
  255. private readonly int _end; // cache Offset + Count, since it's a little slow
  256. private int _current;
  257. internal Enumerator(ArraySegment<T> arraySegment)
  258. {
  259. Debug.Assert(arraySegment.Array != null);
  260. Debug.Assert(arraySegment.Offset >= 0);
  261. Debug.Assert(arraySegment.Count >= 0);
  262. Debug.Assert(arraySegment.Offset + arraySegment.Count <= arraySegment.Array.Length);
  263. _array = arraySegment.Array;
  264. _start = arraySegment.Offset;
  265. _end = arraySegment.Offset + arraySegment.Count;
  266. _current = arraySegment.Offset - 1;
  267. }
  268. public bool MoveNext()
  269. {
  270. if (_current < _end)
  271. {
  272. _current++;
  273. return (_current < _end);
  274. }
  275. return false;
  276. }
  277. public T Current
  278. {
  279. get
  280. {
  281. if (_current < _start)
  282. ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
  283. if (_current >= _end)
  284. ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
  285. return _array[_current];
  286. }
  287. }
  288. object IEnumerator.Current => Current;
  289. void IEnumerator.Reset()
  290. {
  291. _current = _start - 1;
  292. }
  293. public void Dispose()
  294. {
  295. }
  296. }
  297. }
  298. }