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 #pragma once 18 19 #include <array> 20 #include <cstdint> 21 #include <vector> 22 23 #include "packet/bit_inserter.h" 24 #include "packet/packet_builder.h" 25 26 namespace bluetooth { 27 namespace packet { 28 29 class RawBuilder : public PacketBuilder<true> { 30 public: 31 RawBuilder() = default; 32 explicit RawBuilder(size_t max_bytes); 33 explicit RawBuilder(std::vector<uint8_t> vec); 34 virtual ~RawBuilder() = default; 35 36 virtual size_t size() const override; 37 38 virtual void Serialize(BitInserter& it) const; 39 40 // Return true if |num_bytes| can be added to the payload. 41 bool CanAddOctets(size_t num_bytes) const; 42 43 // Add |octets| bytes to the payload. Return true if: 44 // - the size of |bytes| is equal to |octets| and 45 // - the new size of the payload is still <= |max_bytes_| 46 bool AddOctets(size_t octets, const std::vector<uint8_t>& bytes); 47 48 // Add |N| bytes to the payload. Return true if: 49 // - the new size of the payload is still <= |max_bytes_| 50 template <std::size_t N> AddOctets(const std::array<uint8_t,N> & bytes)51 bool AddOctets(const std::array<uint8_t, N>& bytes) { 52 if (payload_.size() + N > max_bytes_) { 53 return false; 54 } 55 56 payload_.insert(payload_.end(), bytes.begin(), bytes.end()); 57 return true; 58 } 59 60 bool AddOctets(const std::vector<uint8_t>& bytes); 61 62 bool AddOctets1(uint8_t value); 63 bool AddOctets2(uint16_t value); 64 bool AddOctets3(uint32_t value); 65 bool AddOctets4(uint32_t value); 66 bool AddOctets6(uint64_t value); 67 bool AddOctets8(uint64_t value); 68 69 private: 70 // Add |octets| bytes to the payload. Return true if: 71 // - the value of |value| fits in |octets| bytes and 72 // - the new size of the payload is still <= |max_bytes_| 73 bool AddOctets(size_t octets, uint64_t value); 74 75 size_t max_bytes_{0xffff}; 76 77 // Underlying containers for storing the actual packet 78 std::vector<uint8_t> payload_; 79 }; 80 81 } // namespace packet 82 } // namespace bluetooth 83