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 };
18 base::StringPiece piece
;
19 BigEndianReader
reader(data
, sizeof(data
));
21 EXPECT_TRUE(reader
.Skip(2));
22 EXPECT_EQ(data
+ 2, reader
.ptr());
23 EXPECT_EQ(reader
.remaining(), static_cast<int>(sizeof(data
)) - 2);
24 EXPECT_TRUE(reader
.ReadBytes(buf
, sizeof(buf
)));
25 EXPECT_EQ(0x2, buf
[0]);
26 EXPECT_EQ(0x3, buf
[1]);
27 EXPECT_TRUE(reader
.ReadU8(&u8
));
29 EXPECT_TRUE(reader
.ReadU16(&u16
));
30 EXPECT_EQ(0x0506, u16
);
31 EXPECT_TRUE(reader
.ReadU32(&u32
));
32 EXPECT_EQ(0x0708090Au
, u32
);
33 base::StringPiece
expected(reader
.ptr(), 2);
34 EXPECT_TRUE(reader
.ReadPiece(&piece
, 2));
35 EXPECT_EQ(2u, piece
.size());
36 EXPECT_EQ(expected
.data(), piece
.data());
39 TEST(BigEndianReaderTest
, RespectsLength
) {
45 base::StringPiece piece
;
46 BigEndianReader
reader(data
, sizeof(data
));
48 EXPECT_FALSE(reader
.Skip(6));
49 EXPECT_TRUE(reader
.Skip(1));
51 EXPECT_FALSE(reader
.ReadU32(&u32
));
52 EXPECT_FALSE(reader
.ReadPiece(&piece
, 4));
53 EXPECT_TRUE(reader
.Skip(2));
55 EXPECT_FALSE(reader
.ReadU16(&u16
));
56 EXPECT_FALSE(reader
.ReadBytes(buf
, 2));
57 EXPECT_TRUE(reader
.Skip(1));
59 EXPECT_FALSE(reader
.ReadU8(&u8
));
60 EXPECT_EQ(0, reader
.remaining());
63 TEST(BigEndianWriterTest
, WritesValues
) {
64 char expected
[] = { 0, 0, 2, 3, 4, 5, 6, 7, 8, 9, 0xA };
65 char data
[sizeof(expected
)];
66 char buf
[] = { 0x2, 0x3 };
67 memset(data
, 0, sizeof(data
));
68 BigEndianWriter
writer(data
, sizeof(data
));
70 EXPECT_TRUE(writer
.Skip(2));
71 EXPECT_TRUE(writer
.WriteBytes(buf
, sizeof(buf
)));
72 EXPECT_TRUE(writer
.WriteU8(0x4));
73 EXPECT_TRUE(writer
.WriteU16(0x0506));
74 EXPECT_TRUE(writer
.WriteU32(0x0708090A));
75 EXPECT_EQ(0, memcmp(expected
, data
, sizeof(expected
)));
78 TEST(BigEndianWriterTest
, RespectsLength
) {
84 BigEndianWriter
writer(data
, sizeof(data
));
86 EXPECT_FALSE(writer
.Skip(6));
87 EXPECT_TRUE(writer
.Skip(1));
89 EXPECT_FALSE(writer
.WriteU32(u32
));
90 EXPECT_TRUE(writer
.Skip(2));
92 EXPECT_FALSE(writer
.WriteU16(u16
));
93 EXPECT_FALSE(writer
.WriteBytes(buf
, 2));
94 EXPECT_TRUE(writer
.Skip(1));
96 EXPECT_FALSE(writer
.WriteU8(u8
));
97 EXPECT_EQ(0, writer
.remaining());