From d28c38a9d0b682a065e64d184604076fdda7d802 Mon Sep 17 00:00:00 2001 From: Alex Barney Date: Tue, 8 Mar 2022 17:20:41 -0700 Subject: [PATCH] Add MemoryResourceBufferHoldStorage --- .../MemoryResourceBufferHoldStorage.cs | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 src/LibHac/FsSystem/MemoryResourceBufferHoldStorage.cs diff --git a/src/LibHac/FsSystem/MemoryResourceBufferHoldStorage.cs b/src/LibHac/FsSystem/MemoryResourceBufferHoldStorage.cs new file mode 100644 index 00000000..00f77c1c --- /dev/null +++ b/src/LibHac/FsSystem/MemoryResourceBufferHoldStorage.cs @@ -0,0 +1,91 @@ +using System; +using LibHac.Common; +using LibHac.Diag; +using LibHac.Fs; + +namespace LibHac.FsSystem; + +/// +/// Allocates a buffer from the provided that is deallocated +/// when the is disposed. +/// +/// Based on FS 13.1.0 (nnSdk 13.4.0) +public class MemoryResourceBufferHoldStorage : IStorage +{ + private SharedRef _storage; + private MemoryResource _memoryResource; + private Mem.Buffer _buffer; + + public MemoryResourceBufferHoldStorage(ref SharedRef baseStorage, MemoryResource memoryResource, + int bufferSize) + { + _storage = SharedRef.CreateMove(ref baseStorage); + _memoryResource = memoryResource; + _buffer = memoryResource.Allocate(bufferSize); + } + + public override void Dispose() + { + if (!_buffer.IsNull) + { + _memoryResource.Deallocate(ref _buffer); + } + + _storage.Destroy(); + + base.Dispose(); + } + + public bool IsValid() + { + return !_buffer.IsNull; + } + + public Mem.Buffer GetBuffer() + { + return _buffer; + } + + public override Result Read(long offset, Span destination) + { + Assert.SdkRequiresNotNull(_storage); + + return _storage.Get.Read(offset, destination); + } + + public override Result Write(long offset, ReadOnlySpan source) + { + Assert.SdkRequiresNotNull(_storage); + + return _storage.Get.Write(offset, source); + } + + public override Result Flush() + { + Assert.SdkRequiresNotNull(_storage); + + return _storage.Get.Flush(); + } + + public override Result SetSize(long size) + { + Assert.SdkRequiresNotNull(_storage); + + return _storage.Get.SetSize(size); + } + + public override Result GetSize(out long size) + { + Assert.SdkRequiresNotNull(_storage); + + return _storage.Get.GetSize(out size); + } + + public override Result OperateRange(Span outBuffer, OperationId operationId, long offset, long size, + ReadOnlySpan inBuffer) + { + Assert.SdkRequiresNotNull(_storage); + + return _storage.Get.OperateRange(outBuffer, operationId, offset, size, inBuffer); + } +} \ No newline at end of file