1 // Copyright 2017 PDFium 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.
4
5 #include "core/fxcodec/jbig2/JBig2_BitStream.h"
6
7 #include <memory>
8 #include <utility>
9
10 #include "testing/gtest/include/gtest/gtest.h"
11 #include "third_party/base/ptr_util.h"
12
TEST(JBig2_BitStream,ReadNBits)13 TEST(JBig2_BitStream, ReadNBits) {
14 const uint8_t kData[] = {0xb1}; // 10110001
15 CJBig2_BitStream stream(kData, 0);
16
17 uint32_t val1;
18 EXPECT_EQ(0, stream.readNBits(1, &val1));
19 EXPECT_EQ(1U, val1);
20
21 int32_t val2;
22 EXPECT_EQ(0, stream.readNBits(1, &val2));
23 EXPECT_EQ(0, val2);
24
25 EXPECT_EQ(0, stream.readNBits(2, &val2));
26 EXPECT_EQ(3, val2);
27
28 EXPECT_EQ(0, stream.readNBits(4, &val2));
29 EXPECT_EQ(1, val2);
30 }
31
TEST(JBig2_BitStream,ReadNBitsLargerThenData)32 TEST(JBig2_BitStream, ReadNBitsLargerThenData) {
33 const uint8_t kData[] = {0xb1}; // 10110001
34 CJBig2_BitStream stream(kData, 42);
35
36 uint32_t val1;
37 EXPECT_EQ(0, stream.readNBits(10, &val1));
38 EXPECT_EQ(0xb1U, val1);
39 }
40
TEST(JBig2_BitStream,ReadNBitsNullStream)41 TEST(JBig2_BitStream, ReadNBitsNullStream) {
42 CJBig2_BitStream stream({}, 0);
43
44 uint32_t val1;
45 EXPECT_EQ(-1, stream.readNBits(1, &val1));
46
47 int32_t val2;
48 EXPECT_EQ(-1, stream.readNBits(2, &val2));
49 }
50
TEST(JBig2_BitStream,ReadNBitsOutOfBounds)51 TEST(JBig2_BitStream, ReadNBitsOutOfBounds) {
52 const uint8_t kData[] = {0xb1}; // 10110001
53 CJBig2_BitStream stream(kData, 42);
54
55 uint32_t val1;
56 EXPECT_EQ(0, stream.readNBits(8, &val1));
57
58 int32_t val2;
59 EXPECT_EQ(-1, stream.readNBits(2, &val2));
60 }
61
TEST(JBig2_BitStream,ReadNBitsWhereNIs36)62 TEST(JBig2_BitStream, ReadNBitsWhereNIs36) {
63 const uint8_t kData[] = {0xb0, 0x01, 0x00, 0x00, 0x40};
64 CJBig2_BitStream stream(kData, 42);
65
66 // This will shift off the top two bits and they end up lost.
67 uint32_t val1;
68 EXPECT_EQ(0, stream.readNBits(34, &val1));
69 EXPECT_EQ(0xc0040001U, val1);
70 }
71