| | | 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.Diagnostics; |
| | | 6 | | using System.IO; |
| | | 7 | | using System.Runtime.InteropServices; |
| | | 8 | | using System.Threading; |
| | | 9 | | |
| | | 10 | | namespace System.Reflection.Internal |
| | | 11 | | { |
| | | 12 | | internal sealed class ByteArrayMemoryProvider : MemoryBlockProvider |
| | | 13 | | { |
| | | 14 | | private readonly ImmutableArray<byte> _array; |
| | | 15 | | private PinnedObject? _pinned; |
| | | 16 | | |
| | 0 | 17 | | public ByteArrayMemoryProvider(ImmutableArray<byte> array) |
| | 0 | 18 | | { |
| | 0 | 19 | | Debug.Assert(!array.IsDefault); |
| | 0 | 20 | | _array = array; |
| | 0 | 21 | | } |
| | | 22 | | |
| | | 23 | | protected override void Dispose(bool disposing) |
| | 0 | 24 | | { |
| | 0 | 25 | | Debug.Assert(disposing); |
| | 0 | 26 | | Interlocked.Exchange(ref _pinned, null)?.Dispose(); |
| | 0 | 27 | | } |
| | | 28 | | |
| | 0 | 29 | | public override int Size => _array.Length; |
| | 0 | 30 | | public ImmutableArray<byte> Array => _array; |
| | | 31 | | |
| | | 32 | | protected override AbstractMemoryBlock GetMemoryBlockImpl(int start, int size) |
| | 0 | 33 | | { |
| | 0 | 34 | | return new ByteArrayMemoryBlock(this, start, size); |
| | 0 | 35 | | } |
| | | 36 | | |
| | | 37 | | internal unsafe byte* Pointer |
| | | 38 | | { |
| | | 39 | | get |
| | 0 | 40 | | { |
| | 0 | 41 | | if (_pinned == null) |
| | 0 | 42 | | { |
| | 0 | 43 | | var newPinned = new PinnedObject(ImmutableCollectionsMarshal.AsArray(_array)!); |
| | | 44 | | |
| | 0 | 45 | | if (Interlocked.CompareExchange(ref _pinned, newPinned, null) != null) |
| | 0 | 46 | | { |
| | | 47 | | // another thread has already allocated the handle: |
| | 0 | 48 | | newPinned.Dispose(); |
| | 0 | 49 | | } |
| | 0 | 50 | | } |
| | | 51 | | |
| | 0 | 52 | | return _pinned.Pointer; |
| | 0 | 53 | | } |
| | | 54 | | } |
| | | 55 | | } |
| | | 56 | | } |
| | | 57 | | |