Memory.cs 24 KB

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