DataReader.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2008 Dolphin Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #pragma once
  4. #include <cstring>
  5. #include "Common/CommonTypes.h"
  6. #include "Common/Inline.h"
  7. #include "Common/Swap.h"
  8. class DataReader
  9. {
  10. public:
  11. DataReader() = default;
  12. DataReader(u8* src, u8* end_) : buffer(src), end(end_) {}
  13. u8* GetPointer() { return buffer; }
  14. const u8* GetPointer() const { return buffer; }
  15. DataReader& operator=(u8* src)
  16. {
  17. buffer = src;
  18. return *this;
  19. }
  20. size_t size() const { return end - buffer; }
  21. template <typename T, bool swapped = true>
  22. DOLPHIN_FORCE_INLINE T Peek(int offset = 0) const
  23. {
  24. T data;
  25. std::memcpy(&data, &buffer[offset], sizeof(T));
  26. if constexpr (swapped)
  27. data = Common::FromBigEndian(data);
  28. return data;
  29. }
  30. template <typename T, bool swapped = true>
  31. DOLPHIN_FORCE_INLINE T Read()
  32. {
  33. const T result = Peek<T, swapped>();
  34. buffer += sizeof(T);
  35. return result;
  36. }
  37. template <typename T, bool swapped = false>
  38. DOLPHIN_FORCE_INLINE void Write(T data)
  39. {
  40. if constexpr (swapped)
  41. data = Common::FromBigEndian(data);
  42. std::memcpy(buffer, &data, sizeof(T));
  43. buffer += sizeof(T);
  44. }
  45. template <typename T = u8>
  46. void Skip(size_t data = 1)
  47. {
  48. buffer += sizeof(T) * data;
  49. }
  50. private:
  51. u8* __restrict buffer = nullptr;
  52. u8* end = nullptr;
  53. };