• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2019 PDFium 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 
5 #include "core/fxcrt/byteorder.h"
6 
7 #include "testing/gtest/include/gtest/gtest.h"
8 
9 namespace {
10 
11 // Original code to use as a reference implementation.
12 
13 #define FXWORD_GET_LSBFIRST(p)                                \
14   (static_cast<uint16_t>((static_cast<uint16_t>(p[1]) << 8) | \
15                          (static_cast<uint16_t>(p[0]))))
16 #define FXWORD_GET_MSBFIRST(p)                                \
17   (static_cast<uint16_t>((static_cast<uint16_t>(p[0]) << 8) | \
18                          (static_cast<uint16_t>(p[1]))))
19 #define FXDWORD_GET_LSBFIRST(p)                                                \
20   ((static_cast<uint32_t>(p[3]) << 24) | (static_cast<uint32_t>(p[2]) << 16) | \
21    (static_cast<uint32_t>(p[1]) << 8) | (static_cast<uint32_t>(p[0])))
22 #define FXDWORD_GET_MSBFIRST(p)                                                \
23   ((static_cast<uint32_t>(p[0]) << 24) | (static_cast<uint32_t>(p[1]) << 16) | \
24    (static_cast<uint32_t>(p[2]) << 8) | (static_cast<uint32_t>(p[3])))
25 
26 constexpr uint32_t kTestValues32[] = {
27     0x0,      0x1,        0x2,        0x3,        0x4,       0xfe,
28     0xff,     0x100,      0x101,      0xffff,     0x10000,   0x123456,
29     0x345167, 0x2f3e4a5b, 0xff000000, 0xfffffffe, 0xffffffff};
30 
31 }  // namespace
32 
33 namespace fxcrt {
34 
TEST(ByteOrder,ByteSwapToLE16)35 TEST(ByteOrder, ByteSwapToLE16) {
36   // Since there are so few values, test them all.
37   for (uint32_t v = 0; v < 0x10000; ++v) {
38     const uint16_t v16 = v;
39     uint16_t expected =
40         FXWORD_GET_LSBFIRST(reinterpret_cast<const uint8_t*>(&v16));
41     EXPECT_EQ(expected, ByteSwapToLE16(v16)) << v;
42   }
43 }
44 
TEST(ByteOrder,ByteSwapToLE32)45 TEST(ByteOrder, ByteSwapToLE32) {
46   for (uint32_t v : kTestValues32) {
47     uint32_t expected =
48         FXDWORD_GET_LSBFIRST(reinterpret_cast<const uint8_t*>(&v));
49     EXPECT_EQ(expected, ByteSwapToLE32(v)) << v;
50   }
51 }
52 
TEST(ByteOrder,ByteSwapToBE16)53 TEST(ByteOrder, ByteSwapToBE16) {
54   // Since there are so few values, test them all.
55   for (uint32_t v = 0; v < 0x10000; ++v) {
56     const uint16_t v16 = v;
57     uint16_t expected =
58         FXWORD_GET_MSBFIRST(reinterpret_cast<const uint8_t*>(&v16));
59     EXPECT_EQ(expected, ByteSwapToBE16(v16)) << v;
60   }
61 }
62 
TEST(ByteOrder,ByteSwapToBE32)63 TEST(ByteOrder, ByteSwapToBE32) {
64   for (uint32_t v : kTestValues32) {
65     uint32_t expected =
66         FXDWORD_GET_MSBFIRST(reinterpret_cast<const uint8_t*>(&v));
67     EXPECT_EQ(expected, ByteSwapToBE32(v)) << v;
68   }
69 }
70 
71 }  // namespace fxcrt
72