Add TryGetOwnedMemory (#16455)
authorBen Adams <thundercat@illyriad.co.uk>
Wed, 21 Feb 2018 01:56:02 +0000 (01:56 +0000)
committerStephen Toub <stoub@microsoft.com>
Wed, 21 Feb 2018 01:56:02 +0000 (20:56 -0500)
* Add TryGetOwnedMemory

* Feedback

* spelling

src/mscorlib/shared/System/Runtime/InteropServices/MemoryMarshal.cs

index cc815d0..c0c270d 100644 (file)
@@ -40,6 +40,30 @@ namespace System.Runtime.InteropServices
         }
 
         /// <summary>
+        /// Get a <see cref="OwnedMemory{T}"/> from the underlying memory.
+        /// If unable to get the <typeparamref name="TOwner"/>, return false with a default <typeparamref name="TOwner"/>.
+        /// </summary>
+        public static bool TryGetOwnedMemory<T, TOwner>(ReadOnlyMemory<T> readOnlyMemory, out TOwner ownedMemory)
+            where TOwner : OwnedMemory<T>
+        {
+            TOwner owner; // Use register for null comparison rather than byref
+            ownedMemory = owner = readOnlyMemory.GetObjectStartLength(out int index, out int length) as TOwner;
+            return !ReferenceEquals(owner, null);
+        }
+
+        /// <summary>
+        /// Get a <see cref="OwnedMemory{T}"/> and <param name="index">, <param name="length"> on the <see cref="OwnedMemory{T}"/> from the underlying memory.
+        /// If unable to get the <typeparamref name="TOwner"/>, return false with a default <typeparamref name="TOwner"/>.
+        /// </summary>
+        public static bool TryGetOwnedMemory<T, TOwner>(ReadOnlyMemory<T> readOnlyMemory, out TOwner ownedMemory, out int index, out int length)
+           where TOwner : OwnedMemory<T>
+        {
+            TOwner owner; // Use register for null comparison rather than byref
+            ownedMemory = owner = readOnlyMemory.GetObjectStartLength(out index, out length) as TOwner;
+            return !ReferenceEquals(owner, null);
+        }
+
+        /// <summary>
         /// Creates an <see cref="IEnumerable{T}"/> view of the given <paramref name="memory" /> to allow
         /// the <paramref name="memory" /> to be used in existing APIs that take an <see cref="IEnumerable{T}"/>.
         /// </summary>