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.
6 using System.Runtime.CompilerServices;
8 namespace System.Buffers
11 /// Manager of <see cref="System.Memory{T}"/> that provides the implementation.
13 public abstract class MemoryManager<T> : IMemoryOwner<T>, IPinnable
16 /// Returns a <see cref="System.Memory{T}"/>.
18 public virtual Memory<T> Memory => new Memory<T>(this, GetSpan().Length);
21 /// Returns a span wrapping the underlying memory.
23 public abstract Span<T> GetSpan();
26 /// Returns a handle to the memory that has been pinned and hence its address can be taken.
28 /// <param name="elementIndex">The offset to the element within the memory at which the returned <see cref="MemoryHandle"/> points to. (default = 0)</param>
29 public abstract MemoryHandle Pin(int elementIndex = 0);
32 /// Lets the garbage collector know that the object is free to be moved now.
34 public abstract void Unpin();
37 /// Returns a <see cref="System.Memory{T}"/> for the current <see cref="MemoryManager{T}"/>.
39 /// <param name="length">The element count in the memory, starting at offset 0.</param>
40 [MethodImpl(MethodImplOptions.AggressiveInlining)]
41 protected Memory<T> CreateMemory(int length) => new Memory<T>(this, length);
44 /// Returns a <see cref="System.Memory{T}"/> for the current <see cref="MemoryManager{T}"/>.
46 /// <param name="start">The offset to the element which the returned memory starts at.</param>
47 /// <param name="length">The element count in the memory, starting at element offset <paramref name="start"/>.</param>
48 [MethodImpl(MethodImplOptions.AggressiveInlining)]
49 protected Memory<T> CreateMemory(int start, int length) => new Memory<T>(this, start, length);
52 /// Returns an array segment.
53 /// <remarks>Returns the default array segment if not overriden.</remarks>
55 protected internal virtual bool TryGetArray(out ArraySegment<T> segment)
62 /// Implements IDisposable.
64 void IDisposable.Dispose()
66 Dispose(disposing: true);
67 GC.SuppressFinalize(this);
71 /// Clean up of any leftover managed and unmanaged resources.
73 protected abstract void Dispose(bool disposing);