1 // Copyright 2017 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "absl/base/internal/endian.h"
16 
17 #include <algorithm>
18 #include <cstdint>
19 #include <limits>
20 #include <random>
21 #include <vector>
22 
23 #include "gtest/gtest.h"
24 #include "absl/base/config.h"
25 
26 namespace absl {
27 namespace {
28 
29 const uint64_t kInitialNumber{0x0123456789abcdef};
30 const uint64_t k64Value{kInitialNumber};
31 const uint32_t k32Value{0x01234567};
32 const uint16_t k16Value{0x0123};
33 const int kNumValuesToTest = 1000000;
34 const int kRandomSeed = 12345;
35 
36 #if defined(ABSL_IS_BIG_ENDIAN)
37 const uint64_t kInitialInNetworkOrder{kInitialNumber};
38 const uint64_t k64ValueLE{0xefcdab8967452301};
39 const uint32_t k32ValueLE{0x67452301};
40 const uint16_t k16ValueLE{0x2301};
41 
42 const uint64_t k64ValueBE{kInitialNumber};
43 const uint32_t k32ValueBE{k32Value};
44 const uint16_t k16ValueBE{k16Value};
45 #elif defined(ABSL_IS_LITTLE_ENDIAN)
46 const uint64_t kInitialInNetworkOrder{0xefcdab8967452301};
47 const uint64_t k64ValueLE{kInitialNumber};
48 const uint32_t k32ValueLE{k32Value};
49 const uint16_t k16ValueLE{k16Value};
50 
51 const uint64_t k64ValueBE{0xefcdab8967452301};
52 const uint32_t k32ValueBE{0x67452301};
53 const uint16_t k16ValueBE{0x2301};
54 #endif
55 
56 template<typename T>
GenerateAllValuesForType()57 std::vector<T> GenerateAllValuesForType() {
58   std::vector<T> result;
59   T next = std::numeric_limits<T>::min();
60   while (true) {
61     result.push_back(next);
62     if (next == std::numeric_limits<T>::max()) {
63       return result;
64     }
65     ++next;
66   }
67 }
68 
69 template<typename T>
GenerateRandomIntegers(size_t numValuesToTest)70 std::vector<T> GenerateRandomIntegers(size_t numValuesToTest) {
71   std::vector<T> result;
72   std::mt19937_64 rng(kRandomSeed);
73   for (size_t i = 0; i < numValuesToTest; ++i) {
74     result.push_back(rng());
75   }
76   return result;
77 }
78 
ManualByteSwap(char * bytes,int length)79 void ManualByteSwap(char* bytes, int length) {
80   if (length == 1)
81     return;
82 
83   EXPECT_EQ(0, length % 2);
84   for (int i = 0; i < length / 2; ++i) {
85     int j = (length - 1) - i;
86     using std::swap;
87     swap(bytes[i], bytes[j]);
88   }
89 }
90 
91 template<typename T>
UnalignedLoad(const char * p)92 inline T UnalignedLoad(const char* p) {
93   static_assert(
94       sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8,
95       "Unexpected type size");
96 
97   switch (sizeof(T)) {
98     case 1: return *reinterpret_cast<const T*>(p);
99     case 2:
100       return ABSL_INTERNAL_UNALIGNED_LOAD16(p);
101     case 4:
102       return ABSL_INTERNAL_UNALIGNED_LOAD32(p);
103     case 8:
104       return ABSL_INTERNAL_UNALIGNED_LOAD64(p);
105     default:
106       // Suppresses invalid "not all control paths return a value" on MSVC
107       return {};
108   }
109 }
110 
111 template <typename T, typename ByteSwapper>
GBSwapHelper(const std::vector<T> & host_values_to_test,const ByteSwapper & byte_swapper)112 static void GBSwapHelper(const std::vector<T>& host_values_to_test,
113                          const ByteSwapper& byte_swapper) {
114   // Test byte_swapper against a manual byte swap.
115   for (typename std::vector<T>::const_iterator it = host_values_to_test.begin();
116        it != host_values_to_test.end(); ++it) {
117     T host_value = *it;
118 
119     char actual_value[sizeof(host_value)];
120     memcpy(actual_value, &host_value, sizeof(host_value));
121     byte_swapper(actual_value);
122 
123     char expected_value[sizeof(host_value)];
124     memcpy(expected_value, &host_value, sizeof(host_value));
125     ManualByteSwap(expected_value, sizeof(host_value));
126 
127     ASSERT_EQ(0, memcmp(actual_value, expected_value, sizeof(host_value)))
128         << "Swap output for 0x" << std::hex << host_value << " does not match. "
129         << "Expected: 0x" << UnalignedLoad<T>(expected_value) << "; "
130         << "actual: 0x" <<  UnalignedLoad<T>(actual_value);
131   }
132 }
133 
Swap16(char * bytes)134 void Swap16(char* bytes) {
135   ABSL_INTERNAL_UNALIGNED_STORE16(
136       bytes, gbswap_16(ABSL_INTERNAL_UNALIGNED_LOAD16(bytes)));
137 }
138 
Swap32(char * bytes)139 void Swap32(char* bytes) {
140   ABSL_INTERNAL_UNALIGNED_STORE32(
141       bytes, gbswap_32(ABSL_INTERNAL_UNALIGNED_LOAD32(bytes)));
142 }
143 
Swap64(char * bytes)144 void Swap64(char* bytes) {
145   ABSL_INTERNAL_UNALIGNED_STORE64(
146       bytes, gbswap_64(ABSL_INTERNAL_UNALIGNED_LOAD64(bytes)));
147 }
148 
TEST(EndianessTest,Uint16)149 TEST(EndianessTest, Uint16) {
150   GBSwapHelper(GenerateAllValuesForType<uint16_t>(), &Swap16);
151 }
152 
TEST(EndianessTest,Uint32)153 TEST(EndianessTest, Uint32) {
154   GBSwapHelper(GenerateRandomIntegers<uint32_t>(kNumValuesToTest), &Swap32);
155 }
156 
TEST(EndianessTest,Uint64)157 TEST(EndianessTest, Uint64) {
158   GBSwapHelper(GenerateRandomIntegers<uint64_t>(kNumValuesToTest), &Swap64);
159 }
160 
TEST(EndianessTest,ghtonll_gntohll)161 TEST(EndianessTest, ghtonll_gntohll) {
162   // Test that absl::ghtonl compiles correctly
163   uint32_t test = 0x01234567;
164   EXPECT_EQ(absl::gntohl(absl::ghtonl(test)), test);
165 
166   uint64_t comp = absl::ghtonll(kInitialNumber);
167   EXPECT_EQ(comp, kInitialInNetworkOrder);
168   comp = absl::gntohll(kInitialInNetworkOrder);
169   EXPECT_EQ(comp, kInitialNumber);
170 
171   // Test that htonll and ntohll are each others' inverse functions on a
172   // somewhat assorted batch of numbers. 37 is chosen to not be anything
173   // particularly nice base 2.
174   uint64_t value = 1;
175   for (int i = 0; i < 100; ++i) {
176     comp = absl::ghtonll(absl::gntohll(value));
177     EXPECT_EQ(value, comp);
178     comp = absl::gntohll(absl::ghtonll(value));
179     EXPECT_EQ(value, comp);
180     value *= 37;
181   }
182 }
183 
TEST(EndianessTest,little_endian)184 TEST(EndianessTest, little_endian) {
185   // Check little_endian uint16_t.
186   uint64_t comp = little_endian::FromHost16(k16Value);
187   EXPECT_EQ(comp, k16ValueLE);
188   comp = little_endian::ToHost16(k16ValueLE);
189   EXPECT_EQ(comp, k16Value);
190 
191   // Check little_endian uint32_t.
192   comp = little_endian::FromHost32(k32Value);
193   EXPECT_EQ(comp, k32ValueLE);
194   comp = little_endian::ToHost32(k32ValueLE);
195   EXPECT_EQ(comp, k32Value);
196 
197   // Check little_endian uint64_t.
198   comp = little_endian::FromHost64(k64Value);
199   EXPECT_EQ(comp, k64ValueLE);
200   comp = little_endian::ToHost64(k64ValueLE);
201   EXPECT_EQ(comp, k64Value);
202 
203   // Check little-endian Load and store functions.
204   uint16_t u16Buf;
205   uint32_t u32Buf;
206   uint64_t u64Buf;
207 
208   little_endian::Store16(&u16Buf, k16Value);
209   EXPECT_EQ(u16Buf, k16ValueLE);
210   comp = little_endian::Load16(&u16Buf);
211   EXPECT_EQ(comp, k16Value);
212 
213   little_endian::Store32(&u32Buf, k32Value);
214   EXPECT_EQ(u32Buf, k32ValueLE);
215   comp = little_endian::Load32(&u32Buf);
216   EXPECT_EQ(comp, k32Value);
217 
218   little_endian::Store64(&u64Buf, k64Value);
219   EXPECT_EQ(u64Buf, k64ValueLE);
220   comp = little_endian::Load64(&u64Buf);
221   EXPECT_EQ(comp, k64Value);
222 }
223 
TEST(EndianessTest,big_endian)224 TEST(EndianessTest, big_endian) {
225   // Check big-endian Load and store functions.
226   uint16_t u16Buf;
227   uint32_t u32Buf;
228   uint64_t u64Buf;
229 
230   unsigned char buffer[10];
231   big_endian::Store16(&u16Buf, k16Value);
232   EXPECT_EQ(u16Buf, k16ValueBE);
233   uint64_t comp = big_endian::Load16(&u16Buf);
234   EXPECT_EQ(comp, k16Value);
235 
236   big_endian::Store32(&u32Buf, k32Value);
237   EXPECT_EQ(u32Buf, k32ValueBE);
238   comp = big_endian::Load32(&u32Buf);
239   EXPECT_EQ(comp, k32Value);
240 
241   big_endian::Store64(&u64Buf, k64Value);
242   EXPECT_EQ(u64Buf, k64ValueBE);
243   comp = big_endian::Load64(&u64Buf);
244   EXPECT_EQ(comp, k64Value);
245 
246   big_endian::Store16(buffer + 1, k16Value);
247   EXPECT_EQ(u16Buf, k16ValueBE);
248   comp = big_endian::Load16(buffer + 1);
249   EXPECT_EQ(comp, k16Value);
250 
251   big_endian::Store32(buffer + 1, k32Value);
252   EXPECT_EQ(u32Buf, k32ValueBE);
253   comp = big_endian::Load32(buffer + 1);
254   EXPECT_EQ(comp, k32Value);
255 
256   big_endian::Store64(buffer + 1, k64Value);
257   EXPECT_EQ(u64Buf, k64ValueBE);
258   comp = big_endian::Load64(buffer + 1);
259   EXPECT_EQ(comp, k64Value);
260 }
261 
262 }  // namespace
263 }  // namespace absl
264