1 // Copyright 2014 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.
5 #include "base/big_endian.h"
7 #include "base/strings/string_piece.h"
8 #include "testing/gtest/include/gtest/gtest.h"
12 TEST(BigEndianReaderTest
, ReadsValues
) {
13 char data
[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
14 0x1A, 0x2B, 0x3C, 0x4D, 0x5E };
20 base::StringPiece piece
;
21 BigEndianReader
reader(data
, sizeof(data
));
23 EXPECT_TRUE(reader
.Skip(2));
24 EXPECT_EQ(data
+ 2, reader
.ptr());
25 EXPECT_EQ(reader
.remaining(), static_cast<int>(sizeof(data
)) - 2);
26 EXPECT_TRUE(reader
.ReadBytes(buf
, sizeof(buf
)));
27 EXPECT_EQ(0x2, buf
[0]);
28 EXPECT_EQ(0x3, buf
[1]);
29 EXPECT_TRUE(reader
.ReadU8(&u8
));
31 EXPECT_TRUE(reader
.ReadU16(&u16
));
32 EXPECT_EQ(0x0506, u16
);
33 EXPECT_TRUE(reader
.ReadU32(&u32
));
34 EXPECT_EQ(0x0708090Au
, u32
);
35 EXPECT_TRUE(reader
.ReadU64(&u64
));
36 EXPECT_EQ(0x0B0C0D0E0F1A2B3Cllu
, u64
);
37 base::StringPiece
expected(reader
.ptr(), 2);
38 EXPECT_TRUE(reader
.ReadPiece(&piece
, 2));
39 EXPECT_EQ(2u, piece
.size());
40 EXPECT_EQ(expected
.data(), piece
.data());
43 TEST(BigEndianReaderTest
, RespectsLength
) {
50 base::StringPiece piece
;
51 BigEndianReader
reader(data
, sizeof(data
));
53 EXPECT_FALSE(reader
.Skip(9));
54 EXPECT_TRUE(reader
.Skip(1));
56 EXPECT_FALSE(reader
.ReadU64(&u64
));
57 EXPECT_TRUE(reader
.Skip(4));
59 EXPECT_FALSE(reader
.ReadU32(&u32
));
60 EXPECT_FALSE(reader
.ReadPiece(&piece
, 4));
61 EXPECT_TRUE(reader
.Skip(2));
63 EXPECT_FALSE(reader
.ReadU16(&u16
));
64 EXPECT_FALSE(reader
.ReadBytes(buf
, 2));
65 EXPECT_TRUE(reader
.Skip(1));
67 EXPECT_FALSE(reader
.ReadU8(&u8
));
68 EXPECT_EQ(0, reader
.remaining());
71 TEST(BigEndianWriterTest
, WritesValues
) {
72 char expected
[] = { 0, 0, 2, 3, 4, 5, 6, 7, 8, 9, 0xA, 0xB, 0xC, 0xD, 0xE,
73 0xF, 0x1A, 0x2B, 0x3C };
74 char data
[sizeof(expected
)];
75 char buf
[] = { 0x2, 0x3 };
76 memset(data
, 0, sizeof(data
));
77 BigEndianWriter
writer(data
, sizeof(data
));
79 EXPECT_TRUE(writer
.Skip(2));
80 EXPECT_TRUE(writer
.WriteBytes(buf
, sizeof(buf
)));
81 EXPECT_TRUE(writer
.WriteU8(0x4));
82 EXPECT_TRUE(writer
.WriteU16(0x0506));
83 EXPECT_TRUE(writer
.WriteU32(0x0708090A));
84 EXPECT_TRUE(writer
.WriteU64(0x0B0C0D0E0F1A2B3Cllu
));
85 EXPECT_EQ(0, memcmp(expected
, data
, sizeof(expected
)));
88 TEST(BigEndianWriterTest
, RespectsLength
) {
95 BigEndianWriter
writer(data
, sizeof(data
));
97 EXPECT_FALSE(writer
.Skip(9));
98 EXPECT_TRUE(writer
.Skip(1));
100 EXPECT_FALSE(writer
.WriteU64(u64
));
101 EXPECT_TRUE(writer
.Skip(4));
103 EXPECT_FALSE(writer
.WriteU32(u32
));
104 EXPECT_TRUE(writer
.Skip(2));
106 EXPECT_FALSE(writer
.WriteU16(u16
));
107 EXPECT_FALSE(writer
.WriteBytes(buf
, 2));
108 EXPECT_TRUE(writer
.Skip(1));
110 EXPECT_FALSE(writer
.WriteU8(u8
));
111 EXPECT_EQ(0, writer
.remaining());