StreamOut.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. namespace JPH {
  5. /// Simple binary output stream
  6. class StreamOut
  7. {
  8. public:
  9. /// Virtual destructor
  10. virtual ~StreamOut() = default;
  11. /// Write a string of bytes to the binary stream
  12. virtual void WriteBytes(const void *inData, size_t inNumBytes) = 0;
  13. /// Returns true if there was an IO failure
  14. virtual bool IsFailed() const = 0;
  15. /// Write a primitive (e.g. float, int, etc.) to the binary stream
  16. template <class T>
  17. void Write(const T &inT)
  18. {
  19. WriteBytes(&inT, sizeof(inT));
  20. }
  21. /// Write a vector of primitives from the binary stream
  22. template <class T, class A>
  23. void Write(const vector<T, A> &inT)
  24. {
  25. typename vector<T>::size_type len = inT.size();
  26. Write(len);
  27. if (!IsFailed())
  28. for (typename vector<T>::size_type i = 0; i < len; ++i)
  29. Write(inT[i]);
  30. }
  31. /// Write a string to the binary stream (writes the number of characters and then the characters)
  32. void Write(const string &inString)
  33. {
  34. string::size_type len = inString.size();
  35. Write(len);
  36. if (!IsFailed())
  37. WriteBytes(inString.data(), len);
  38. }
  39. /// Write a Vec3 (don't write W)
  40. void Write(const Vec3 &inVec)
  41. {
  42. WriteBytes(&inVec, 3 * sizeof(float));
  43. }
  44. };
  45. } // JPH