|
|
- #pragma once
-
- #include "gp/containers/array.hpp"
-
- #include <bit>
-
- #include <stddef.h>
- #include <stdint.h>
-
- namespace gp {
-
- using endian = std::endian;
-
- template <typename T>
- T swap_endian(T value) {
- union {
- T v;
- uint8_t u8[sizeof(T)];
- } src, dest;
-
- src.v = value;
-
- for (size_t idx = 0;idx<sizeof(T);idx++) {
- dest.u8[idx] = src.u8[sizeof(T)-idx-1];
- }
-
- return dest.v;
- }
-
- template<typename T, endian mode = endian::big>
- struct endian_wrapper {
-
- union {
- T value;
- gp::array<uint8_t, sizeof(T)> bytes;
- };
-
- endian_wrapper() {}
-
- endian_wrapper(T v)
- : value{mode == endian::native ? v : swap_endian(v)} {}
-
- endian_wrapper(endian_wrapper& v)
- : value{v.value} {}
-
- endian_wrapper& operator=(T p) {
- value = mode == endian::native ? p : swap_endian(p);
- return *this;
- }
-
- operator T() {
- return mode == endian::native ? value : swap_endian(value);
- }
- };
-
- }
|