PLYwoot
Header-only C++17 library for parsing and writing PLY files
Loading...
Searching...
No Matches
endian.hpp
Go to the documentation of this file.
1/*
2 This file is part of PLYwoot, a header-only PLY parser.
3
4 Copyright (C) 2023-2025, Ton van den Heuvel
5
6 PLYwoot is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
18*/
19
20#ifndef PLYWOOT_ENDIAN_HPP
21#define PLYWOOT_ENDIAN_HPP
22
24
25#include <type_traits>
26#include <utility>
27
28namespace plywoot::detail {
29
32struct LittleEndian
33{
34};
35
38struct BigEndian
39{
40};
41
44#if defined(_MSC_VER) && !defined(__clang__)
45using HostEndian = LittleEndian;
46#else
47using HostEndian = std::conditional_t<__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__, LittleEndian, BigEndian>;
48#endif
49
55template<typename T>
57{
58 unsigned char *bytes = reinterpret_cast<unsigned char *>(&t);
59
60 if constexpr (sizeof(T) == 2) { std::swap(bytes[0], bytes[1]); }
61 else if constexpr (sizeof(T) == 4)
62 {
63 std::swap(bytes[0], bytes[3]);
64 std::swap(bytes[1], bytes[2]);
65 }
66 else if constexpr (sizeof(T) == 8)
67 {
68 std::swap(bytes[0], bytes[7]);
69 std::swap(bytes[1], bytes[6]);
70 std::swap(bytes[2], bytes[5]);
71 std::swap(bytes[3], bytes[4]);
72 }
73
74 return t;
75}
76
77}
78
79#endif
T byte_swap(T t)
Definition endian.hpp:56
std::conditional_t< __BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__, LittleEndian, BigEndian > HostEndian
Definition endian.hpp:47