StreamIn.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. namespace JPH {
  5. /// Simple binary input stream
  6. class StreamIn
  7. {
  8. public:
  9. /// Virtual destructor
  10. virtual ~StreamIn() = default;
  11. /// Read a string of bytes from the binary stream
  12. virtual void ReadBytes(void *outData, size_t inNumBytes) = 0;
  13. /// Returns true when an attempt has been made to read past the end of the file
  14. virtual bool IsEOF() const = 0;
  15. /// Returns true if there was an IO failure
  16. virtual bool IsFailed() const = 0;
  17. /// Read a primitive (e.g. float, int, etc.) from the binary stream
  18. template <class T>
  19. void Read(T &outT)
  20. {
  21. ReadBytes(&outT, sizeof(outT));
  22. }
  23. /// Read a vector of primitives from the binary stream
  24. template <class T, class A>
  25. void Read(vector<T, A> &outT)
  26. {
  27. typename vector<T>::size_type len = outT.size(); // Initialize to previous array size, this is used for validation in the StateRecorder class
  28. Read(len);
  29. if (!IsEOF() && !IsFailed())
  30. {
  31. outT.resize(len);
  32. for (typename vector<T>::size_type i = 0; i < len; ++i)
  33. Read(outT[i]);
  34. }
  35. else
  36. outT.clear();
  37. }
  38. /// Read a string from the binary stream (reads the number of characters and then the characters)
  39. void Read(string &outString)
  40. {
  41. string::size_type len = 0;
  42. Read(len);
  43. if (!IsEOF() && !IsFailed())
  44. {
  45. outString.resize(len);
  46. ReadBytes(outString.data(), len);
  47. }
  48. else
  49. outString.clear();
  50. }
  51. /// Read a Vec3 (don't read W)
  52. void Read(Vec3 &outVec)
  53. {
  54. ReadBytes(&outVec, 3 * sizeof(float));
  55. outVec = Vec3::sFixW(outVec.mValue);
  56. }
  57. };
  58. } // JPH