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 #include <memory> 21 22 #include "os/log.h" 23 24 using bluetooth::packet::BitInserter; 25 using std::vector; 26 27 namespace bluetooth { 28 namespace packet { 29 30 TEST(BitInserterTest, addMoreBits) { 31 std::vector<uint8_t> bytes; 32 BitInserter it(bytes); 33 34 for (size_t i = 0; i < 9; i++) { 35 it.insert_bits(static_cast<uint8_t>(i), i); 36 } 37 it.insert_bits(static_cast<uint8_t>(0b1010), 4); 38 std::vector<uint8_t> result = {0b00011101 /* 3 2 1 */, 0b00010101 /* 5 4 */, 0b11100011 /* 7 6 */, 0b10000000 /* 8 */, 39 0b10100000 /* filled with 1010 */}; 40 41 ASSERT_EQ(result.size(), bytes.size()); 42 for (size_t i = 0; i < bytes.size(); i++) { 43 ASSERT_EQ(result[i], bytes[i]); 44 } 45 } 46 47 TEST(BitInserterTest, observerTest) { 48 std::vector<uint8_t> bytes; 49 BitInserter it(bytes); 50 std::vector<uint8_t> copy; 51 52 uint64_t checksum = 0x0123456789abcdef; 53 it.RegisterObserver(ByteObserver([©](uint8_t byte) { copy.push_back(byte); }, [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 */, 0b10000000 /* 8 */, 60 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