Skip to content

Change OwnedMemory Pin to take an optional integer offset #24126

@ahsonkhan

Description

@ahsonkhan

Related to https://github.com/dotnet/corefx/issues/24317 and dotnet/corefx#24323 (comment)

the scenario is I use OwnedMemory and MemoryHandle directly, without using Memory, e.g. I implement my own Memory-like factory for spans. If we don't like AddOffset, we should add OwnedMemory.Pin overload that takes offset to the added to the pointer inside the handle.

API Proposal

Change:

namespace System.Buffers
{
    public abstract class OwnedMemory<T> : IDisposable, IRetainable 
    {
        public abstract MemoryHandle Pin();
    }
}

To:

namespace System.Buffers
{
    public abstract class OwnedMemory<T> : IDisposable, IRetainable 
    {
        public abstract MemoryHandle Pin(int offset = 0);
    }
}

Usage

Example from NativeOwnedMemory:

public override unsafe MemoryHandle Pin() => new MemoryHandle(this, (void*)_ptr);

Would become:

public override unsafe MemoryHandle Pin(int offset = 0) 
{
   void* pointer = (void*)((byte*)_ptr + offset);
   return new MemoryHandle(this, pointer);
}

The following can then be re-written from Memory.Retain:

if (_index < 0)
{
    memoryHandle = ((OwnedMemory<T>)_arrayOrOwnedMemory).Pin();
    memoryHandle.AddOffset((_index & RemoveOwnedFlagBitMask) * Unsafe.SizeOf<T>());
}

To:

if (_index < 0)
{
    memoryHandle = ((OwnedMemory<T>)_arrayOrOwnedMemory).Pin((_index & RemoveOwnedFlagBitMask) * Unsafe.SizeOf<T>());
}

We can then remove the internal AddOffset method here which was added in dotnet/corefx#24323.

cc @KrzysztofCwalina, @stephentoub, @karelz, @terrajobst, @pakrym

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions