BinaryStream.h 1.7 KB

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