Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added [Memory|Span]Owner<T>.DangerousGetArray #3530

Merged

Conversation

Sergio0694
Copy link
Member

@Sergio0694 Sergio0694 commented Oct 16, 2020

PR Type

What kind of change does this PR introduce?

  • Feature

What is the current behavior?

There is currently no way to get the underlying T[] array from a MemoryOwner<T> or SpanOwner<T> instance without going through some hoops that are very inconvenient (and which are only possible for MemoryOwner<T>). Being able to use the array directly is necessary when working with some older APIs that don't offer a Span<T> or Memory<T> overload.

What is the new behavior?

This PR introduces a new DangerousGetArray method that mirrors the MemoryMarshal.TryGetArray method and works on MemoryOwner<T> and SpanOwner<T> instances. I've removed the try pattern since here the types guarantee that the underlying memory store will always be an array. The methods are called Dangerous___ because using the array is potentially dangerous in case a user keeps the array after disposing the original owner, as it means that that array might've been rented to some other consumer, so using it could lead to unexpected behavior. The methods are not inherently dangerous per se.

API surface

namespace Microsoft.Toolkit.HighPerformance.Buffers
{
    public sealed class MemoryOwner<T>
    {
        public ArraySegment<T> DangerousGetArray();
    }

    public readonly ref struct SpanOwner<T>
    {
        public ArraySegment<T> DangerousGetArray();
    }
}

Example usage

Suppose we have a Person class with string Name, string Surname and int Age properties, and we want to calculate an MD5 hash with the current state of the class. This was originally asked by a user in the C# Discord server (here).

public static string GetMD5Hash(Person person)
{
    using var buffer = new ArrayPoolBufferWriter<byte>();

    buffer.Write<char>(person.Name);
    buffer.Write<char>(person.Surname);
    buffer.Write(person.Age);

    using SpanOwner<byte> hash = SpanOwner<byte>.Allocate(16);

    using var md5 = MD5.Create();

    md5.TryComputeHash(buffer.WrittenSpan, hash.Span, out _);

    return BitConverter.ToString(hash.DangerousGetArray().Array!, 0, 16);
}

You can see how here we can leverage the new DangerousGetArray API to get the underlying array to use with the BitConverter.ToString API, which doesn't have an overload accepting a ReadOnlySpan<byte>. The same goes for many other existing APIs that only accept an array as input data instead of the new memory APIs.

PR Checklist

Please check if your PR fulfills the following requirements:

  • Tested code with current supported SDKs
  • Pull Request has been submitted to the documentation repository instructions. Link:
  • Sample in sample app has been added / updated (for bug fixes / features)
  • Tests for the changes have been added (for bug fixes / features) (if applicable)
  • Header has been added to all new source files (run build/UpdateHeaders.bat)
  • Contains NO breaking changes

@Sergio0694 Sergio0694 added feature 💡 improvements ✨ high-performance 🚂 Issues/PRs for the Microsoft.Toolkit.HighPerformance package .NET Components which are .NET based (non UWP specific) labels Oct 16, 2020
@Sergio0694 Sergio0694 added this to the 7.0 milestone Oct 16, 2020
@Sergio0694 Sergio0694 added this to In progress in Features 7.0 via automation Oct 16, 2020
@ghost
Copy link

ghost commented Oct 16, 2020

Thanks Sergio0694 for opening a Pull Request! The reviewers will test the PR and highlight if there is any conflict or changes required. If the PR is approved we will proceed to merge the pull request 🙌

@ghost
Copy link

ghost commented Nov 12, 2020

Hello @michael-hawker!

Because this pull request has the auto merge label, I will be glad to assist with helping to merge this pull request once all check-in policies pass.

p.s. you can customize the way I help with merging this pull request, such as holding this pull request until a specific person approves. Simply @mention me (@msftbot) and give me an instruction to get started! Learn more here.

@michael-hawker
Copy link
Member

@msftbot auto merge if @vgromfeld or @azchohfi also approve.

@ghost
Copy link

ghost commented Nov 12, 2020

Hello @michael-hawker!

Because you've given me some instructions on how to help merge this pull request, I'll be modifying my merge approach. Here's how I understand your requirements for merging this pull request:

If this doesn't seem right to you, you can tell me to cancel these instructions and use the auto-merge policy that has been configured for this repository. Try telling me "forget everything I just told you".

Features 7.0 automation moved this from In progress to Reviewer approved Nov 12, 2020
@ghost ghost merged commit 72d6847 into CommunityToolkit:master Nov 12, 2020
Features 7.0 automation moved this from Reviewer approved to Done Nov 12, 2020
This pull request was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
auto merge ⚡ feature 💡 high-performance 🚂 Issues/PRs for the Microsoft.Toolkit.HighPerformance package improvements ✨ .NET Components which are .NET based (non UWP specific)
Projects
No open projects
Features 7.0
  
Done
Development

Successfully merging this pull request may close these issues.

None yet

3 participants