1//===- unittests/Support/EndianTest.cpp - Endian.h tests ------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "gtest/gtest.h"
11#include "llvm/Support/Endian.h"
12#include "llvm/Support/DataTypes.h"
13#include <cstdlib>
14#include <ctime>
15using namespace llvm;
16using namespace support;
17
18#undef max
19
20namespace {
21
22TEST(Endian, Read) {
23  // These are 5 bytes so we can be sure at least one of the reads is unaligned.
24  unsigned char big[] = {0x00, 0x01, 0x02, 0x03, 0x04};
25  unsigned char little[] = {0x00, 0x04, 0x03, 0x02, 0x01};
26  int32_t BigAsHost = 0x00010203;
27  EXPECT_EQ(BigAsHost, (endian::read_be<int32_t, unaligned>(big)));
28  int32_t LittleAsHost = 0x02030400;
29  EXPECT_EQ(LittleAsHost, (endian::read_le<int32_t, unaligned>(little)));
30
31  EXPECT_EQ((endian::read_be<int32_t, unaligned>(big + 1)),
32            (endian::read_le<int32_t, unaligned>(little + 1)));
33}
34
35TEST(Endian, Write) {
36  unsigned char data[5];
37  endian::write_be<int32_t, unaligned>(data, -1362446643);
38  EXPECT_EQ(data[0], 0xAE);
39  EXPECT_EQ(data[1], 0xCA);
40  EXPECT_EQ(data[2], 0xB6);
41  EXPECT_EQ(data[3], 0xCD);
42  endian::write_be<int32_t, unaligned>(data + 1, -1362446643);
43  EXPECT_EQ(data[1], 0xAE);
44  EXPECT_EQ(data[2], 0xCA);
45  EXPECT_EQ(data[3], 0xB6);
46  EXPECT_EQ(data[4], 0xCD);
47
48  endian::write_le<int32_t, unaligned>(data, -1362446643);
49  EXPECT_EQ(data[0], 0xCD);
50  EXPECT_EQ(data[1], 0xB6);
51  EXPECT_EQ(data[2], 0xCA);
52  EXPECT_EQ(data[3], 0xAE);
53  endian::write_le<int32_t, unaligned>(data + 1, -1362446643);
54  EXPECT_EQ(data[1], 0xCD);
55  EXPECT_EQ(data[2], 0xB6);
56  EXPECT_EQ(data[3], 0xCA);
57  EXPECT_EQ(data[4], 0xAE);
58}
59
60TEST(Endian, PackedEndianSpecificIntegral) {
61  // These are 5 bytes so we can be sure at least one of the reads is unaligned.
62  unsigned char big[] = {0x00, 0x01, 0x02, 0x03, 0x04};
63  unsigned char little[] = {0x00, 0x04, 0x03, 0x02, 0x01};
64  big32_t    *big_val    =
65    reinterpret_cast<big32_t *>(big + 1);
66  little32_t *little_val =
67    reinterpret_cast<little32_t *>(little + 1);
68
69  EXPECT_EQ(*big_val, *little_val);
70}
71
72}
73