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