Memory.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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.Buffers;
  5. using System.Diagnostics;
  6. using System.Runtime.CompilerServices;
  7. using System.Runtime.InteropServices;
  8. using System.Text;
  9. using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
  10. using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
  11. using Internal.Runtime.CompilerServices;
  12. #pragma warning disable SA1121 // explicitly using type aliases instead of built-in types
  13. #if BIT64
  14. using nuint = System.UInt64;
  15. #else // BIT64
  16. using nuint = System.UInt32;
  17. #endif // BIT64
  18. namespace System
  19. {
  20. /// <summary>
  21. /// Memory represents a contiguous region of arbitrary memory similar to <see cref="Span{T}"/>.
  22. /// Unlike <see cref="Span{T}"/>, it is not a byref-like type.
  23. /// </summary>
  24. [DebuggerTypeProxy(typeof(MemoryDebugView<>))]
  25. [DebuggerDisplay("{ToString(),raw}")]
  26. public readonly struct Memory<T> : IEquatable<Memory<T>>
  27. {
  28. // NOTE: With the current implementation, Memory<T> and ReadOnlyMemory<T> must have the same layout,
  29. // as code uses Unsafe.As to cast between them.
  30. // The highest order bit of _index is used to discern whether _object is a pre-pinned array.
  31. // (_index < 0) => _object is a pre-pinned array, so Pin() will not allocate a new GCHandle
  32. // (else) => Pin() needs to allocate a new GCHandle to pin the object.
  33. private readonly object? _object;
  34. private readonly int _index;
  35. private readonly int _length;
  36. /// <summary>
  37. /// Creates a new memory over the entirety of the target array.
  38. /// </summary>
  39. /// <param name="array">The target array.</param>
  40. /// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
  41. /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
  42. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  43. public Memory(T[]? array)
  44. {
  45. if (array == null)
  46. {
  47. this = default;
  48. return; // returns default
  49. }
  50. if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
  51. ThrowHelper.ThrowArrayTypeMismatchException();
  52. _object = array;
  53. _index = 0;
  54. _length = array.Length;
  55. }
  56. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  57. internal Memory(T[]? array, int start)
  58. {
  59. if (array == null)
  60. {
  61. if (start != 0)
  62. ThrowHelper.ThrowArgumentOutOfRangeException();
  63. this = default;
  64. return; // returns default
  65. }
  66. if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
  67. ThrowHelper.ThrowArrayTypeMismatchException();
  68. if ((uint)start > (uint)array.Length)
  69. ThrowHelper.ThrowArgumentOutOfRangeException();
  70. _object = array;
  71. _index = start;
  72. _length = array.Length - start;
  73. }
  74. /// <summary>
  75. /// Creates a new memory over the portion of the target array beginning
  76. /// at 'start' index and ending at 'end' index (exclusive).
  77. /// </summary>
  78. /// <param name="array">The target array.</param>
  79. /// <param name="start">The index at which to begin the memory.</param>
  80. /// <param name="length">The number of items in the memory.</param>
  81. /// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
  82. /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
  83. /// <exception cref="System.ArgumentOutOfRangeException">
  84. /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;Length).
  85. /// </exception>
  86. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  87. public Memory(T[]? array, int start, int length)
  88. {
  89. if (array == null)
  90. {
  91. if (start != 0 || length != 0)
  92. ThrowHelper.ThrowArgumentOutOfRangeException();
  93. this = default;
  94. return; // returns default
  95. }
  96. if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
  97. ThrowHelper.ThrowArrayTypeMismatchException();
  98. #if BIT64
  99. // See comment in Span<T>.Slice for how this works.
  100. if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)array.Length)
  101. ThrowHelper.ThrowArgumentOutOfRangeException();
  102. #else
  103. if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
  104. ThrowHelper.ThrowArgumentOutOfRangeException();
  105. #endif
  106. _object = array;
  107. _index = start;
  108. _length = length;
  109. }
  110. /// <summary>
  111. /// Creates a new memory from a memory manager that provides specific method implementations beginning
  112. /// at 0 index and ending at 'end' index (exclusive).
  113. /// </summary>
  114. /// <param name="manager">The memory manager.</param>
  115. /// <param name="length">The number of items in the memory.</param>
  116. /// <exception cref="System.ArgumentOutOfRangeException">
  117. /// Thrown when the specified <paramref name="length"/> is negative.
  118. /// </exception>
  119. /// <remarks>For internal infrastructure only</remarks>
  120. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  121. internal Memory(MemoryManager<T> manager, int length)
  122. {
  123. Debug.Assert(manager != null);
  124. if (length < 0)
  125. ThrowHelper.ThrowArgumentOutOfRangeException();
  126. _object = manager;
  127. _index = 0;
  128. _length = length;
  129. }
  130. /// <summary>
  131. /// Creates a new memory from a memory manager that provides specific method implementations beginning
  132. /// at 'start' index and ending at 'end' index (exclusive).
  133. /// </summary>
  134. /// <param name="manager">The memory manager.</param>
  135. /// <param name="start">The index at which to begin the memory.</param>
  136. /// <param name="length">The number of items in the memory.</param>
  137. /// <exception cref="System.ArgumentOutOfRangeException">
  138. /// Thrown when the specified <paramref name="start"/> or <paramref name="length"/> is negative.
  139. /// </exception>
  140. /// <remarks>For internal infrastructure only</remarks>
  141. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  142. internal Memory(MemoryManager<T> manager, int start, int length)
  143. {
  144. Debug.Assert(manager != null);
  145. if (length < 0 || start < 0)
  146. ThrowHelper.ThrowArgumentOutOfRangeException();
  147. _object = manager;
  148. _index = start;
  149. _length = length;
  150. }
  151. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  152. internal Memory(object? obj, int start, int length)
  153. {
  154. // No validation performed in release builds; caller must provide any necessary validation.
  155. // 'obj is T[]' below also handles things like int[] <-> uint[] being convertible
  156. Debug.Assert((obj == null)
  157. || (typeof(T) == typeof(char) && obj is string)
  158. #if FEATURE_UTF8STRING
  159. || ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && obj is Utf8String)
  160. #endif // FEATURE_UTF8STRING
  161. || (obj is T[])
  162. || (obj is MemoryManager<T>));
  163. _object = obj;
  164. _index = start;
  165. _length = length;
  166. }
  167. /// <summary>
  168. /// Defines an implicit conversion of an array to a <see cref="Memory{T}"/>
  169. /// </summary>
  170. public static implicit operator Memory<T>(T[]? array) => new Memory<T>(array);
  171. /// <summary>
  172. /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Memory{T}"/>
  173. /// </summary>
  174. public static implicit operator Memory<T>(ArraySegment<T> segment) => new Memory<T>(segment.Array, segment.Offset, segment.Count);
  175. /// <summary>
  176. /// Defines an implicit conversion of a <see cref="Memory{T}"/> to a <see cref="ReadOnlyMemory{T}"/>
  177. /// </summary>
  178. public static implicit operator ReadOnlyMemory<T>(Memory<T> memory) =>
  179. Unsafe.As<Memory<T>, ReadOnlyMemory<T>>(ref memory);
  180. /// <summary>
  181. /// Returns an empty <see cref="Memory{T}"/>
  182. /// </summary>
  183. public static Memory<T> Empty => default;
  184. /// <summary>
  185. /// The number of items in the memory.
  186. /// </summary>
  187. public int Length => _length;
  188. /// <summary>
  189. /// Returns true if Length is 0.
  190. /// </summary>
  191. public bool IsEmpty => _length == 0;
  192. /// <summary>
  193. /// For <see cref="Memory{Char}"/>, returns a new instance of string that represents the characters pointed to by the memory.
  194. /// Otherwise, returns a <see cref="string"/> with the name of the type and the number of elements.
  195. /// </summary>
  196. public override string ToString()
  197. {
  198. if (typeof(T) == typeof(char))
  199. {
  200. return (_object is string str) ? str.Substring(_index, _length) : Span.ToString();
  201. }
  202. #if FEATURE_UTF8STRING
  203. else if (typeof(T) == typeof(Char8))
  204. {
  205. // TODO_UTF8STRING: Call into optimized transcoding routine when it's available.
  206. Span<T> span = Span;
  207. return Encoding.UTF8.GetString(new ReadOnlySpan<byte>(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length));
  208. }
  209. #endif // FEATURE_UTF8STRING
  210. return string.Format("System.Memory<{0}>[{1}]", typeof(T).Name, _length);
  211. }
  212. /// <summary>
  213. /// Forms a slice out of the given memory, beginning at 'start'.
  214. /// </summary>
  215. /// <param name="start">The index at which to begin this slice.</param>
  216. /// <exception cref="System.ArgumentOutOfRangeException">
  217. /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;Length).
  218. /// </exception>
  219. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  220. public Memory<T> Slice(int start)
  221. {
  222. if ((uint)start > (uint)_length)
  223. {
  224. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
  225. }
  226. // It is expected for _index + start to be negative if the memory is already pre-pinned.
  227. return new Memory<T>(_object, _index + start, _length - start);
  228. }
  229. /// <summary>
  230. /// Forms a slice out of the given memory, beginning at 'start', of given length
  231. /// </summary>
  232. /// <param name="start">The index at which to begin this slice.</param>
  233. /// <param name="length">The desired length for the slice (exclusive).</param>
  234. /// <exception cref="System.ArgumentOutOfRangeException">
  235. /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;Length).
  236. /// </exception>
  237. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  238. public Memory<T> Slice(int start, int length)
  239. {
  240. #if BIT64
  241. // See comment in Span<T>.Slice for how this works.
  242. if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)_length)
  243. ThrowHelper.ThrowArgumentOutOfRangeException();
  244. #else
  245. if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
  246. ThrowHelper.ThrowArgumentOutOfRangeException();
  247. #endif
  248. // It is expected for _index + start to be negative if the memory is already pre-pinned.
  249. return new Memory<T>(_object, _index + start, length);
  250. }
  251. /// <summary>
  252. /// Returns a span from the memory.
  253. /// </summary>
  254. public unsafe Span<T> Span
  255. {
  256. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  257. get
  258. {
  259. // This property getter has special support for returning a mutable Span<char> that wraps
  260. // an immutable String instance. This is obviously a dangerous feature and breaks type safety.
  261. // However, we need to handle the case where a ReadOnlyMemory<char> was created from a string
  262. // and then cast to a Memory<T>. Such a cast can only be done with unsafe or marshaling code,
  263. // in which case that's the dangerous operation performed by the dev, and we're just following
  264. // suit here to make it work as best as possible.
  265. ref T refToReturn = ref Unsafe.NullRef<T>();
  266. int lengthOfUnderlyingSpan = 0;
  267. // Copy this field into a local so that it can't change out from under us mid-operation.
  268. object? tmpObject = _object;
  269. if (tmpObject != null)
  270. {
  271. if (typeof(T) == typeof(char) && tmpObject.GetType() == typeof(string))
  272. {
  273. // Special-case string since it's the most common for ROM<char>.
  274. refToReturn = ref Unsafe.As<char, T>(ref Unsafe.As<string>(tmpObject).GetRawStringData());
  275. lengthOfUnderlyingSpan = Unsafe.As<string>(tmpObject).Length;
  276. }
  277. #if FEATURE_UTF8STRING
  278. else if ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && tmpObject.GetType() == typeof(Utf8String))
  279. {
  280. refToReturn = ref Unsafe.As<byte, T>(ref Unsafe.As<Utf8String>(tmpObject).DangerousGetMutableReference());
  281. lengthOfUnderlyingSpan = Unsafe.As<Utf8String>(tmpObject).Length;
  282. }
  283. #endif // FEATURE_UTF8STRING
  284. else if (RuntimeHelpers.ObjectHasComponentSize(tmpObject))
  285. {
  286. // We know the object is not null, it's not a string, and it is variable-length. The only
  287. // remaining option is for it to be a T[] (or a U[] which is blittable to T[], like int[]
  288. // and uint[]). Otherwise somebody used private reflection to set this field, and we're not
  289. // too worried about type safety violations at this point.
  290. // 'tmpObject is T[]' below also handles things like int[] <-> uint[] being convertible
  291. Debug.Assert(tmpObject is T[]);
  292. refToReturn = ref Unsafe.As<byte, T>(ref Unsafe.As<T[]>(tmpObject).GetRawSzArrayData());
  293. lengthOfUnderlyingSpan = Unsafe.As<T[]>(tmpObject).Length;
  294. }
  295. else
  296. {
  297. // We know the object is not null, and it's not variable-length, so it must be a MemoryManager<T>.
  298. // Otherwise somebody used private reflection to set this field, and we're not too worried about
  299. // type safety violations at that point. Note that it can't be a MemoryManager<U>, even if U and
  300. // T are blittable (e.g., MemoryManager<int> to MemoryManager<uint>), since there exists no
  301. // constructor or other public API which would allow such a conversion.
  302. Debug.Assert(tmpObject is MemoryManager<T>);
  303. Span<T> memoryManagerSpan = Unsafe.As<MemoryManager<T>>(tmpObject).GetSpan();
  304. refToReturn = ref MemoryMarshal.GetReference(memoryManagerSpan);
  305. lengthOfUnderlyingSpan = memoryManagerSpan.Length;
  306. }
  307. // If the Memory<T> or ReadOnlyMemory<T> instance is torn, this property getter has undefined behavior.
  308. // We try to detect this condition and throw an exception, but it's possible that a torn struct might
  309. // appear to us to be valid, and we'll return an undesired span. Such a span is always guaranteed at
  310. // least to be in-bounds when compared with the original Memory<T> instance, so using the span won't
  311. // AV the process.
  312. nuint desiredStartIndex = (uint)_index & (uint)ReadOnlyMemory<T>.RemoveFlagsBitMask;
  313. int desiredLength = _length;
  314. #if BIT64
  315. // See comment in Span<T>.Slice for how this works.
  316. if ((ulong)desiredStartIndex + (ulong)(uint)desiredLength > (ulong)(uint)lengthOfUnderlyingSpan)
  317. {
  318. ThrowHelper.ThrowArgumentOutOfRangeException();
  319. }
  320. #else
  321. if ((uint)desiredStartIndex > (uint)lengthOfUnderlyingSpan || (uint)desiredLength > (uint)(lengthOfUnderlyingSpan - desiredStartIndex))
  322. {
  323. ThrowHelper.ThrowArgumentOutOfRangeException();
  324. }
  325. #endif
  326. refToReturn = ref Unsafe.Add(ref refToReturn, (IntPtr)(void*)desiredStartIndex);
  327. lengthOfUnderlyingSpan = desiredLength;
  328. }
  329. return new Span<T>(ref refToReturn, lengthOfUnderlyingSpan);
  330. }
  331. }
  332. /// <summary>
  333. /// Copies the contents of the memory into the destination. If the source
  334. /// and destination overlap, this method behaves as if the original values are in
  335. /// a temporary location before the destination is overwritten.
  336. ///
  337. /// <param name="destination">The Memory to copy items into.</param>
  338. /// <exception cref="System.ArgumentException">
  339. /// Thrown when the destination is shorter than the source.
  340. /// </exception>
  341. /// </summary>
  342. public void CopyTo(Memory<T> destination) => Span.CopyTo(destination.Span);
  343. /// <summary>
  344. /// Copies the contents of the memory into the destination. If the source
  345. /// and destination overlap, this method behaves as if the original values are in
  346. /// a temporary location before the destination is overwritten.
  347. ///
  348. /// <returns>If the destination is shorter than the source, this method
  349. /// return false and no data is written to the destination.</returns>
  350. /// </summary>
  351. /// <param name="destination">The span to copy items into.</param>
  352. public bool TryCopyTo(Memory<T> destination) => Span.TryCopyTo(destination.Span);
  353. /// <summary>
  354. /// Creates a handle for the memory.
  355. /// The GC will not move the memory until the returned <see cref="MemoryHandle"/>
  356. /// is disposed, enabling taking and using the memory's address.
  357. /// <exception cref="System.ArgumentException">
  358. /// An instance with nonprimitive (non-blittable) members cannot be pinned.
  359. /// </exception>
  360. /// </summary>
  361. public unsafe MemoryHandle Pin()
  362. {
  363. // Just like the Span property getter, we have special support for a mutable Memory<char>
  364. // that wraps an immutable String instance. This might happen if a caller creates an
  365. // immutable ROM<char> wrapping a String, then uses Unsafe.As to create a mutable M<char>.
  366. // This needs to work, however, so that code that uses a single Memory<char> field to store either
  367. // a readable ReadOnlyMemory<char> or a writable Memory<char> can still be pinned and
  368. // used for interop purposes.
  369. // It's possible that the below logic could result in an AV if the struct
  370. // is torn. This is ok since the caller is expecting to use raw pointers,
  371. // and we're not required to keep this as safe as the other Span-based APIs.
  372. object? tmpObject = _object;
  373. if (tmpObject != null)
  374. {
  375. if (typeof(T) == typeof(char) && tmpObject is string s)
  376. {
  377. GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned);
  378. ref char stringData = ref Unsafe.Add(ref s.GetRawStringData(), _index);
  379. return new MemoryHandle(Unsafe.AsPointer(ref stringData), handle);
  380. }
  381. #if FEATURE_UTF8STRING
  382. else if ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && tmpObject is Utf8String utf8String)
  383. {
  384. GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned);
  385. ref byte stringData = ref utf8String.DangerousGetMutableReference(_index);
  386. return new MemoryHandle(Unsafe.AsPointer(ref stringData), handle);
  387. }
  388. #endif // FEATURE_UTF8STRING
  389. else if (RuntimeHelpers.ObjectHasComponentSize(tmpObject))
  390. {
  391. // 'tmpObject is T[]' below also handles things like int[] <-> uint[] being convertible
  392. Debug.Assert(tmpObject is T[]);
  393. // Array is already pre-pinned
  394. if (_index < 0)
  395. {
  396. void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref Unsafe.As<T[]>(tmpObject).GetRawSzArrayData()), _index & ReadOnlyMemory<T>.RemoveFlagsBitMask);
  397. return new MemoryHandle(pointer);
  398. }
  399. else
  400. {
  401. GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned);
  402. void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref Unsafe.As<T[]>(tmpObject).GetRawSzArrayData()), _index);
  403. return new MemoryHandle(pointer, handle);
  404. }
  405. }
  406. else
  407. {
  408. Debug.Assert(tmpObject is MemoryManager<T>);
  409. return Unsafe.As<MemoryManager<T>>(tmpObject).Pin(_index);
  410. }
  411. }
  412. return default;
  413. }
  414. /// <summary>
  415. /// Copies the contents from the memory into a new array. This heap
  416. /// allocates, so should generally be avoided, however it is sometimes
  417. /// necessary to bridge the gap with APIs written in terms of arrays.
  418. /// </summary>
  419. public T[] ToArray() => Span.ToArray();
  420. /// <summary>
  421. /// Determines whether the specified object is equal to the current object.
  422. /// Returns true if the object is Memory or ReadOnlyMemory and if both objects point to the same array and have the same length.
  423. /// </summary>
  424. [EditorBrowsable(EditorBrowsableState.Never)]
  425. public override bool Equals(object? obj)
  426. {
  427. if (obj is ReadOnlyMemory<T>)
  428. {
  429. return ((ReadOnlyMemory<T>)obj).Equals(this);
  430. }
  431. else if (obj is Memory<T> memory)
  432. {
  433. return Equals(memory);
  434. }
  435. else
  436. {
  437. return false;
  438. }
  439. }
  440. /// <summary>
  441. /// Returns true if the memory points to the same array and has the same length. Note that
  442. /// this does *not* check to see if the *contents* are equal.
  443. /// </summary>
  444. public bool Equals(Memory<T> other)
  445. {
  446. return
  447. _object == other._object &&
  448. _index == other._index &&
  449. _length == other._length;
  450. }
  451. /// <summary>
  452. /// Serves as the default hash function.
  453. /// </summary>
  454. [EditorBrowsable(EditorBrowsableState.Never)]
  455. public override int GetHashCode()
  456. {
  457. // We use RuntimeHelpers.GetHashCode instead of Object.GetHashCode because the hash
  458. // code is based on object identity and referential equality, not deep equality (as common with string).
  459. return (_object != null) ? HashCode.Combine(RuntimeHelpers.GetHashCode(_object), _index, _length) : 0;
  460. }
  461. }
  462. }