1 /*
2  * Copyright 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "packet/bit_inserter.h"
18 
19 #include <gtest/gtest.h>
20 
21 #include <memory>
22 
23 using bluetooth::packet::BitInserter;
24 using std::vector;
25 
26 namespace bluetooth {
27 namespace packet {
28 
TEST(BitInserterTest,addMoreBits)29 TEST(BitInserterTest, addMoreBits) {
30   std::vector<uint8_t> bytes;
31   BitInserter it(bytes);
32 
33   for (size_t i = 0; i < 9; i++) {
34     it.insert_bits(static_cast<uint8_t>(i), i);
35   }
36   it.insert_bits(static_cast<uint8_t>(0b1010), 4);
37   std::vector<uint8_t> result = {0b00011101 /* 3 2 1 */, 0b00010101 /* 5 4 */, 0b11100011 /* 7 6 */,
38                                  0b10000000 /* 8 */, 0b10100000 /* filled with 1010 */};
39 
40   ASSERT_EQ(result.size(), bytes.size());
41   for (size_t i = 0; i < bytes.size(); i++) {
42     ASSERT_EQ(result[i], bytes[i]);
43   }
44 }
45 
TEST(BitInserterTest,observerTest)46 TEST(BitInserterTest, observerTest) {
47   std::vector<uint8_t> bytes;
48   BitInserter it(bytes);
49   std::vector<uint8_t> copy;
50 
51   uint64_t checksum = 0x0123456789abcdef;
52   it.RegisterObserver(ByteObserver([&copy](uint8_t byte) { copy.push_back(byte); },
53                                    [checksum]() { return checksum; }));
54 
55   for (size_t i = 0; i < 9; i++) {
56     it.insert_bits(static_cast<uint8_t>(i), i);
57   }
58   it.insert_bits(static_cast<uint8_t>(0b1010), 4);
59   std::vector<uint8_t> result = {0b00011101 /* 3 2 1 */, 0b00010101 /* 5 4 */, 0b11100011 /* 7 6 */,
60                                  0b10000000 /* 8 */, 0b10100000 /* filled with 1010 */};
61 
62   ASSERT_EQ(result.size(), bytes.size());
63   for (size_t i = 0; i < bytes.size(); i++) {
64     ASSERT_EQ(result[i], bytes[i]);
65   }
66 
67   ASSERT_EQ(result.size(), copy.size());
68   for (size_t i = 0; i < copy.size(); i++) {
69     ASSERT_EQ(result[i], copy[i]);
70   }
71 
72   ByteObserver observer = it.UnregisterObserver();
73   ASSERT_EQ(checksum, observer.GetValue());
74   uint8_t another_byte = 0xef;
75   it.insert_bits(another_byte, 8);
76   ASSERT_EQ(bytes.back(), another_byte);
77   ASSERT_EQ(result.size() + 1, bytes.size());
78   ASSERT_EQ(result.size(), copy.size());
79 }
80 
81 }  // namespace packet
82 }  // namespace bluetooth
83