memory.hpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #pragma once
  2. #include <nall/file.hpp>
  3. #include <nall/decode/zip.hpp>
  4. namespace nall::vfs {
  5. struct memory : file {
  6. ~memory() { delete[] _data; }
  7. static auto open(const void* data, uintmax size) -> shared_pointer<memory> {
  8. auto instance = shared_pointer<memory>{new memory};
  9. instance->_open((const uint8_t*)data, size);
  10. return instance;
  11. }
  12. static auto open(string location, bool decompress = false) -> shared_pointer<memory> {
  13. auto instance = shared_pointer<memory>{new memory};
  14. if(decompress && location.iendsWith(".zip")) {
  15. Decode::ZIP archive;
  16. if(archive.open(location) && archive.file.size() == 1) {
  17. auto memory = archive.extract(archive.file.first());
  18. instance->_open(memory.data(), memory.size());
  19. return instance;
  20. }
  21. }
  22. auto memory = nall::file::read(location);
  23. instance->_open(memory.data(), memory.size());
  24. return instance;
  25. }
  26. auto data() const -> const uint8_t* { return _data; }
  27. auto size() const -> uintmax override { return _size; }
  28. auto offset() const -> uintmax override { return _offset; }
  29. auto seek(intmax offset, index mode) -> void override {
  30. if(mode == index::absolute) _offset = (uintmax)offset;
  31. if(mode == index::relative) _offset += (intmax)offset;
  32. }
  33. auto read() -> uint8_t override {
  34. if(_offset >= _size) return 0x00;
  35. return _data[_offset++];
  36. }
  37. auto write(uint8_t data) -> void override {
  38. if(_offset >= _size) return;
  39. _data[_offset++] = data;
  40. }
  41. private:
  42. memory() = default;
  43. memory(const file&) = delete;
  44. auto operator=(const memory&) -> memory& = delete;
  45. auto _open(const uint8_t* data, uintmax size) -> void {
  46. _size = size;
  47. _data = new uint8_t[size];
  48. nall::memory::copy(_data, data, size);
  49. }
  50. uint8_t* _data = nullptr;
  51. uintmax _size = 0;
  52. uintmax _offset = 0;
  53. };
  54. }