Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit 6626bcc

Browse files
benaadamsjkotas
authored andcommitted
Add TryGetOwnedMemory (dotnet/coreclr#16455)
* Add TryGetOwnedMemory * Feedback * spelling Signed-off-by: dotnet-bot-corefx-mirror <dotnet-bot@microsoft.com>
1 parent fdeedd7 commit 6626bcc

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/Common/src/CoreLib/System/Runtime/InteropServices/MemoryMarshal.cs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,30 @@ public static bool TryGetArray<T>(ReadOnlyMemory<T> readOnlyMemory, out ArraySeg
3939
return false;
4040
}
4141

42+
/// <summary>
43+
/// Get a <see cref="OwnedMemory{T}"/> from the underlying memory.
44+
/// If unable to get the <typeparamref name="TOwner"/>, return false with a default <typeparamref name="TOwner"/>.
45+
/// </summary>
46+
public static bool TryGetOwnedMemory<T, TOwner>(ReadOnlyMemory<T> readOnlyMemory, out TOwner ownedMemory)
47+
where TOwner : OwnedMemory<T>
48+
{
49+
TOwner owner; // Use register for null comparison rather than byref
50+
ownedMemory = owner = readOnlyMemory.GetObjectStartLength(out int index, out int length) as TOwner;
51+
return !ReferenceEquals(owner, null);
52+
}
53+
54+
/// <summary>
55+
/// Get a <see cref="OwnedMemory{T}"/> and <param name="index">, <param name="length"> on the <see cref="OwnedMemory{T}"/> from the underlying memory.
56+
/// If unable to get the <typeparamref name="TOwner"/>, return false with a default <typeparamref name="TOwner"/>.
57+
/// </summary>
58+
public static bool TryGetOwnedMemory<T, TOwner>(ReadOnlyMemory<T> readOnlyMemory, out TOwner ownedMemory, out int index, out int length)
59+
where TOwner : OwnedMemory<T>
60+
{
61+
TOwner owner; // Use register for null comparison rather than byref
62+
ownedMemory = owner = readOnlyMemory.GetObjectStartLength(out index, out length) as TOwner;
63+
return !ReferenceEquals(owner, null);
64+
}
65+
4266
/// <summary>
4367
/// Creates an <see cref="IEnumerable{T}"/> view of the given <paramref name="memory" /> to allow
4468
/// the <paramref name="memory" /> to be used in existing APIs that take an <see cref="IEnumerable{T}"/>.

0 commit comments

Comments
 (0)