| | | 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 | | |
| | | 4 | | using System.Collections.Immutable; |
| | | 5 | | using System.IO; |
| | | 6 | | using System.Reflection.Metadata; |
| | | 7 | | |
| | | 8 | | namespace System.Reflection.Internal |
| | | 9 | | { |
| | | 10 | | /// <summary> |
| | | 11 | | /// Represents a disposable blob of memory accessed via unsafe pointer. |
| | | 12 | | /// </summary> |
| | | 13 | | internal abstract class AbstractMemoryBlock : IDisposable |
| | | 14 | | { |
| | | 15 | | /// <summary> |
| | | 16 | | /// Pointer to the underlying data (not valid after disposal). |
| | | 17 | | /// </summary> |
| | | 18 | | public abstract unsafe byte* Pointer { get; } |
| | | 19 | | |
| | | 20 | | /// <summary> |
| | | 21 | | /// Size of the block. |
| | | 22 | | /// </summary> |
| | | 23 | | public abstract int Size { get; } |
| | | 24 | | |
| | 0 | 25 | | public unsafe BlobReader GetReader() => new BlobReader(Pointer, Size); |
| | | 26 | | |
| | | 27 | | /// <summary> |
| | | 28 | | /// Creates a new stream wrapping the block's memory. |
| | | 29 | | /// </summary> |
| | 0 | 30 | | public unsafe Stream GetStream() => new UnmanagedMemoryStream(Pointer, Size); |
| | | 31 | | |
| | | 32 | | /// <summary> |
| | | 33 | | /// Returns the content of the entire memory block. |
| | | 34 | | /// </summary> |
| | | 35 | | /// <remarks> |
| | | 36 | | /// Does not check bounds. |
| | | 37 | | /// |
| | | 38 | | /// Only creates a copy of the data if they are not represented by a managed byte array, |
| | | 39 | | /// or if the specified range doesn't span the entire block. |
| | | 40 | | /// </remarks> |
| | | 41 | | public virtual unsafe ImmutableArray<byte> GetContentUnchecked(int start, int length) |
| | 0 | 42 | | { |
| | 0 | 43 | | var result = new ReadOnlySpan<byte>(Pointer + start, length).ToImmutableArray(); |
| | 0 | 44 | | GC.KeepAlive(this); |
| | 0 | 45 | | return result; |
| | 0 | 46 | | } |
| | | 47 | | |
| | | 48 | | /// <summary> |
| | | 49 | | /// Disposes the block. |
| | | 50 | | /// </summary> |
| | | 51 | | /// <remarks> |
| | | 52 | | /// The operation is idempotent, but must not be called concurrently with any other operations on the block. |
| | | 53 | | /// |
| | | 54 | | /// Using the block after dispose is an error in our code and therefore no effort is made to throw a tidy |
| | | 55 | | /// ObjectDisposedException and null ref or AV is possible. |
| | | 56 | | /// </remarks> |
| | | 57 | | public abstract void Dispose(); |
| | | 58 | | } |
| | | 59 | | } |
| | | 60 | | |