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 "chrome/browser/net/bit_stream_reader.h"
10 #include "testing/gtest/include/gtest/gtest.h"
14 const uint8_t kSomeData
[] = {0xd5, 0xe2, 0xaf, 0xe5, 0xbb, 0x10, 0x7c, 0xd1};
16 TEST(BitStreamReaderTest
, CanReadSingleByte
) {
17 BitStreamReader
reader(
18 base::StringPiece(reinterpret_cast<const char*>(kSomeData
), 1));
21 EXPECT_EQ(8u, reader
.BitsLeft());
22 EXPECT_TRUE(reader
.ReadBits(8, &v
));
23 EXPECT_EQ(UINT64_C(0xd5), v
);
25 EXPECT_FALSE(reader
.ReadBits(1, &v
));
26 EXPECT_EQ(0u, reader
.BitsLeft());
29 TEST(BitStreamReaderTest
, CanReadSingleBits
) {
30 const uint64_t expected_bits
[] = {
31 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0};
32 BitStreamReader
reader(
33 base::StringPiece(reinterpret_cast<const char*>(kSomeData
), 2));
34 EXPECT_EQ(16u, reader
.BitsLeft());
37 for (int i
= 0; i
< 16; ++i
) {
38 EXPECT_TRUE(reader
.ReadBits(1, &v
));
39 EXPECT_EQ(expected_bits
[i
], v
);
41 EXPECT_EQ(0u, reader
.BitsLeft());
44 TEST(BitStreamReaderTest
, CanReadBitGroups
) {
45 BitStreamReader
reader(
46 base::StringPiece(reinterpret_cast<const char*>(kSomeData
), 3));
47 EXPECT_EQ(24u, reader
.BitsLeft());
51 EXPECT_TRUE(reader
.ReadBits(5, &v
));
53 EXPECT_EQ(19u, reader
.BitsLeft());
54 EXPECT_TRUE(reader
.ReadBits(13, &v
));
56 EXPECT_EQ(6u, reader
.BitsLeft());
57 EXPECT_TRUE(reader
.ReadBits(6, &v
));
59 EXPECT_EQ(UINT64_C(0xd5e2af), res
);
61 EXPECT_FALSE(reader
.ReadBits(1, &v
));
64 TEST(BitStreamReaderTest
, CanRead64Bit
) {
65 BitStreamReader
reader(
66 base::StringPiece(reinterpret_cast<const char*>(kSomeData
), 8));
67 EXPECT_EQ(64u, reader
.BitsLeft());
70 EXPECT_TRUE(reader
.ReadBits(64, &v
));
71 EXPECT_EQ(UINT64_C(0xd5e2afe5bb107cd1), v
);
74 TEST(BitStreamReaderTest
, CanReadUnaryEncodedNumbers
) {
75 internal::BitStreamReader
reader(
76 base::StringPiece(reinterpret_cast<const char*>(kSomeData
), 3));
77 const uint64_t expected_values
[] = {2, 1, 1, 4, 0, 0, 1, 1, 1, 4};
79 for (int i
= 0; i
< 10; ++i
) {
80 EXPECT_TRUE(reader
.ReadUnaryEncoding(&v
));
81 EXPECT_EQ(expected_values
[i
], v
) << "Values differ at position " << i
;
85 TEST(BitStreamReaderTest
, CannotReadFromEmptyStream
) {
86 BitStreamReader
reader(base::StringPiece(
87 reinterpret_cast<const char*>(kSomeData
), static_cast<size_t>(0u)));
90 EXPECT_EQ(0u, reader
.BitsLeft());
91 EXPECT_FALSE(reader
.ReadBits(1, &v
));
92 EXPECT_FALSE(reader
.ReadUnaryEncoding(&v
));
95 } // namespace internal