• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2017 The Chromium OS 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 <cstring>
6 
7 #include "gtest/gtest.h"
8 
9 #include "puffin/src/bit_reader.h"
10 #include "puffin/src/bit_writer.h"
11 #include "puffin/src/logging.h"
12 #include "puffin/src/unittest_common.h"
13 
14 namespace puffin {
15 
16 // Testing |BufferBitReader| and |BufferBitWriter|.
TEST(BitIOTest,BitWriterAndBitReaderTest)17 TEST(BitIOTest, BitWriterAndBitReaderTest) {
18   static const size_t kSize = 5;
19   uint8_t buf[kSize];
20 
21   puffin::BufferBitWriter bw(buf, kSize);
22   ASSERT_TRUE(bw.WriteBits(0, 0x05));
23   ASSERT_TRUE(bw.WriteBits(3, 0x05));
24   ASSERT_TRUE(bw.WriteBits(8, 0xFF));
25   ASSERT_TRUE(bw.WriteBoundaryBits(0x0F));
26   uint8_t tmp[] = {1, 2};
27   size_t index = 0;
28   ASSERT_TRUE(bw.WriteBytes(2, [&tmp, &index](uint8_t* buffer, size_t count) {
29     if (count > 2 - index)
30       return false;
31     memcpy(buffer, &tmp[index], count);
32     return true;
33   }));
34   ASSERT_FALSE(bw.WriteBits(9, 0x1C));
35   ASSERT_TRUE(bw.WriteBits(4, 0x0A));
36   ASSERT_TRUE(bw.WriteBoundaryBits(0xBB));
37   ASSERT_TRUE(bw.Flush());
38   ASSERT_EQ(5, bw.Size());
39 
40   puffin::BufferBitReader br(buf, kSize);
41   ASSERT_TRUE(br.CacheBits(11));
42   ASSERT_EQ(br.ReadBits(3), 0x05);
43   br.DropBits(3);
44   ASSERT_EQ(br.ReadBits(8), 0xFF);
45   br.DropBits(8);
46   ASSERT_EQ(br.ReadBoundaryBits(), 0x0F);
47   ASSERT_EQ(br.SkipBoundaryBits(), 5);
48   std::function<bool(uint8_t*, size_t)> read_fn;
49   ASSERT_TRUE(br.GetByteReaderFn(2, &read_fn));
50   ASSERT_TRUE(read_fn(tmp, 2));
51   ASSERT_EQ(br.Offset(), 4);
52   ASSERT_TRUE(read_fn(tmp, 0));
53   ASSERT_FALSE(read_fn(tmp, 1));
54   ASSERT_FALSE(br.CacheBits(9));
55   ASSERT_TRUE(br.CacheBits(8));
56   ASSERT_EQ(br.ReadBits(4), 0x0A);
57   br.DropBits(4);
58   ASSERT_EQ(br.ReadBoundaryBits(), 0x0B);
59   ASSERT_EQ(br.SkipBoundaryBits(), 4);
60   ASSERT_EQ(br.ReadBoundaryBits(), 0);
61   ASSERT_EQ(br.SkipBoundaryBits(), 0);
62   ASSERT_FALSE(br.CacheBits(1));
63 }
64 
TEST(BitIOTest,BitsRemaining)65 TEST(BitIOTest, BitsRemaining) {
66   const size_t kSize = 5;
67   uint8_t buf[kSize];
68 
69   BufferBitReader br(buf, kSize);
70   EXPECT_EQ(br.BitsRemaining(), 40);
71   ASSERT_TRUE(br.CacheBits(1));
72   br.DropBits(1);
73   EXPECT_EQ(br.BitsRemaining(), 39);
74 
75   ASSERT_TRUE(br.CacheBits(7));
76   br.DropBits(7);
77   EXPECT_EQ(br.BitsRemaining(), 32);
78 
79   ASSERT_TRUE(br.CacheBits(31));
80   br.DropBits(31);
81   EXPECT_EQ(br.BitsRemaining(), 1);
82 
83   ASSERT_TRUE(br.CacheBits(1));
84   br.DropBits(1);
85   EXPECT_EQ(br.BitsRemaining(), 0);
86 }
87 }  // namespace puffin
88