iceberg-cpp
Loading...
Searching...
No Matches
byte_swap.h
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20#pragma once
21
22#include <bit>
23#include <concepts>
24#include <cstddef>
25#include <cstdint>
26
27#include "iceberg/compat/compiler.h"
28
29namespace iceberg::internal {
30
31template <std::unsigned_integral T>
32constexpr T ByteSwapUnsigned(T value) {
33#if !ICEBERG_CXX20_COMPAT
34 return std::byteswap(value);
35#else
36# if defined(__GNUC__) || defined(__clang__)
37 if constexpr (sizeof(T) == sizeof(uint16_t)) {
38 return static_cast<T>(__builtin_bswap16(value));
39 } else if constexpr (sizeof(T) == sizeof(uint32_t)) {
40 return static_cast<T>(__builtin_bswap32(value));
41 } else if constexpr (sizeof(T) == sizeof(uint64_t)) {
42 return static_cast<T>(__builtin_bswap64(value));
43 }
44# endif
45 T swapped{0};
46 for (size_t byte = 0; byte < sizeof(T); ++byte) {
47 swapped = static_cast<T>(swapped << 8) | static_cast<T>(value & 0xFF);
48 value = static_cast<T>(value >> 8);
49 }
50 return swapped;
51#endif
52}
53
54} // namespace iceberg::internal