BinaryStream.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #pragma once
  2. #if __has_include(<bit>)
  3. #include <bit> // for endian
  4. #endif
  5. #include <stdint.h> // for int16_t, int32_t, int64_t, uint16_t, uint32_t
  6. #include <cstddef> // for byte
  7. #include <iostream> // for istream, ostream
  8. namespace bell {
  9. class BinaryStream {
  10. private:
  11. std::endian byteOrder;
  12. std::istream* istr = nullptr;
  13. std::ostream* ostr = nullptr;
  14. void ensureReadable();
  15. void ensureWritable();
  16. bool flipBytes = false;
  17. template <typename T>
  18. T swap16(T value) {
  19. #ifdef _WIN32
  20. return _byteswap_ushort(value);
  21. #else
  22. return __builtin_bswap16(value);
  23. #endif
  24. }
  25. template <typename T>
  26. T swap32(T value) {
  27. #ifdef _WIN32
  28. return _byteswap_ulong(value);
  29. #else
  30. return __builtin_bswap32(value);
  31. #endif
  32. }
  33. template <typename T>
  34. T swap64(T value) {
  35. #ifdef _WIN32
  36. return _byteswap_uint64(value);
  37. #else
  38. return __builtin_bswap64(value);
  39. #endif
  40. }
  41. public:
  42. BinaryStream(std::ostream* ostr);
  43. BinaryStream(std::istream* istr);
  44. /**
  45. * @brief Set byte order used by stream.
  46. *
  47. * @param byteOrder stream's byteorder. Defaults to native.
  48. */
  49. void setByteOrder(std::endian byteOrder);
  50. // Read operations
  51. BinaryStream& operator>>(char& value);
  52. BinaryStream& operator>>(std::byte& value);
  53. BinaryStream& operator>>(int16_t& value);
  54. BinaryStream& operator>>(uint16_t& value);
  55. BinaryStream& operator>>(int32_t& value);
  56. BinaryStream& operator>>(uint32_t& value);
  57. BinaryStream& operator>>(int64_t& value);
  58. BinaryStream& operator>>(uint64_t& value);
  59. // Write operations
  60. BinaryStream& operator<<(char value);
  61. BinaryStream& operator<<(std::byte value);
  62. BinaryStream& operator<<(int16_t value);
  63. BinaryStream& operator<<(uint16_t value);
  64. BinaryStream& operator<<(int32_t value);
  65. BinaryStream& operator<<(uint32_t value);
  66. BinaryStream& operator<<(int64_t value);
  67. BinaryStream& operator<<(uint64_t value);
  68. };
  69. } // namespace bell