blob: f322b04406272a5fabab2ec35d70cba3899dcb07 [file] [log] [blame]
QUICHE team173c48f2019-11-19 16:34:44 -08001// Copyright 2019 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
bncb8fd1f82020-10-16 17:37:52 -07005#ifndef QUICHE_COMMON_QUICHE_ENDIAN_H_
6#define QUICHE_COMMON_QUICHE_ENDIAN_H_
QUICHE team173c48f2019-11-19 16:34:44 -08007
vasilvv6b2b7522020-09-18 11:47:57 -07008#include <algorithm>
9#include <cstdint>
10#include <type_traits>
11
QUICHE team5be974e2020-12-29 18:35:24 -050012#include "common/platform/api/quiche_export.h"
QUICHE team173c48f2019-11-19 16:34:44 -080013
14namespace quiche {
15
16enum Endianness {
17 NETWORK_BYTE_ORDER, // big endian
18 HOST_BYTE_ORDER // little endian
19};
20
21// Provide utility functions that convert from/to network order (big endian)
22// to/from host order (can be either little or big endian depending on the
23// platform).
24class QUICHE_EXPORT_PRIVATE QuicheEndian {
25 public:
vasilvv6b2b7522020-09-18 11:47:57 -070026 // Convert |x| from host order (little endian) to network order (big endian).
27#if defined(__clang__) || \
28 (defined(__GNUC__) && \
29 ((__GNUC__ == 4 && __GNUC_MINOR__ >= 8) || __GNUC__ >= 5))
30 static uint16_t HostToNet16(uint16_t x) { return __builtin_bswap16(x); }
31 static uint32_t HostToNet32(uint32_t x) { return __builtin_bswap32(x); }
32 static uint64_t HostToNet64(uint64_t x) { return __builtin_bswap64(x); }
33#else
34 static uint16_t HostToNet16(uint16_t x) { return PortableByteSwap(x); }
35 static uint32_t HostToNet32(uint32_t x) { return PortableByteSwap(x); }
36 static uint64_t HostToNet64(uint64_t x) { return PortableByteSwap(x); }
37#endif
QUICHE team173c48f2019-11-19 16:34:44 -080038
vasilvv6b2b7522020-09-18 11:47:57 -070039 // Convert |x| from network order (big endian) to host order (little endian).
40 static uint16_t NetToHost16(uint16_t x) { return HostToNet16(x); }
41 static uint32_t NetToHost32(uint32_t x) { return HostToNet32(x); }
42 static uint64_t NetToHost64(uint64_t x) { return HostToNet64(x); }
QUICHE team173c48f2019-11-19 16:34:44 -080043
44 // Returns true if current host order is little endian.
vasilvv6b2b7522020-09-18 11:47:57 -070045 static bool HostIsLittleEndian() { return true; }
46
47 // Left public for tests.
48 template <typename T>
49 static T PortableByteSwap(T input) {
50 static_assert(std::is_unsigned<T>::value, "T has to be uintNN_t");
51 union {
52 T number;
53 char bytes[sizeof(T)];
54 } value;
55 value.number = input;
56 std::reverse(std::begin(value.bytes), std::end(value.bytes));
57 return value.number;
QUICHE team173c48f2019-11-19 16:34:44 -080058 }
59};
60
61} // namespace quiche
62
bncb8fd1f82020-10-16 17:37:52 -070063#endif // QUICHE_COMMON_QUICHE_ENDIAN_H_