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 "components/packed_ct_ev_whitelist/bit_stream_reader.h"
10 #include "testing/gtest/include/gtest/gtest.h"
12 namespace packed_ct_ev_whitelist
{
15 const uint8_t kSomeData
[] = {0xd5, 0xe2, 0xaf, 0xe5, 0xbb, 0x10, 0x7c, 0xd1};
17 TEST(BitStreamReaderTest
, CanReadSingleByte
) {
18 BitStreamReader
reader(
19 base::StringPiece(reinterpret_cast<const char*>(kSomeData
), 1));
22 EXPECT_EQ(8u, reader
.BitsLeft());
23 EXPECT_TRUE(reader
.ReadBits(8, &v
));
24 EXPECT_EQ(UINT64_C(0xd5), v
);
26 EXPECT_FALSE(reader
.ReadBits(1, &v
));
27 EXPECT_EQ(0u, reader
.BitsLeft());
30 TEST(BitStreamReaderTest
, CanReadSingleBits
) {
31 const uint64_t expected_bits
[] = {
32 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0};
33 BitStreamReader
reader(
34 base::StringPiece(reinterpret_cast<const char*>(kSomeData
), 2));
35 EXPECT_EQ(16u, reader
.BitsLeft());
38 for (int i
= 0; i
< 16; ++i
) {
39 EXPECT_TRUE(reader
.ReadBits(1, &v
));
40 EXPECT_EQ(expected_bits
[i
], v
);
42 EXPECT_EQ(0u, reader
.BitsLeft());
45 TEST(BitStreamReaderTest
, CanReadBitGroups
) {
46 BitStreamReader
reader(
47 base::StringPiece(reinterpret_cast<const char*>(kSomeData
), 3));
48 EXPECT_EQ(24u, reader
.BitsLeft());
52 EXPECT_TRUE(reader
.ReadBits(5, &v
));
54 EXPECT_EQ(19u, reader
.BitsLeft());
55 EXPECT_TRUE(reader
.ReadBits(13, &v
));
57 EXPECT_EQ(6u, reader
.BitsLeft());
58 EXPECT_TRUE(reader
.ReadBits(6, &v
));
60 EXPECT_EQ(UINT64_C(0xd5e2af), res
);
62 EXPECT_FALSE(reader
.ReadBits(1, &v
));
65 TEST(BitStreamReaderTest
, CanRead64Bit
) {
66 BitStreamReader
reader(
67 base::StringPiece(reinterpret_cast<const char*>(kSomeData
), 8));
68 EXPECT_EQ(64u, reader
.BitsLeft());
71 EXPECT_TRUE(reader
.ReadBits(64, &v
));
72 EXPECT_EQ(UINT64_C(0xd5e2afe5bb107cd1), v
);
75 TEST(BitStreamReaderTest
, CanReadUnaryEncodedNumbers
) {
76 internal::BitStreamReader
reader(
77 base::StringPiece(reinterpret_cast<const char*>(kSomeData
), 3));
78 const uint64_t expected_values
[] = {2, 1, 1, 4, 0, 0, 1, 1, 1, 4};
80 for (int i
= 0; i
< 10; ++i
) {
81 EXPECT_TRUE(reader
.ReadUnaryEncoding(&v
));
82 EXPECT_EQ(expected_values
[i
], v
) << "Values differ at position " << i
;
86 TEST(BitStreamReaderTest
, CannotReadFromEmptyStream
) {
87 BitStreamReader
reader(base::StringPiece(
88 reinterpret_cast<const char*>(kSomeData
), static_cast<size_t>(0u)));
91 EXPECT_EQ(0u, reader
.BitsLeft());
92 EXPECT_FALSE(reader
.ReadBits(1, &v
));
93 EXPECT_FALSE(reader
.ReadUnaryEncoding(&v
));
96 } // namespace internal
97 } // namespace packed_ct_ev_whitelist