1 //===- SwapByteOrder.h - Generic and optimized byte swaps -------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file declares generic and optimized functions to swap the byte order of 10 // an integral type. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_SUPPORT_SWAPBYTEORDER_H 15 #define LLVM_SUPPORT_SWAPBYTEORDER_H 16 17 #include "llvm/ADT/STLForwardCompat.h" 18 #include "llvm/ADT/bit.h" 19 #include <cstdint> 20 #include <type_traits> 21 22 namespace llvm { 23 24 namespace sys { 25 26 constexpr bool IsBigEndianHost = 27 llvm::endianness::native == llvm::endianness::big; 28 29 static const bool IsLittleEndianHost = !IsBigEndianHost; 30 31 inline unsigned char getSwappedBytes(unsigned char C) { return llvm::byteswap(C); } 32 inline signed char getSwappedBytes( signed char C) { return llvm::byteswap(C); } 33 inline char getSwappedBytes( char C) { return llvm::byteswap(C); } 34 35 inline unsigned short getSwappedBytes(unsigned short C) { return llvm::byteswap(C); } 36 inline signed short getSwappedBytes( signed short C) { return llvm::byteswap(C); } 37 38 inline unsigned int getSwappedBytes(unsigned int C) { return llvm::byteswap(C); } 39 inline signed int getSwappedBytes( signed int C) { return llvm::byteswap(C); } 40 41 inline unsigned long getSwappedBytes(unsigned long C) { return llvm::byteswap(C); } 42 inline signed long getSwappedBytes( signed long C) { return llvm::byteswap(C); } 43 44 inline unsigned long long getSwappedBytes(unsigned long long C) { return llvm::byteswap(C); } 45 inline signed long long getSwappedBytes( signed long long C) { return llvm::byteswap(C); } 46 47 inline float getSwappedBytes(float C) { 48 return llvm::bit_cast<float>(llvm::byteswap(llvm::bit_cast<uint32_t>(C))); 49 } 50 51 inline double getSwappedBytes(double C) { 52 return llvm::bit_cast<double>(llvm::byteswap(llvm::bit_cast<uint64_t>(C))); 53 } 54 55 template <typename T> 56 inline std::enable_if_t<std::is_enum_v<T>, T> getSwappedBytes(T C) { 57 return static_cast<T>(llvm::byteswap(llvm::to_underlying(C))); 58 } 59 60 template<typename T> 61 inline void swapByteOrder(T &Value) { 62 Value = getSwappedBytes(Value); 63 } 64 65 } // end namespace sys 66 } // end namespace llvm 67 68 #endif 69