1 // Copyright (c) 2011 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/string_piece.h"
6 #include "net/base/big_endian.h"
7 #include "testing/gtest/include/gtest/gtest.h"
11 TEST(BigEndianReaderTest
, ReadsValues
) {
12 char data
[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xA, 0xB, 0xC };
17 base::StringPiece piece
;
18 BigEndianReader
reader(data
, sizeof(data
));
20 EXPECT_TRUE(reader
.Skip(2));
21 EXPECT_EQ(data
+ 2, reader
.ptr());
22 EXPECT_EQ(reader
.remaining(), static_cast<int>(sizeof(data
)) - 2);
23 EXPECT_TRUE(reader
.ReadBytes(buf
, sizeof(buf
)));
24 EXPECT_EQ(0x2, buf
[0]);
25 EXPECT_EQ(0x3, buf
[1]);
26 EXPECT_TRUE(reader
.ReadU8(&u8
));
28 EXPECT_TRUE(reader
.ReadU16(&u16
));
29 EXPECT_EQ(0x0506, u16
);
30 EXPECT_TRUE(reader
.ReadU32(&u32
));
31 EXPECT_EQ(0x0708090Au
, u32
);
32 base::StringPiece
expected(reader
.ptr(), 2);
33 EXPECT_TRUE(reader
.ReadPiece(&piece
, 2));
34 EXPECT_EQ(2u, piece
.size());
35 EXPECT_EQ(expected
.data(), piece
.data());
38 TEST(BigEndianReaderTest
, RespectsLength
) {
44 base::StringPiece piece
;
45 BigEndianReader
reader(data
, sizeof(data
));
47 EXPECT_FALSE(reader
.Skip(6));
48 EXPECT_TRUE(reader
.Skip(1));
50 EXPECT_FALSE(reader
.ReadU32(&u32
));
51 EXPECT_FALSE(reader
.ReadPiece(&piece
, 4));
52 EXPECT_TRUE(reader
.Skip(2));
54 EXPECT_FALSE(reader
.ReadU16(&u16
));
55 EXPECT_FALSE(reader
.ReadBytes(buf
, 2));
56 EXPECT_TRUE(reader
.Skip(1));
58 EXPECT_FALSE(reader
.ReadU8(&u8
));
59 EXPECT_EQ(0, reader
.remaining());
62 TEST(BigEndianWriterTest
, WritesValues
) {
63 char expected
[] = { 0, 0, 2, 3, 4, 5, 6, 7, 8, 9, 0xA };
64 char data
[sizeof(expected
)];
65 char buf
[] = { 0x2, 0x3 };
66 memset(data
, 0, sizeof(data
));
67 BigEndianWriter
writer(data
, sizeof(data
));
69 EXPECT_TRUE(writer
.Skip(2));
70 EXPECT_TRUE(writer
.WriteBytes(buf
, sizeof(buf
)));
71 EXPECT_TRUE(writer
.WriteU8(0x4));
72 EXPECT_TRUE(writer
.WriteU16(0x0506));
73 EXPECT_TRUE(writer
.WriteU32(0x0708090A));
74 EXPECT_EQ(0, memcmp(expected
, data
, sizeof(expected
)));
77 TEST(BigEndianWriterTest
, RespectsLength
) {
83 BigEndianWriter
writer(data
, sizeof(data
));
85 EXPECT_FALSE(writer
.Skip(6));
86 EXPECT_TRUE(writer
.Skip(1));
88 EXPECT_FALSE(writer
.WriteU32(u32
));
89 EXPECT_TRUE(writer
.Skip(2));
91 EXPECT_FALSE(writer
.WriteU16(u16
));
92 EXPECT_FALSE(writer
.WriteBytes(buf
, 2));
93 EXPECT_TRUE(writer
.Skip(1));
95 EXPECT_FALSE(writer
.WriteU8(u8
));
96 EXPECT_EQ(0, writer
.remaining());