diff --git a/src/connectivity/bluetooth/core/bt-host/att/att.h b/src/connectivity/bluetooth/core/bt-host/att/att.h index 37d28f1473017c261afa8b9fffd5457a5b89d4b4..28007681341222ed8f00e1a8a17bab1355130da9 100644 --- a/src/connectivity/bluetooth/core/bt-host/att/att.h +++ b/src/connectivity/bluetooth/core/bt-host/att/att.h @@ -26,7 +26,8 @@ constexpr uint16_t kLEMinMTU = 23; // v5.0, Vol 3, Part G, 5.1.1 constexpr uint16_t kBREDRMinMTU = 48; -constexpr uint16_t kLEMaxMTU = hci::kMaxLEExtendedDataLength - sizeof(l2cap::BasicHeader); +constexpr uint16_t kLEMaxMTU = + hci::kMaxLEExtendedDataLength - sizeof(l2cap::BasicHeader); // The maximum length of an attribute value (v5.0, Vol 3, Part F, 3.2.9). constexpr size_t kMaxAttributeValueLength = 512; @@ -112,9 +113,8 @@ enum class UUIDType : uint8_t { }; template <UUIDType Type> -using AttributeType = - typename std::conditional<Type == UUIDType::k16Bit, uint16_t, - common::UInt128>::type; +using AttributeType = typename std::conditional<Type == UUIDType::k16Bit, + uint16_t, UInt128>::type; using AttributeType16 = AttributeType<UUIDType::k16Bit>; using AttributeType128 = AttributeType<UUIDType::k128Bit>; diff --git a/src/connectivity/bluetooth/core/bt-host/att/attribute.cc b/src/connectivity/bluetooth/core/bt-host/att/attribute.cc index 0df8fe8c1ec38c048ad9bc0c19792e61c0d3c702..d104031e01f5d4f8337aee89f67820e0d7c3e73f 100644 --- a/src/connectivity/bluetooth/core/bt-host/att/attribute.cc +++ b/src/connectivity/bluetooth/core/bt-host/att/attribute.cc @@ -7,8 +7,6 @@ namespace bt { namespace att { -using common::PeerId; - AccessRequirements::AccessRequirements() : value_(0u) {} AccessRequirements::AccessRequirements(bool encryption, bool authentication, @@ -25,8 +23,7 @@ AccessRequirements::AccessRequirements(bool encryption, bool authentication, } } -Attribute::Attribute(AttributeGrouping* group, Handle handle, - const common::UUID& type, +Attribute::Attribute(AttributeGrouping* group, Handle handle, const UUID& type, const AccessRequirements& read_reqs, const AccessRequirements& write_reqs) : group_(group), @@ -40,11 +37,11 @@ Attribute::Attribute(AttributeGrouping* group, Handle handle, Attribute::Attribute() : handle_(kInvalidHandle) {} -void Attribute::SetValue(const common::ByteBuffer& value) { +void Attribute::SetValue(const ByteBuffer& value) { ZX_DEBUG_ASSERT(value.size()); ZX_DEBUG_ASSERT(value.size() <= kMaxAttributeValueLength); ZX_DEBUG_ASSERT(!write_reqs_.allowed()); - value_ = common::DynamicByteBuffer(value); + value_ = DynamicByteBuffer(value); } bool Attribute::ReadAsync(PeerId peer_id, uint16_t offset, @@ -60,7 +57,7 @@ bool Attribute::ReadAsync(PeerId peer_id, uint16_t offset, } bool Attribute::WriteAsync(PeerId peer_id, uint16_t offset, - const common::ByteBuffer& value, + const ByteBuffer& value, WriteResultCallback result_callback) const { if (!is_initialized() || !write_handler_) return false; @@ -73,9 +70,9 @@ bool Attribute::WriteAsync(PeerId peer_id, uint16_t offset, return true; } -AttributeGrouping::AttributeGrouping(const common::UUID& group_type, +AttributeGrouping::AttributeGrouping(const UUID& group_type, Handle start_handle, size_t attr_count, - const common::ByteBuffer& decl_value) + const ByteBuffer& decl_value) : start_handle_(start_handle), active_(false) { ZX_DEBUG_ASSERT(start_handle_ != kInvalidHandle); ZX_DEBUG_ASSERT(kHandleMax - start_handle > attr_count); @@ -94,7 +91,7 @@ AttributeGrouping::AttributeGrouping(const common::UUID& group_type, } Attribute* AttributeGrouping::AddAttribute( - const common::UUID& type, const AccessRequirements& read_reqs, + const UUID& type, const AccessRequirements& read_reqs, const AccessRequirements& write_reqs) { if (complete()) return nullptr; diff --git a/src/connectivity/bluetooth/core/bt-host/att/attribute.h b/src/connectivity/bluetooth/core/bt-host/att/attribute.h index af8b291a57b5cc03173d25431d159c8928fd23ab..68f071af3a097718eb2bb72fb5b0b805463e8e88 100644 --- a/src/connectivity/bluetooth/core/bt-host/att/attribute.h +++ b/src/connectivity/bluetooth/core/bt-host/att/attribute.h @@ -90,16 +90,14 @@ class Attribute final { bool is_initialized() const { return handle_ != kInvalidHandle; } Handle handle() const { return handle_; } - const common::UUID& type() const { return type_; } + const UUID& type() const { return type_; } // The grouping that this attribute belongs to. const AttributeGrouping& group() const { return *group_; } // Returns the current attribute value. Returns nullptr if the attribute has a // dynamic value. - const common::ByteBuffer* value() const { - return value_.size() ? &value_ : nullptr; - } + const ByteBuffer* value() const { return value_.size() ? &value_ : nullptr; } // The read/write permissions of this attribute. const AccessRequirements& read_reqs() const { return read_reqs_; } @@ -109,15 +107,15 @@ class Attribute final { // cannot be overwritten. A static value cannot be assigned to an attribute // that permits writes as attribute writes need to propagate to the service // layer. - void SetValue(const common::ByteBuffer& value); + void SetValue(const ByteBuffer& value); // Handlers for reading and writing and attribute value asynchronously. A // handler must call the provided the |result_callback| to signal the end of // the operation. using ReadResultCallback = - fit::function<void(ErrorCode status, const common::ByteBuffer& value)>; + fit::function<void(ErrorCode status, const ByteBuffer& value)>; using ReadHandler = - fit::function<void(common::PeerId peer_id, Handle handle, uint16_t offset, + fit::function<void(PeerId peer_id, Handle handle, uint16_t offset, ReadResultCallback result_callback)>; void set_read_handler(ReadHandler read_handler) { read_handler_ = std::move(read_handler); @@ -127,21 +125,20 @@ class Attribute final { // a null |result_callback| using WriteResultCallback = fit::function<void(ErrorCode status)>; using WriteHandler = fit::function<void( - common::PeerId peer_id, Handle handle, uint16_t offset, - const common::ByteBuffer& value, WriteResultCallback result_callback)>; + PeerId peer_id, Handle handle, uint16_t offset, const ByteBuffer& value, + WriteResultCallback result_callback)>; void set_write_handler(WriteHandler write_handler) { write_handler_ = std::move(write_handler); } // Initiates an asynchronous read of the attribute value. Returns false if // this attribute is not dynamic. - bool ReadAsync(common::PeerId peer_id, uint16_t offset, + bool ReadAsync(PeerId peer_id, uint16_t offset, ReadResultCallback result_callback) const; // Initiates an asynchronous write of the attribute value. Returns false if // this attribute is not dynamic. - bool WriteAsync(common::PeerId peer_id, uint16_t offset, - const common::ByteBuffer& value, + bool WriteAsync(PeerId peer_id, uint16_t offset, const ByteBuffer& value, WriteResultCallback result_callback) const; private: @@ -151,20 +148,20 @@ class Attribute final { // The default constructor will construct this attribute as uninitialized. // This is intended for STL containers. Attribute(); - Attribute(AttributeGrouping* group, Handle handle, const common::UUID& type, + Attribute(AttributeGrouping* group, Handle handle, const UUID& type, const AccessRequirements& read_reqs, const AccessRequirements& write_reqs); AttributeGrouping* group_; // The group that owns this Attribute. Handle handle_; - common::UUID type_; + UUID type_; AccessRequirements read_reqs_; AccessRequirements write_reqs_; ReadHandler read_handler_; WriteHandler write_handler_; - common::DynamicByteBuffer value_; + DynamicByteBuffer value_; DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(Attribute); }; @@ -186,8 +183,8 @@ class AttributeGrouping final { // // Note: |attr_count| should not cause the group end handle to exceed // att::kHandleMax. - AttributeGrouping(const common::UUID& group_type, Handle start_handle, - size_t attr_count, const common::ByteBuffer& decl_value); + AttributeGrouping(const UUID& group_type, Handle start_handle, + size_t attr_count, const ByteBuffer& decl_value); // Inserts a new attribute into this grouping using the given parameters and // returns a pointer to it. Returns nullptr if the grouping is out of handles @@ -196,7 +193,7 @@ class AttributeGrouping final { // The caller should not hold on to the returned pointer as the Attribute // object is owned and managed by this AttributeGrouping. Attribute* AddAttribute( - const common::UUID& type, + const UUID& type, const AccessRequirements& read_reqs = AccessRequirements(), const AccessRequirements& write_reqs = AccessRequirements()); @@ -205,13 +202,13 @@ class AttributeGrouping final { return attributes_.size() == (end_handle_ - start_handle_ + 1); } - const common::UUID& group_type() const { + const UUID& group_type() const { ZX_DEBUG_ASSERT(!attributes_.empty()); return attributes_[0].type(); } // Value of the group declaration attribute. - const common::BufferView decl_value() const { + const BufferView decl_value() const { ZX_DEBUG_ASSERT(!attributes_.empty()); ZX_DEBUG_ASSERT(attributes_[0].value()); return attributes_[0].value()->view(); diff --git a/src/connectivity/bluetooth/core/bt-host/att/attribute_unittest.cc b/src/connectivity/bluetooth/core/bt-host/att/attribute_unittest.cc index c2f4c68827fd431a9b40b0ab21e2f1ef09f2410a..59e55f13044282ad11d7f5524f3a82abafa49c83 100644 --- a/src/connectivity/bluetooth/core/bt-host/att/attribute_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/att/attribute_unittest.cc @@ -11,16 +11,14 @@ namespace bt { namespace att { namespace { -using common::PeerId; - constexpr PeerId kTestPeerId(1); constexpr Handle kTestHandle = 0x0001; -constexpr common::UUID kTestType1((uint16_t)0x0001); -constexpr common::UUID kTestType2((uint16_t)0x0002); -constexpr common::UUID kTestType3((uint16_t)0x0003); -constexpr common::UUID kTestType4((uint16_t)0x0004); +constexpr UUID kTestType1((uint16_t)0x0001); +constexpr UUID kTestType2((uint16_t)0x0002); +constexpr UUID kTestType3((uint16_t)0x0003); +constexpr UUID kTestType4((uint16_t)0x0004); -const auto kTestValue = common::CreateStaticByteBuffer('t', 'e', 's', 't'); +const auto kTestValue = CreateStaticByteBuffer('t', 'e', 's', 't'); TEST(ATT_AttributeTest, AccessRequirementsDefault) { AccessRequirements reqs; @@ -76,7 +74,7 @@ TEST(ATT_AttributeTest, GroupingDeclAttr) { EXPECT_EQ(kTestHandle, decl_attr.handle()); EXPECT_EQ(kTestType1, decl_attr.type()); ASSERT_TRUE(decl_attr.value()); - EXPECT_TRUE(common::ContainersEqual(kTestValue, *decl_attr.value())); + EXPECT_TRUE(ContainersEqual(kTestValue, *decl_attr.value())); EXPECT_TRUE(decl_attr.read_reqs().allowed()); EXPECT_FALSE(decl_attr.read_reqs().encryption_required()); EXPECT_FALSE(decl_attr.read_reqs().authentication_required()); @@ -104,7 +102,7 @@ TEST(ATT_AttributeTest, GroupingAddAttribute) { EXPECT_FALSE(attr->value()); attr->SetValue(kTestValue); ASSERT_TRUE(attr->value()); - EXPECT_TRUE(common::ContainersEqual(kTestValue, *attr->value())); + EXPECT_TRUE(ContainersEqual(kTestValue, *attr->value())); // The group is not complete until |kAttrCount| attributes have been added. EXPECT_FALSE(group.complete()); @@ -152,8 +150,7 @@ TEST(ATT_AttributeTest, ReadAsync) { bool callback_called = false; auto callback = [&](ErrorCode status, const auto& value) { EXPECT_EQ(kTestStatus, status); - EXPECT_TRUE(common::ContainersEqual( - common::CreateStaticByteBuffer('h', 'i'), value)); + EXPECT_TRUE(ContainersEqual(CreateStaticByteBuffer('h', 'i'), value)); callback_called = true; }; @@ -164,7 +161,7 @@ TEST(ATT_AttributeTest, ReadAsync) { EXPECT_EQ(kTestOffset, offset); EXPECT_TRUE(result_cb); - result_cb(kTestStatus, common::CreateStaticByteBuffer('h', 'i')); + result_cb(kTestStatus, CreateStaticByteBuffer('h', 'i')); }; attr->set_read_handler(handler); @@ -176,8 +173,7 @@ TEST(ATT_AttributeTest, WriteAsyncWriteNotAllowed) { AttributeGrouping group(kTestType1, kTestHandle, 1, kTestValue); Attribute* attr = group.AddAttribute(kTestType2, AccessRequirements(), AccessRequirements()); - EXPECT_FALSE( - attr->WriteAsync(kTestPeerId, 0, common::BufferView(), [](auto) {})); + EXPECT_FALSE(attr->WriteAsync(kTestPeerId, 0, BufferView(), [](auto) {})); } TEST(ATT_AttributeTest, WriteAsyncWriteNoHandler) { @@ -186,8 +182,7 @@ TEST(ATT_AttributeTest, WriteAsyncWriteNoHandler) { kTestType2, AccessRequirements(), // read not allowed AccessRequirements(false, false, false)); // write no security - EXPECT_FALSE( - attr->WriteAsync(kTestPeerId, 0, common::BufferView(), [](auto) {})); + EXPECT_FALSE(attr->WriteAsync(kTestPeerId, 0, BufferView(), [](auto) {})); } TEST(ATT_AttributeTest, WriteAsync) { @@ -211,8 +206,7 @@ TEST(ATT_AttributeTest, WriteAsync) { EXPECT_EQ(kTestPeerId, peer_id); EXPECT_EQ(attr->handle(), handle); EXPECT_EQ(kTestOffset, offset); - EXPECT_TRUE(common::ContainersEqual( - common::CreateStaticByteBuffer('h', 'i'), value)); + EXPECT_TRUE(ContainersEqual(CreateStaticByteBuffer('h', 'i'), value)); EXPECT_TRUE(result_cb); result_cb(kTestStatus); @@ -220,8 +214,7 @@ TEST(ATT_AttributeTest, WriteAsync) { attr->set_write_handler(handler); EXPECT_TRUE(attr->WriteAsync(kTestPeerId, kTestOffset, - common::CreateStaticByteBuffer('h', 'i'), - callback)); + CreateStaticByteBuffer('h', 'i'), callback)); EXPECT_TRUE(callback_called); } diff --git a/src/connectivity/bluetooth/core/bt-host/att/bearer.cc b/src/connectivity/bluetooth/core/bt-host/att/bearer.cc index 2ad921c23a033d77ea210ac802a65794f63bdbbc..a1dd3204646a0f07f3d4aa9c0fe664390838b200 100644 --- a/src/connectivity/bluetooth/core/bt-host/att/bearer.cc +++ b/src/connectivity/bluetooth/core/bt-host/att/bearer.cc @@ -9,15 +9,11 @@ #include "src/connectivity/bluetooth/core/bt-host/common/log.h" #include "src/connectivity/bluetooth/core/bt-host/common/slab_allocator.h" #include "src/connectivity/bluetooth/core/bt-host/l2cap/channel.h" - #include "src/lib/fxl/strings/string_printf.h" namespace bt { namespace att { -using common::HostError; -using common::NewSlabBuffer; - // static constexpr Bearer::HandlerId Bearer::kInvalidHandlerId; constexpr Bearer::TransactionId Bearer::kInvalidTransactionId; @@ -176,7 +172,7 @@ fxl::RefPtr<Bearer> Bearer::Create(fbl::RefPtr<l2cap::Channel> chan) { Bearer::PendingTransaction::PendingTransaction(OpCode opcode, TransactionCallback callback, ErrorCallback error_callback, - common::ByteBufferPtr pdu) + ByteBufferPtr pdu) : opcode(opcode), callback(std::move(callback)), error_callback(std::move(error_callback)), @@ -336,8 +332,7 @@ void Bearer::ShutDownInternal(bool due_to_timeout) { ind_queue.InvokeErrorAll(status); } -bool Bearer::StartTransaction(common::ByteBufferPtr pdu, - TransactionCallback callback, +bool Bearer::StartTransaction(ByteBufferPtr pdu, TransactionCallback callback, ErrorCallback error_callback) { ZX_DEBUG_ASSERT(pdu); ZX_DEBUG_ASSERT(callback); @@ -347,13 +342,12 @@ bool Bearer::StartTransaction(common::ByteBufferPtr pdu, std::move(error_callback)); } -bool Bearer::SendWithoutResponse(common::ByteBufferPtr pdu) { +bool Bearer::SendWithoutResponse(ByteBufferPtr pdu) { ZX_DEBUG_ASSERT(pdu); return SendInternal(std::move(pdu), {}, {}); } -bool Bearer::SendInternal(common::ByteBufferPtr pdu, - TransactionCallback callback, +bool Bearer::SendInternal(ByteBufferPtr pdu, TransactionCallback callback, ErrorCallback error_callback) { ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); if (!is_open()) { @@ -445,7 +439,7 @@ void Bearer::UnregisterHandler(HandlerId id) { handlers_.erase(opcode); } -bool Bearer::Reply(TransactionId tid, common::ByteBufferPtr pdu) { +bool Bearer::Reply(TransactionId tid, ByteBufferPtr pdu) { ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); ZX_DEBUG_ASSERT(pdu); @@ -505,7 +499,7 @@ bool Bearer::ReplyWithError(TransactionId id, Handle handle, return true; } -bool Bearer::IsPacketValid(const common::ByteBuffer& packet) { +bool Bearer::IsPacketValid(const ByteBuffer& packet) { return packet.size() != 0u && packet.size() <= mtu_; } @@ -728,7 +722,7 @@ void Bearer::OnChannelClosed() { ShutDown(); } -void Bearer::OnRxBFrame(common::ByteBufferPtr sdu) { +void Bearer::OnRxBFrame(ByteBufferPtr sdu) { ZX_DEBUG_ASSERT(sdu); ZX_DEBUG_ASSERT(is_open()); ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); diff --git a/src/connectivity/bluetooth/core/bt-host/att/bearer.h b/src/connectivity/bluetooth/core/bt-host/att/bearer.h index a398290e2ac5968523c5a718301dc7097e0598a1..f9a743868f283e9c539120e980b6587eea3a1aef 100644 --- a/src/connectivity/bluetooth/core/bt-host/att/bearer.h +++ b/src/connectivity/bluetooth/core/bt-host/att/bearer.h @@ -116,7 +116,7 @@ class Bearer final : public fxl::RefCountedThreadSafe<Bearer> { // correspond to a request or indication. using TransactionCallback = fit::function<void(const PacketReader& packet)>; using ErrorCallback = fit::function<void(Status, Handle attr_in_error)>; - bool StartTransaction(common::ByteBufferPtr pdu, TransactionCallback callback, + bool StartTransaction(ByteBufferPtr pdu, TransactionCallback callback, ErrorCallback error_callback); // Sends |pdu| without initiating a transaction. Used for command and @@ -124,7 +124,7 @@ class Bearer final : public fxl::RefCountedThreadSafe<Bearer> { // // Returns false if the packet is malformed or does not correspond to a // command or notification. - bool SendWithoutResponse(common::ByteBufferPtr pdu); + bool SendWithoutResponse(ByteBufferPtr pdu); // A Handler is a function that gets invoked when the Bearer receives a PDU // that is not tied to a locally initiated transaction (see @@ -153,7 +153,7 @@ class Bearer final : public fxl::RefCountedThreadSafe<Bearer> { // Ends a currently pending transaction with the given response or // confirmation |pdu|. Returns false if |pdu| is malformed or if |id| and // |pdu| do not match a pending transaction. - bool Reply(TransactionId tid, common::ByteBufferPtr pdu); + bool Reply(TransactionId tid, ByteBufferPtr pdu); // Ends a request transaction with an error response. bool ReplyWithError(TransactionId id, Handle handle, ErrorCode error_code); @@ -168,9 +168,9 @@ class Bearer final : public fxl::RefCountedThreadSafe<Bearer> { bool Activate(); // Represents a locally initiated pending request or indication transaction. - struct PendingTransaction : common::LinkedListable<PendingTransaction> { + struct PendingTransaction : LinkedListable<PendingTransaction> { PendingTransaction(OpCode opcode, TransactionCallback callback, - ErrorCallback error_callback, common::ByteBufferPtr pdu); + ErrorCallback error_callback, ByteBufferPtr pdu); // Required fields OpCode opcode; @@ -180,7 +180,7 @@ class Bearer final : public fxl::RefCountedThreadSafe<Bearer> { ErrorCallback error_callback; // Holds the pdu while the transaction is in the send queue. - common::ByteBufferPtr pdu; + ByteBufferPtr pdu; // Contains the most recently requested security upgrade level under which // this transaction has been retried following an ATT security error. The @@ -238,19 +238,19 @@ class Bearer final : public fxl::RefCountedThreadSafe<Bearer> { void InvokeErrorAll(Status status); private: - common::LinkedList<PendingTransaction> queue_; + LinkedList<PendingTransaction> queue_; PendingTransactionPtr current_; async::Task timeout_task_; }; - bool SendInternal(common::ByteBufferPtr pdu, TransactionCallback callback, + bool SendInternal(ByteBufferPtr pdu, TransactionCallback callback, ErrorCallback error_callback); // Shuts down the link. void ShutDownInternal(bool due_to_timeout); // Returns false if |pdu| is malformed. - bool IsPacketValid(const common::ByteBuffer& pdu); + bool IsPacketValid(const ByteBuffer& pdu); // Tries to initiate the next transaction from the given |queue|. void TryStartNextTransaction(TransactionQueue* tq); @@ -285,7 +285,7 @@ class Bearer final : public fxl::RefCountedThreadSafe<Bearer> { // l2cap::Channel callbacks: void OnChannelClosed(); - void OnRxBFrame(common::ByteBufferPtr sdu); + void OnRxBFrame(ByteBufferPtr sdu); l2cap::ScopedChannel chan_; uint16_t mtu_; @@ -293,7 +293,7 @@ class Bearer final : public fxl::RefCountedThreadSafe<Bearer> { uint16_t min_mtu_; // Callback passed to l2cap::Channel::OnRxBFrame(). - fxl::CancelableCallback<void(common::ByteBufferPtr sdu)> rx_task_; + fxl::CancelableCallback<void(ByteBufferPtr sdu)> rx_task_; // Callback that wraps our internal OnChannelClosed handler. fxl::CancelableClosure chan_closed_cb_; diff --git a/src/connectivity/bluetooth/core/bt-host/att/bearer_unittest.cc b/src/connectivity/bluetooth/core/bt-host/att/bearer_unittest.cc index 05308930fac937fc7ffe817d61f0efac93777fb3..ec472941b342aabde45ea151fc6badd192a8a446 100644 --- a/src/connectivity/bluetooth/core/bt-host/att/bearer_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/att/bearer_unittest.cc @@ -11,12 +11,6 @@ namespace bt { namespace att { namespace { -using common::CreateStaticByteBuffer; -using common::HostError; -using common::LowerBits; -using common::NewBuffer; -using common::UpperBits; - constexpr OpCode kTestRequest = kFindInformationRequest; constexpr OpCode kTestResponse = kFindInformationResponse; constexpr OpCode kTestRequest2 = kExchangeMTURequest; @@ -101,8 +95,8 @@ TEST_F(ATT_BearerTest, StartTransactionErrorClosed) { TEST_F(ATT_BearerTest, StartTransactionInvalidPacket) { // Empty - EXPECT_FALSE(bearer()->StartTransaction( - std::make_unique<common::BufferView>(), NopCallback, NopErrorCallback)); + EXPECT_FALSE(bearer()->StartTransaction(std::make_unique<BufferView>(), + NopCallback, NopErrorCallback)); // Exceeds MTU. bearer()->set_mtu(1); @@ -129,7 +123,7 @@ TEST_F(ATT_BearerTest, RequestTimeout) { [&closed, &err_cb_called, this] { closed = true; }); auto err_cb = [&closed, &err_cb_called, this](Status status, Handle handle) { - EXPECT_EQ(common::HostError::kTimedOut, status.error()); + EXPECT_EQ(HostError::kTimedOut, status.error()); EXPECT_EQ(0, handle); err_cb_called = true; @@ -164,7 +158,7 @@ TEST_F(ATT_BearerTest, RequestTimeoutMany) { [&err_cb_count, &closed, this] { closed = true; }); auto err_cb = [&closed, &err_cb_count, this](Status status, Handle handle) { - EXPECT_EQ(common::HostError::kTimedOut, status.error()); + EXPECT_EQ(HostError::kTimedOut, status.error()); EXPECT_EQ(0, handle); err_cb_count++; @@ -200,7 +194,7 @@ TEST_F(ATT_BearerTest, IndicationTimeout) { [&closed, &err_cb_called, this] { closed = true; }); auto err_cb = [&closed, &err_cb_called, this](Status status, Handle handle) { - EXPECT_EQ(common::HostError::kTimedOut, status.error()); + EXPECT_EQ(HostError::kTimedOut, status.error()); EXPECT_EQ(0, handle); err_cb_called = true; @@ -236,7 +230,7 @@ TEST_F(ATT_BearerTest, IndicationTimeoutMany) { [&closed, &err_cb_count, this] { closed = true; }); auto err_cb = [&closed, &err_cb_count, this](Status status, Handle handle) { - EXPECT_EQ(common::HostError::kTimedOut, status.error()); + EXPECT_EQ(HostError::kTimedOut, status.error()); EXPECT_EQ(0, handle); err_cb_count++; @@ -266,7 +260,7 @@ TEST_F(ATT_BearerTest, ReceiveEmptyPacket) { bool closed = false; bearer()->set_closed_callback([&closed] { closed = true; }); - fake_chan()->Receive(common::BufferView()); + fake_chan()->Receive(BufferView()); RunLoopUntilIdle(); EXPECT_TRUE(closed); @@ -310,7 +304,7 @@ TEST_F(ATT_BearerTest, SendRequestWrongResponse) { bearer()->set_closed_callback([&closed, this] { closed = true; }); auto err_cb = [&err_cb_called, this](Status status, Handle handle) { - EXPECT_EQ(common::HostError::kFailed, status.error()); + EXPECT_EQ(HostError::kFailed, status.error()); EXPECT_EQ(0, handle); err_cb_called = true; @@ -349,7 +343,7 @@ TEST_F(ATT_BearerTest, SendRequestErrorResponseTooShort) { auto err_cb = [&err_cb_called, this](Status status, Handle handle) { EXPECT_EQ(0, handle); - EXPECT_EQ(common::HostError::kFailed, status.error()); + EXPECT_EQ(HostError::kFailed, status.error()); err_cb_called = true; }; @@ -387,7 +381,7 @@ TEST_F(ATT_BearerTest, SendRequestErrorResponseTooLong) { auto err_cb = [&err_cb_called, this](Status status, Handle handle) { EXPECT_EQ(0, handle); - EXPECT_EQ(common::HostError::kFailed, status.error()); + EXPECT_EQ(HostError::kFailed, status.error()); err_cb_called = true; }; @@ -430,7 +424,7 @@ TEST_F(ATT_BearerTest, SendRequestErrorResponseWrongOpCode) { auto err_cb = [&err_cb_called, this](Status status, Handle handle) { EXPECT_EQ(0, handle); - EXPECT_EQ(common::HostError::kFailed, status.error()); + EXPECT_EQ(HostError::kFailed, status.error()); err_cb_called = true; }; @@ -502,7 +496,7 @@ TEST_F(ATT_BearerTest, SendRequestSuccess) { ASSERT_FALSE(cb_called); cb_called = true; - EXPECT_TRUE(common::ContainersEqual(response, rsp_packet.data())); + EXPECT_TRUE(ContainersEqual(response, rsp_packet.data())); }; bearer()->StartTransaction(NewBuffer(kTestRequest), cb, NopErrorCallback); @@ -583,7 +577,7 @@ TEST_F(ATT_BearerTest, SendManyRequests) { // corresponding request. auto callback1 = [&success_count, &response1](const auto& rsp_packet) { EXPECT_EQ(0u, success_count); - EXPECT_TRUE(common::ContainersEqual(response1, rsp_packet.data())); + EXPECT_TRUE(ContainersEqual(response1, rsp_packet.data())); success_count++; }; bearer()->StartTransaction(NewBuffer(kTestRequest), callback1, error_cb); @@ -595,7 +589,7 @@ TEST_F(ATT_BearerTest, SendManyRequests) { auto callback3 = [&success_count, &response3](const auto& rsp_packet) { EXPECT_EQ(1u, success_count); - EXPECT_TRUE(common::ContainersEqual(response3, rsp_packet.data())); + EXPECT_TRUE(ContainersEqual(response3, rsp_packet.data())); success_count++; }; bearer()->StartTransaction(NewBuffer(kTestRequest3), callback3, error_cb); @@ -634,7 +628,7 @@ TEST_F(ATT_BearerTest, SendIndicationSuccess) { ASSERT_FALSE(cb_called); cb_called = true; - EXPECT_TRUE(common::ContainersEqual(conf, packet.data())); + EXPECT_TRUE(ContainersEqual(conf, packet.data())); }; bearer()->StartTransaction(NewBuffer(kIndication), cb, NopErrorCallback); @@ -655,8 +649,7 @@ TEST_F(ATT_BearerTest, SendWithoutResponseErrorClosed) { TEST_F(ATT_BearerTest, SendWithoutResponseInvalidPacket) { // Empty - EXPECT_FALSE( - bearer()->SendWithoutResponse(std::make_unique<common::BufferView>())); + EXPECT_FALSE(bearer()->SendWithoutResponse(std::make_unique<BufferView>())); // Exceeds MTU bearer()->set_mtu(1); @@ -747,7 +740,7 @@ TEST_F(ATT_BearerTest, RemoteTransactionNoHandler) { bool received_error_rsp = false; auto chan_cb = [&received_error_rsp, &error_rsp](auto packet) { received_error_rsp = true; - EXPECT_TRUE(common::ContainersEqual(error_rsp, *packet)); + EXPECT_TRUE(ContainersEqual(error_rsp, *packet)); }; fake_chan()->SetSendCallback(chan_cb, dispatcher()); fake_chan()->Receive(CreateStaticByteBuffer(kTestRequest)); @@ -814,7 +807,7 @@ TEST_F(ATT_BearerTest, RemoteIndicationSeqProtocolError) { TEST_F(ATT_BearerTest, ReplyInvalidPacket) { // Empty - EXPECT_FALSE(bearer()->Reply(0, std::make_unique<common::BufferView>())); + EXPECT_FALSE(bearer()->Reply(0, std::make_unique<BufferView>())); // Exceeds MTU. bearer()->set_mtu(1); @@ -975,7 +968,7 @@ TEST_F(ATT_BearerTest, ReplyWithError) { // The error response that we send below auto expected = CreateStaticByteBuffer(kErrorResponse, kTestRequest, 0x00, 0x00, ErrorCode::kUnlikelyError); - EXPECT_TRUE(common::ContainersEqual(expected, *packet)); + EXPECT_TRUE(ContainersEqual(expected, *packet)); }; fake_chan()->SetSendCallback(chan_cb, dispatcher()); diff --git a/src/connectivity/bluetooth/core/bt-host/att/database.cc b/src/connectivity/bluetooth/core/bt-host/att/database.cc index 0e790bc747e2044fb4304dc471b85e442c418f53..9cf41683266f1f51b93a849f839534d6b224f79f 100644 --- a/src/connectivity/bluetooth/core/bt-host/att/database.cc +++ b/src/connectivity/bluetooth/core/bt-host/att/database.cc @@ -15,11 +15,6 @@ namespace bt { namespace att { namespace { -using common::ByteBuffer; -using common::DynamicByteBuffer; -using common::PeerId; -using common::UUID; - bool StartLessThan(const AttributeGrouping& grp, const Handle handle) { return grp.start_handle() < handle; } diff --git a/src/connectivity/bluetooth/core/bt-host/att/database.h b/src/connectivity/bluetooth/core/bt-host/att/database.h index 270d3962d3f4031f83aad89720c6b88c23e8c3a4..06f7424085c03a6d910822a5d28c6b8723cd8d31 100644 --- a/src/connectivity/bluetooth/core/bt-host/att/database.h +++ b/src/connectivity/bluetooth/core/bt-host/att/database.h @@ -29,7 +29,7 @@ class QueuedWrite { ~QueuedWrite() = default; // Constructs a write request by copying the contents of |value|. - QueuedWrite(Handle handle, uint16_t offset, const common::ByteBuffer& value); + QueuedWrite(Handle handle, uint16_t offset, const ByteBuffer& value); // Allow move operations. QueuedWrite(QueuedWrite&&) = default; @@ -37,12 +37,12 @@ class QueuedWrite { Handle handle() const { return handle_; } uint16_t offset() const { return offset_; } - const common::ByteBuffer& value() const { return value_; } + const ByteBuffer& value() const { return value_; } private: Handle handle_; uint16_t offset_; - common::DynamicByteBuffer value_; + DynamicByteBuffer value_; }; // Represents a prepare queue used to handle the ATT Prepare Write and Execute @@ -84,7 +84,7 @@ class Database final : public fxl::RefCountedThreadSafe<Database> { // If set, |next()| will only return attributes with the given |type|. No // filter is set by default. - void set_type_filter(const common::UUID& type) { type_filter_ = type; } + void set_type_filter(const UUID& type) { type_filter_ = type; } // Returns true if the iterator cannot be advanced any further. inline bool AtEnd() const { return grp_iter_ == grp_end_; } @@ -93,8 +93,8 @@ class Database final : public fxl::RefCountedThreadSafe<Database> { inline void MarkEnd() { grp_iter_ = grp_end_; } friend class Database; - Iterator(GroupingList* list, Handle start, Handle end, - const common::UUID* type, bool groups_only); + Iterator(GroupingList* list, Handle start, Handle end, const UUID* type, + bool groups_only); Handle start_; Handle end_; @@ -102,7 +102,7 @@ class Database final : public fxl::RefCountedThreadSafe<Database> { GroupingList::iterator grp_end_; GroupingList::iterator grp_iter_; uint8_t attr_offset_; - std::optional<common::UUID> type_filter_; + std::optional<UUID> type_filter_; }; // Initializes this database to span the attribute handle range given by @@ -126,8 +126,7 @@ class Database final : public fxl::RefCountedThreadSafe<Database> { // // If |type| is not a nullptr, it will be assigned as the iterator's type // filter. - Iterator GetIterator(Handle start, Handle end, - const common::UUID* type = nullptr, + Iterator GetIterator(Handle start, Handle end, const UUID* type = nullptr, bool groups_only = false); // Creates a new attribute grouping with the given |type|. The grouping will @@ -142,9 +141,8 @@ class Database final : public fxl::RefCountedThreadSafe<Database> { // The returned pointer is owned and managed by this Database and should not // be retained by the caller. Removing the grouping will invalidate the // returned pointer. - AttributeGrouping* NewGrouping(const common::UUID& group_type, - size_t attr_count, - const common::ByteBuffer& decl_value); + AttributeGrouping* NewGrouping(const UUID& group_type, size_t attr_count, + const ByteBuffer& decl_value); // Removes the attribute grouping that has the given starting handle. Returns // false if no such grouping was found. @@ -181,7 +179,7 @@ class Database final : public fxl::RefCountedThreadSafe<Database> { // The Handle argument of |callback| is undefined if ErrorCode is // ErrorCode::kNoError and should be ignored. using WriteCallback = fit::function<void(Handle, ErrorCode)>; - void ExecuteWriteQueue(common::PeerId peer_id, PrepareWriteQueue write_queue, + void ExecuteWriteQueue(PeerId peer_id, PrepareWriteQueue write_queue, const sm::SecurityProperties& security, WriteCallback callback); @@ -199,7 +197,7 @@ class Database final : public fxl::RefCountedThreadSafe<Database> { // represent contiguous handle ranges as any grouping can be removed. // // Note: This uses a std::list because fbl::lower_bound doesn't work with a - // common::LinkedList (aka fbl::DoublyLinkedList). This is only marginally + // LinkedList (aka fbl::DoublyLinkedList). This is only marginally // less space efficient. GroupingList groupings_; diff --git a/src/connectivity/bluetooth/core/bt-host/att/database_unittest.cc b/src/connectivity/bluetooth/core/bt-host/att/database_unittest.cc index 869df6a29d2d8dce371ee7ee4e85364baab380b7..a31f5b811581a871701b03b616e9125a11db41ea 100644 --- a/src/connectivity/bluetooth/core/bt-host/att/database_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/att/database_unittest.cc @@ -13,26 +13,20 @@ namespace bt { namespace att { namespace { -using common::BufferView; -using common::ByteBuffer; -using common::ContainersEqual; -using common::DynamicByteBuffer; -using common::PeerId; - constexpr Handle kTestRangeStart = 1; constexpr Handle kTestRangeEnd = 10; -constexpr common::UUID kTestType1((uint16_t)1); -constexpr common::UUID kTestType2((uint16_t)2); -constexpr common::UUID kTestType3((uint16_t)3); +constexpr UUID kTestType1((uint16_t)1); +constexpr UUID kTestType2((uint16_t)2); +constexpr UUID kTestType3((uint16_t)3); const AccessRequirements kAllowed(false, false, false); const sm::SecurityProperties kNoSecurity(sm::SecurityLevel::kNoSecurity, 16, false); // Values with different lengths -const auto kTestValue1 = common::CreateStaticByteBuffer('x', 'x'); -const auto kTestValue2 = common::CreateStaticByteBuffer('x', 'x', 'x'); +const auto kTestValue1 = CreateStaticByteBuffer('x', 'x'); +const auto kTestValue2 = CreateStaticByteBuffer('x', 'x', 'x'); // Returns the handles of each attribute visited by advancing |iter| until the // end. diff --git a/src/connectivity/bluetooth/core/bt-host/att/packet.cc b/src/connectivity/bluetooth/core/bt-host/att/packet.cc index 9e88b975a9e7c6229cbbf61325da3156bf54c70f..144b334c74a0edab56d8f34260b6ca678d957865 100644 --- a/src/connectivity/bluetooth/core/bt-host/att/packet.cc +++ b/src/connectivity/bluetooth/core/bt-host/att/packet.cc @@ -7,12 +7,11 @@ namespace bt { namespace att { -PacketReader::PacketReader(const common::ByteBuffer* buffer) - : common::PacketView<Header>(buffer, buffer->size() - sizeof(Header)) {} +PacketReader::PacketReader(const ByteBuffer* buffer) + : PacketView<Header>(buffer, buffer->size() - sizeof(Header)) {} -PacketWriter::PacketWriter(OpCode opcode, common::MutableByteBuffer* buffer) - : common::MutablePacketView<Header>(buffer, - buffer->size() - sizeof(Header)) { +PacketWriter::PacketWriter(OpCode opcode, MutableByteBuffer* buffer) + : MutablePacketView<Header>(buffer, buffer->size() - sizeof(Header)) { mutable_header()->opcode = opcode; } diff --git a/src/connectivity/bluetooth/core/bt-host/att/packet.h b/src/connectivity/bluetooth/core/bt-host/att/packet.h index 0a5b2326fab9dc11064a8609e18847f6c81b69e9..44d4b1a84fff209c30bc743aeaf400185376fa9b 100644 --- a/src/connectivity/bluetooth/core/bt-host/att/packet.h +++ b/src/connectivity/bluetooth/core/bt-host/att/packet.h @@ -14,17 +14,17 @@ namespace att { // Utilities for processing ATT protocol Packets. -class PacketReader : public common::PacketView<Header> { +class PacketReader : public PacketView<Header> { public: - explicit PacketReader(const common::ByteBuffer* buffer); + explicit PacketReader(const ByteBuffer* buffer); inline OpCode opcode() const { return header().opcode; } }; -class PacketWriter : public common::MutablePacketView<Header> { +class PacketWriter : public MutablePacketView<Header> { public: // Constructor writes |opcode| into |buffer|. - PacketWriter(OpCode opcode, common::MutableByteBuffer* buffer); + PacketWriter(OpCode opcode, MutableByteBuffer* buffer); }; } // namespace att diff --git a/src/connectivity/bluetooth/core/bt-host/att/status.cc b/src/connectivity/bluetooth/core/bt-host/att/status.cc index b8a01ef244ee2f608dd0184ce442e87148763003..4a6ec6ac8d5f824aae364d4cd852eed8fa993d41 100644 --- a/src/connectivity/bluetooth/core/bt-host/att/status.cc +++ b/src/connectivity/bluetooth/core/bt-host/att/status.cc @@ -5,7 +5,6 @@ #include "status.h" namespace bt { -namespace common { namespace { std::string ErrorToString(att::ErrorCode ecode) { @@ -62,5 +61,4 @@ std::string ProtocolErrorTraits<att::ErrorCode>::ToString( static_cast<unsigned int>(ecode)); } -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/att/status.h b/src/connectivity/bluetooth/core/bt-host/att/status.h index 51bfedaf6069598d11485a06f6f8299abc24e795..6c0a914dcc340d8e0de9f70a37ff326232bd65ad 100644 --- a/src/connectivity/bluetooth/core/bt-host/att/status.h +++ b/src/connectivity/bluetooth/core/bt-host/att/status.h @@ -11,18 +11,15 @@ #include "src/connectivity/bluetooth/core/bt-host/common/status.h" namespace bt { -namespace common { template <> struct ProtocolErrorTraits<att::ErrorCode> { static std::string ToString(att::ErrorCode ecode); }; -} // namespace common - namespace att { -using Status = common::Status<ErrorCode>; +using Status = bt::Status<ErrorCode>; // Copyable callback for reporting a Status. using StatusCallback = fit::function<void(att::Status)>; diff --git a/src/connectivity/bluetooth/core/bt-host/common/byte_buffer.cc b/src/connectivity/bluetooth/core/bt-host/common/byte_buffer.cc index 16341020c5e24275aa6b5e44f2d834a01d5a0558..50013cd0381ed018a9025fd483352f2ad2d62a1c 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/byte_buffer.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/byte_buffer.cc @@ -5,7 +5,6 @@ #include "byte_buffer.h" namespace bt { -namespace common { size_t ByteBuffer::Copy(MutableByteBuffer* out_buffer, size_t pos, size_t size) const { @@ -174,5 +173,4 @@ uint8_t* MutableBufferView::mutable_data() { return bytes_; } void MutableBufferView::Fill(uint8_t value) { memset(bytes_, value, size_); } -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h b/src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h index d7083d6bf2fbb611ae0587b42a8be20d771e1fb4..f737c34b90b44fada7050fe14fc9f5bd9e001ceb 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h +++ b/src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h @@ -17,7 +17,6 @@ #include "src/lib/fxl/strings/string_view.h" namespace bt { -namespace common { class BufferView; class MutableBufferView; @@ -213,7 +212,7 @@ class StaticByteBuffer : public MutableByteBuffer { // way one can construct a StaticByteBuffer without hard-coding the size of the // buffer like so: // -// auto buffer = common::CreateStaticByteBuffer(0x01, 0x02, 0x03); +// auto buffer = CreateStaticByteBuffer(0x01, 0x02, 0x03); // template <typename... T> StaticByteBuffer<sizeof...(T)> CreateStaticByteBuffer(T... bytes) { @@ -326,7 +325,6 @@ class MutableBufferView final : public MutableByteBuffer { uint8_t* bytes_; }; -} // namespace common } // namespace bt #endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_BYTE_BUFFER_H_ diff --git a/src/connectivity/bluetooth/core/bt-host/common/byte_buffer_unittest.cc b/src/connectivity/bluetooth/core/bt-host/common/byte_buffer_unittest.cc index 4d52b8253eefd0d056cc2d9f77a43bc02c41fd86..b22777b5c53e7a3b822d72bf1c14038aa9b1af58 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/byte_buffer_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/byte_buffer_unittest.cc @@ -5,11 +5,9 @@ #include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" #include "gtest/gtest.h" - #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" namespace bt { -namespace common { namespace { TEST(ByteBufferTest, StaticByteBuffer) { @@ -155,7 +153,7 @@ TEST(ByteBufferTest, MutableBufferViewTest) { } TEST(ByteBufferTest, Copy) { - auto buffer = common::CreateStaticByteBuffer('T', 'e', 's', 't'); + auto buffer = CreateStaticByteBuffer('T', 'e', 's', 't'); BufferView empty_buffer; // Create a large enough buffer. @@ -196,7 +194,7 @@ TEST(ByteBufferTest, Copy) { } TEST(ByteBufferTest, View) { - auto buffer = common::CreateStaticByteBuffer('T', 'e', 's', 't'); + auto buffer = CreateStaticByteBuffer('T', 'e', 's', 't'); BufferView empty_buffer; BufferView view = empty_buffer.view(); @@ -222,7 +220,7 @@ TEST(ByteBufferTest, View) { } TEST(ByteBufferTest, MutableView) { - auto buffer = common::CreateStaticByteBuffer('T', 'e', 's', 't'); + auto buffer = CreateStaticByteBuffer('T', 'e', 's', 't'); MutableBufferView empty_buffer; MutableBufferView view; @@ -254,31 +252,29 @@ TEST(ByteBufferTest, MutableView) { } TEST(ByteBufferTest, ByteBufferEqualityFail) { - const auto kData0 = common::CreateStaticByteBuffer('T', 'e', 's', 't'); - const auto kData1 = common::CreateStaticByteBuffer('F', 'o', 'o'); + const auto kData0 = CreateStaticByteBuffer('T', 'e', 's', 't'); + const auto kData1 = CreateStaticByteBuffer('F', 'o', 'o'); EXPECT_FALSE(kData0 == kData1); } TEST(ByteBufferTest, ByteBufferEqualitySuccess) { - const auto kData0 = common::CreateStaticByteBuffer('T', 'e', 's', 't'); - const auto kData1 = common::CreateStaticByteBuffer('T', 'e', 's', 't'); + const auto kData0 = CreateStaticByteBuffer('T', 'e', 's', 't'); + const auto kData1 = CreateStaticByteBuffer('T', 'e', 's', 't'); EXPECT_TRUE(kData0 == kData1); } TEST(ByteBufferTest, MutableByteBufferWrite) { - const auto kData0 = common::CreateStaticByteBuffer('T', 'e', 's', 't'); - const auto kData1 = common::CreateStaticByteBuffer('F', 'o', 'o'); + const auto kData0 = CreateStaticByteBuffer('T', 'e', 's', 't'); + const auto kData1 = CreateStaticByteBuffer('F', 'o', 'o'); - auto buffer = - common::CreateStaticByteBuffer('X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'); + auto buffer = CreateStaticByteBuffer('X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'); EXPECT_EQ("XXXXXXXX", buffer.AsString()); buffer.Write(kData0); EXPECT_EQ("TestXXXX", buffer.AsString()); // Write from raw pointer. - buffer = - common::CreateStaticByteBuffer('X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'); + buffer = CreateStaticByteBuffer('X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'); buffer.Write(kData0.data(), kData0.size()); EXPECT_EQ("TestXXXX", buffer.AsString()); @@ -291,8 +287,7 @@ TEST(ByteBufferTest, MutableByteBufferWrite) { EXPECT_EQ("TFoFooXX", buffer.AsString()); // Writing zero bytes should have no effect. - buffer = - common::CreateStaticByteBuffer('X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'); + buffer = CreateStaticByteBuffer('X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'); buffer.Write(kData1.data(), 0u); buffer.Write(nullptr, 0u); // Passing nullptr is OK when size is 0 EXPECT_EQ("XXXXXXXX", buffer.AsString()); @@ -304,7 +299,7 @@ TEST(ByteBufferTest, MutableByteBufferWrite) { } TEST(ByteBufferTest, AsString) { - auto buffer = common::CreateStaticByteBuffer('T', 'e', 's', 't'); + auto buffer = CreateStaticByteBuffer('T', 'e', 's', 't'); EXPECT_EQ("Test", buffer.AsString()); } @@ -315,5 +310,4 @@ TEST(ByteBufferTest, Fill) { } } // namespace -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/common/device_address.cc b/src/connectivity/bluetooth/core/bt-host/common/device_address.cc index 5b43068af70dbecd2146c3f4c352f84e97ec9b99..e3e0b1d20e987591550e2d942da0bfd9dbb35e52 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/device_address.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/device_address.cc @@ -11,7 +11,6 @@ #include "src/lib/fxl/strings/string_printf.h" namespace bt { -namespace common { namespace { std::string TypeToString(DeviceAddress::Type type) { @@ -31,16 +30,14 @@ std::string TypeToString(DeviceAddress::Type type) { } // namespace -DeviceAddressBytes::DeviceAddressBytes() { - SetToZero(); -} +DeviceAddressBytes::DeviceAddressBytes() { SetToZero(); } DeviceAddressBytes::DeviceAddressBytes( std::array<uint8_t, kDeviceAddressSize> bytes) { bytes_ = std::move(bytes); } -DeviceAddressBytes::DeviceAddressBytes(const common::ByteBuffer& bytes) { +DeviceAddressBytes::DeviceAddressBytes(const ByteBuffer& bytes) { ZX_DEBUG_ASSERT(bytes.size() == bytes_.size()); std::copy(bytes.cbegin(), bytes.cend(), bytes_.begin()); } @@ -79,9 +76,7 @@ std::string DeviceAddressBytes::ToString() const { bytes_[0]); } -void DeviceAddressBytes::SetToZero() { - bytes_.fill(0); -} +void DeviceAddressBytes::SetToZero() { bytes_.fill(0); } std::size_t DeviceAddressBytes::Hash() const { uint64_t bytes_as_int = 0; @@ -139,13 +134,12 @@ std::string DeviceAddress::ToString() const { return TypeToString(type_) + value_.ToString(); } -} // namespace common } // namespace bt namespace std { -hash<bt::common::DeviceAddress>::result_type hash< - bt::common::DeviceAddress>::operator()(argument_type const& value) const { +hash<bt::DeviceAddress>::result_type hash<bt::DeviceAddress>::operator()( + argument_type const& value) const { return value.Hash(); } diff --git a/src/connectivity/bluetooth/core/bt-host/common/device_address.h b/src/connectivity/bluetooth/core/bt-host/common/device_address.h index c09f294c70d2be096a78871c82eadb39e5327a7e..53e6c0635f005ef83f5227df5a7d09c0f099cdb1 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/device_address.h +++ b/src/connectivity/bluetooth/core/bt-host/common/device_address.h @@ -5,16 +5,15 @@ #ifndef SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_DEVICE_ADDRESS_H_ #define SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_DEVICE_ADDRESS_H_ +#include <fbl/string_piece.h> + #include <array> #include <initializer_list> #include <string> -#include <fbl/string_piece.h> - #include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" namespace bt { -namespace common { const size_t kDeviceAddressSize = 6; @@ -27,7 +26,7 @@ class DeviceAddressBytes { // Initializes the contents from |bytes|. explicit DeviceAddressBytes(std::array<uint8_t, kDeviceAddressSize> bytes); - explicit DeviceAddressBytes(const common::ByteBuffer& bytes); + explicit DeviceAddressBytes(const ByteBuffer& bytes); // Initializes the contents from a string of the form XX:XX:XX:XX:XX:XX where // each "XX" is an ASCII encoded two-digit hexadecimal integer. @@ -153,7 +152,6 @@ class DeviceAddress { static_assert(sizeof(DeviceAddress) == 8, "DeviceAddress must take up exactly 8 bytes"); -} // namespace common } // namespace bt // Custom specialization of std::hash to support unordered associative @@ -161,8 +159,8 @@ static_assert(sizeof(DeviceAddress) == 8, namespace std { template <> -struct hash<bt::common::DeviceAddress> { - using argument_type = bt::common::DeviceAddress; +struct hash<bt::DeviceAddress> { + using argument_type = bt::DeviceAddress; using result_type = std::size_t; result_type operator()(argument_type const& value) const; diff --git a/src/connectivity/bluetooth/core/bt-host/common/device_address_unittest.cc b/src/connectivity/bluetooth/core/bt-host/common/device_address_unittest.cc index 2d94c5f2fd0551874e17b0cb864e761431077f70..17a30c6d3458f49fba09098258f3285bf849486f 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/device_address_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/device_address_unittest.cc @@ -10,7 +10,6 @@ #include "gtest/gtest.h" namespace bt { -namespace common { namespace { // Initialize from string literal. @@ -180,5 +179,4 @@ TEST(DeviceAddressTest, IsPublic) { } } // namespace -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/common/device_class.cc b/src/connectivity/bluetooth/core/bt-host/common/device_class.cc index a0cb26e28d1c6232404869af9cd7c319fd819672..fc8d6c9f5d2fff791f83a5eed9a034587fd10ecb 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/device_class.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/device_class.cc @@ -7,7 +7,6 @@ #include <zircon/assert.h> namespace bt { -namespace common { namespace { @@ -141,5 +140,4 @@ std::string DeviceClass::ToString() const { return "(unknown)"; } -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/common/device_class.h b/src/connectivity/bluetooth/core/bt-host/common/device_class.h index c8bb1885cd28d2f31afa01cd0a9b077e0d4f6ee4..d5f81e1354958d7ceef1541c70101920058713e1 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/device_class.h +++ b/src/connectivity/bluetooth/core/bt-host/common/device_class.h @@ -11,7 +11,6 @@ #include <unordered_set> namespace bt { -namespace common { // Represents a 24-bit "Class of Device/Service" field. // This data structure can be directly serialized into HCI command payloads. @@ -84,7 +83,6 @@ class DeviceClass { static_assert(sizeof(DeviceClass) == 3, "DeviceClass must take up exactly 3 bytes"); -} // namespace common } // namespace bt #endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_DEVICE_CLASS_H_ diff --git a/src/connectivity/bluetooth/core/bt-host/common/device_class_unittest.cc b/src/connectivity/bluetooth/core/bt-host/common/device_class_unittest.cc index 0d8582c167a6ffd691b367659fc847620a8b9137..f96b4b2441837e6668b9f370006a2d3de94bf6db 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/device_class_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/device_class_unittest.cc @@ -7,7 +7,6 @@ #include "gtest/gtest.h" namespace bt { -namespace common { namespace { struct TestPayload { @@ -86,5 +85,4 @@ TEST(DeviceClassTest, Comparison) { } } // namespace -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/common/identifier.cc b/src/connectivity/bluetooth/core/bt-host/common/identifier.cc index 681c6c7b71820f8cc6c78a804422712c2c99531f..5030559e4c7666fbb658d3f324f8188d1eec894a 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/identifier.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/identifier.cc @@ -7,7 +7,6 @@ #include "random.h" namespace bt { -namespace common { PeerId RandomPeerId() { PeerId id = kInvalidPeerId; @@ -21,5 +20,4 @@ PeerId RandomPeerId() { return id; } -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/common/identifier.h b/src/connectivity/bluetooth/core/bt-host/common/identifier.h index 8e4fbdcf001aea8d0bf1306fdb24a7fd6ca23e16..9d14ca5bc66fc5d1d7df04a9263eb17abc5765ef 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/identifier.h +++ b/src/connectivity/bluetooth/core/bt-host/common/identifier.h @@ -12,7 +12,6 @@ #include "src/lib/fxl/strings/string_printf.h" namespace bt { -namespace common { template <typename T> struct IdentifierTraits { @@ -73,22 +72,21 @@ constexpr PeerId kInvalidPeerId(0u); // kInvalidPeerId. PeerId RandomPeerId(); -} // namespace common } // namespace bt // Specialization of std::hash for std::unordered_set, std::unordered_map, etc. namespace std { template <typename T> -struct hash<bt::common::Identifier<T>> { - size_t operator()(const bt::common::Identifier<T>& id) const { +struct hash<bt::Identifier<T>> { + size_t operator()(const bt::Identifier<T>& id) const { return std::hash<T>()(id.value()); } }; template <> -struct hash<bt::common::PeerId> { - size_t operator()(const bt::common::PeerId& id) const { +struct hash<bt::PeerId> { + size_t operator()(const bt::PeerId& id) const { return std::hash<decltype(id.value())>()(id.value()); } }; diff --git a/src/connectivity/bluetooth/core/bt-host/common/identifier_unittest.cc b/src/connectivity/bluetooth/core/bt-host/common/identifier_unittest.cc index 3300153c46f5a12c39378ba67c6b9deedd034800..d539abfdd9085ad41d9586b4ac6234eb84622b3d 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/identifier_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/identifier_unittest.cc @@ -9,7 +9,6 @@ #include "gtest/gtest.h" namespace bt { -namespace common { namespace { constexpr Identifier<int> id1(1); @@ -61,5 +60,4 @@ TEST(IdentifierTest, PeerIdIsValid) { } } // namespace -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/common/linked_list.h b/src/connectivity/bluetooth/core/bt-host/common/linked_list.h index 19564d964f8b8b62649ffdf663304afb296ba789..ce4fb1e156a7b4411a60f897a042682cc69beab1 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/linked_list.h +++ b/src/connectivity/bluetooth/core/bt-host/common/linked_list.h @@ -5,12 +5,11 @@ #ifndef SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_LINKED_LIST_H_ #define SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_LINKED_LIST_H_ -#include <memory> - #include <fbl/intrusive_double_list.h> +#include <memory> + namespace bt { -namespace common { // TODO(armansito): Use this in more places where it makes sense (see NET-176). @@ -29,7 +28,6 @@ using LinkedList = fbl::DoublyLinkedList<std::unique_ptr<T>>; template <typename T> using LinkedListable = fbl::DoublyLinkedListable<std::unique_ptr<T>>; -} // namespace common } // namespace bt #endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_LINKED_LIST_H_ diff --git a/src/connectivity/bluetooth/core/bt-host/common/log.cc b/src/connectivity/bluetooth/core/bt-host/common/log.cc index db6861079b07ea0ed3d21299711d1c6e56cc0893..188ef7be29d4b22d2b1d32d9a681f01e6f2f4739 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/log.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/log.cc @@ -4,15 +4,14 @@ #include "log.h" +#include <ddk/debug.h> #include <stdarg.h> -#include <algorithm> -#include <ddk/debug.h> +#include <algorithm> #include "src/lib/fxl/strings/string_printf.h" namespace bt { -namespace common { namespace { std::atomic_int g_printf_min_severity(-1); @@ -75,5 +74,4 @@ void UsePrintf(LogSeverity min_severity) { g_printf_min_severity = static_cast<int>(min_severity); } -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/common/log.h b/src/connectivity/bluetooth/core/bt-host/common/log.h index 48500e5b05860f7ec235478d50b56fe5e233531c..b2a90a29ef6090aa9fd3870fa72f0fa3cae6ee2c 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/log.h +++ b/src/connectivity/bluetooth/core/bt-host/common/log.h @@ -5,10 +5,10 @@ #ifndef SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_LOG_H_ #define SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_LOG_H_ -#include <cstddef> - #include <ddk/driver.h> +#include <cstddef> + #include "src/lib/fxl/compiler_specific.h" // Logging utilities for the host library. This provides a common abstraction @@ -54,7 +54,7 @@ // enable this mode, call the UsePrintf() function at process start-up: // // int main() { -// bt::common::UsePrintf(bt::common::LogSeverity::ERROR); +// bt::UsePrintf(bt::LogSeverity::ERROR); // // ...do stuff... // @@ -80,11 +80,10 @@ // BT_DECLARE_FAKE_DRIVER(); // // int main() { -// bt::common::UsePrintf(bt::common::LogSeverity::TRACE); +// bt::UsePrintf(bt::LogSeverity::TRACE); // } namespace bt { -namespace common { // Log severity levels used by the host library, following the convention of // <ddk/debug.h> @@ -119,15 +118,13 @@ void LogMessage(const char* file, int line, LogSeverity severity, void UsePrintf(LogSeverity min_severity); -} // namespace common } // namespace bt -#define bt_log(flag, tag, fmt...) \ - do { \ - if (bt::common::IsLogLevelEnabled(bt::common::LogSeverity::flag)) { \ - bt::common::LogMessage(__FILE__, __LINE__, \ - bt::common::LogSeverity::flag, tag, fmt); \ - } \ +#define bt_log(flag, tag, fmt...) \ + do { \ + if (bt::IsLogLevelEnabled(bt::LogSeverity::flag)) { \ + bt::LogMessage(__FILE__, __LINE__, bt::LogSeverity::flag, tag, fmt); \ + } \ } while (0) #define BT_DECLARE_FAKE_DRIVER() zx_driver_rec_t __zircon_driver_rec__ = {}; diff --git a/src/connectivity/bluetooth/core/bt-host/common/manufacturer_names.cc b/src/connectivity/bluetooth/core/bt-host/common/manufacturer_names.cc index dca29a597fcef11b4a5ca67b43942ce6063658e6..5a96dd0ba6964468522f50c61f08a928be41ca1e 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/manufacturer_names.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/manufacturer_names.cc @@ -9,7 +9,6 @@ #include "src/lib/fxl/arraysize.h" namespace bt { -namespace common { namespace { // The company identifiers have been taken from the Bluetooth SIG Assigned @@ -1212,5 +1211,4 @@ std::string GetManufacturerName(uint16_t manufacturer_id) { return kManufacturers[manufacturer_id]; } -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/common/manufacturer_names.h b/src/connectivity/bluetooth/core/bt-host/common/manufacturer_names.h index f699a84f88ad07b5674c8bfaa1dffc0c48872fae..b1deebf2005310bf4fba1ac4a9b1e395aa032850 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/manufacturer_names.h +++ b/src/connectivity/bluetooth/core/bt-host/common/manufacturer_names.h @@ -9,14 +9,12 @@ #include <string> namespace bt { -namespace common { // Returns a manufacturer name as a string for the given company identifier. If // |manufacturer_id| does not match a known company then an empty string will be // returned. std::string GetManufacturerName(uint16_t manufacturer_id); -} // namespace common } // namespace bt #endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_MANUFACTURER_NAMES_H_ diff --git a/src/connectivity/bluetooth/core/bt-host/common/manufacturer_names_unittest.cc b/src/connectivity/bluetooth/core/bt-host/common/manufacturer_names_unittest.cc index e960c3ec8e7a4292062b56d858fc0d175404e170..4d6b7f393d0fc0da357e756978a7d6388fe7becc 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/manufacturer_names_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/manufacturer_names_unittest.cc @@ -7,7 +7,6 @@ #include "gtest/gtest.h" namespace bt { -namespace common { namespace { TEST(ManufacturerNamesTest, ExhaustiveLookUp) { @@ -26,5 +25,4 @@ TEST(ManufacturerNamesTest, ExhaustiveLookUp) { } } // namespace -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/common/packet_view.h b/src/connectivity/bluetooth/core/bt-host/common/packet_view.h index 9abffb974b2d7a45908bc8bb06be86704f4395cb..cb6831b530293dc2bdf6861c0cb58f2dc12a8110 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/packet_view.h +++ b/src/connectivity/bluetooth/core/bt-host/common/packet_view.h @@ -5,14 +5,13 @@ #ifndef SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_PACKET_VIEW_H_ #define SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_PACKET_VIEW_H_ -#include <cstdint> - #include <zircon/assert.h> +#include <cstdint> + #include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" namespace bt { -namespace common { // Base class-template for generic packets that contain a header and a payload. // A PacketView is a light-weight object that operates over a previously @@ -99,9 +98,7 @@ class PacketView { // A PacketView that contains no backing buffer is considered invalid. A // PacketView that was initialized with a buffer that is too small is invalid. - bool is_valid() const { - return buffer_ && size_ >= sizeof(HeaderType); - } + bool is_valid() const { return buffer_ && size_ >= sizeof(HeaderType); } // Adjusts the size of this PacketView to match the given |payload_size|. This // is useful when the exact packet size is not known during construction. @@ -171,7 +168,6 @@ class MutablePacketView : public PacketView<HeaderType> { } }; -} // namespace common } // namespace bt #endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_PACKET_VIEW_H_ diff --git a/src/connectivity/bluetooth/core/bt-host/common/packet_view_unittest.cc b/src/connectivity/bluetooth/core/bt-host/common/packet_view_unittest.cc index 8ac8b91ff2722b671d4f5ce3969459d6fe878846..c0dea8f2f6253fea716d9620276fb22c1a6686a1 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/packet_view_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/packet_view_unittest.cc @@ -7,12 +7,10 @@ #include <string> #include "gtest/gtest.h" - #include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" namespace bt { -namespace common { namespace { struct TestHeader { @@ -88,5 +86,4 @@ TEST(PacketViewTest, NonEmptyPayload) { } } // namespace -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/common/random.h b/src/connectivity/bluetooth/core/bt-host/common/random.h index f7c510bf3e93807dc312c4e165299437dded0dd3..9ab5c93fa74222840156283baaeb670df06ceda6 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/random.h +++ b/src/connectivity/bluetooth/core/bt-host/common/random.h @@ -8,7 +8,6 @@ #include <zircon/syscalls.h> namespace bt { -namespace common { template <typename T> T Random() { @@ -19,7 +18,6 @@ T Random() { return t; } -} // namespace common } // namespace bt #endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_RANDOM_H_ diff --git a/src/connectivity/bluetooth/core/bt-host/common/run_or_post.cc b/src/connectivity/bluetooth/core/bt-host/common/run_or_post.cc index 5b16ae1c9d475c77c05c817367e5d5d47a7b1c9f..d958ae384b4f69a701a1116572ecdce1d2c8af41 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/run_or_post.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/run_or_post.cc @@ -8,7 +8,6 @@ #include <zircon/assert.h> namespace bt { -namespace common { void RunOrPost(fit::closure task, async_dispatcher_t* dispatcher) { ZX_DEBUG_ASSERT(task); @@ -21,5 +20,4 @@ void RunOrPost(fit::closure task, async_dispatcher_t* dispatcher) { async::PostTask(dispatcher, std::move(task)); } -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/common/run_or_post.h b/src/connectivity/bluetooth/core/bt-host/common/run_or_post.h index 03d6d276e063f51d0d5193539bf9c7d7551db1ae..f7d99faf30e496e9b8236f968740b9158d48dcc7 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/run_or_post.h +++ b/src/connectivity/bluetooth/core/bt-host/common/run_or_post.h @@ -2,14 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#ifndef SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_RUN_OR_POST_H_ +#define SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_RUN_OR_POST_H_ + #include <lib/async/dispatcher.h> #include <lib/fit/function.h> namespace bt { -namespace common { // Runs |task|. Posts it on |dispatcher| if dispatcher is not null. void RunOrPost(fit::closure task, async_dispatcher_t* dispatcher); -} // namespace common } // namespace bt + +#endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_RUN_OR_POST_H_ diff --git a/src/connectivity/bluetooth/core/bt-host/common/run_or_post_unittest.cc b/src/connectivity/bluetooth/core/bt-host/common/run_or_post_unittest.cc index e9199ea8f613782817f428b055260cf7748ac407..bc527ed7db297023bf7805a56af5e081449c2138 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/run_or_post_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/run_or_post_unittest.cc @@ -7,7 +7,6 @@ #include "lib/gtest/test_loop_fixture.h" namespace bt { -namespace common { namespace { using RunOrPostTest = ::gtest::TestLoopFixture; @@ -28,5 +27,4 @@ TEST_F(RunOrPostTest, WithDispatcher) { } } // namespace -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/common/run_task_sync.cc b/src/connectivity/bluetooth/core/bt-host/common/run_task_sync.cc index 6faf9aa4497dd3be063fa1c344183ef1f56e5598..cf6f69be53fb5bf7734fa73bd62fd3f63fe54c0e 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/run_task_sync.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/run_task_sync.cc @@ -4,21 +4,20 @@ #include "run_task_sync.h" -#include <condition_variable> -#include <mutex> - #include <lib/async/cpp/task.h> #include <lib/async/default.h> #include <zircon/assert.h> +#include <condition_variable> +#include <mutex> + namespace bt { -namespace common { void RunTaskSync(fit::closure callback, async_dispatcher_t* dispatcher) { ZX_DEBUG_ASSERT(callback); - // TODO(armansito) This check is risky. async_get_default_dispatcher() could return - // a dispatcher that goes to another thread. We don't have any current + // TODO(armansito) This check is risky. async_get_default_dispatcher() could + // return a dispatcher that goes to another thread. We don't have any current // instances of a multi threaded dispatcher but we could. if (dispatcher == async_get_default_dispatcher()) { callback(); @@ -29,20 +28,20 @@ void RunTaskSync(fit::closure callback, async_dispatcher_t* dispatcher) { std::condition_variable cv; bool done = false; - async::PostTask(dispatcher, [callback = std::move(callback), &mtx, &cv, &done] { - callback(); + async::PostTask(dispatcher, + [callback = std::move(callback), &mtx, &cv, &done] { + callback(); - { - std::lock_guard<std::mutex> lock(mtx); - done = true; - } + { + std::lock_guard<std::mutex> lock(mtx); + done = true; + } - cv.notify_one(); - }); + cv.notify_one(); + }); std::unique_lock<std::mutex> lock(mtx); cv.wait(lock, [&done] { return done; }); } -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/common/run_task_sync.h b/src/connectivity/bluetooth/core/bt-host/common/run_task_sync.h index c3694c2e8db7eeccd306abaa91f59b626e66f671..033028c6b4f286f75cb2bab2e9d7bcafacb3b112 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/run_task_sync.h +++ b/src/connectivity/bluetooth/core/bt-host/common/run_task_sync.h @@ -9,7 +9,6 @@ #include <lib/fit/function.h> namespace bt { -namespace common { // Posts |callback| on |dispatcher| and waits for it to finish running. // |callback| will always finish running before this function returns. @@ -20,7 +19,6 @@ namespace common { // synchronous setup/shutdown sequences and unit tests. void RunTaskSync(fit::closure callback, async_dispatcher_t* dispatcher); -} // namespace common } // namespace bt #endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_RUN_TASK_SYNC_H_ diff --git a/src/connectivity/bluetooth/core/bt-host/common/run_task_sync_unittest.cc b/src/connectivity/bluetooth/core/bt-host/common/run_task_sync_unittest.cc index 94857cbf379e5784093d2ce6dd3d82c7472290f8..589ea84b9ffdb6468fb4afbed4229b23f6a07b7c 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/run_task_sync_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/run_task_sync_unittest.cc @@ -4,14 +4,13 @@ #include "src/connectivity/bluetooth/core/bt-host/common/run_task_sync.h" -#include "gtest/gtest.h" - #include <lib/async-loop/cpp/loop.h> #include <lib/async/cpp/task.h> #include <lib/zx/time.h> +#include "gtest/gtest.h" + namespace bt { -namespace common { namespace { TEST(RunTaskSyncTest, RunTaskSync) { @@ -38,5 +37,4 @@ TEST(RunTaskSyncTest, RunTaskSync) { } } // namespace -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/common/slab_allocator.cc b/src/connectivity/bluetooth/core/bt-host/common/slab_allocator.cc index a6282d70c52456f083cc6638a84cd7973d2db682..982c8cd3599800bafa7219df401e8f3ef237c3e3 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/slab_allocator.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/slab_allocator.cc @@ -10,7 +10,6 @@ #include "slab_buffer.h" namespace bt { -namespace common { using SmallBufferTraits = SlabBufferTraits<kSmallBufferSize, kSlabSize / kSmallBufferSize>; @@ -20,9 +19,9 @@ using LargeBufferTraits = using SmallAllocator = fbl::SlabAllocator<SmallBufferTraits>; using LargeAllocator = fbl::SlabAllocator<LargeBufferTraits>; -common::MutableByteBufferPtr NewSlabBuffer(size_t size) { +MutableByteBufferPtr NewSlabBuffer(size_t size) { if (size == 0) - return std::make_unique<common::DynamicByteBuffer>(); + return std::make_unique<DynamicByteBuffer>(); if (size <= kSmallBufferSize) { auto buffer = SmallAllocator::New(size); if (buffer) @@ -32,10 +31,9 @@ common::MutableByteBufferPtr NewSlabBuffer(size_t size) { return LargeAllocator::New(size); } -} // namespace common } // namespace bt -DECLARE_STATIC_SLAB_ALLOCATOR_STORAGE(bt::common::LargeBufferTraits, - bt::common::kMaxNumSlabs, true); -DECLARE_STATIC_SLAB_ALLOCATOR_STORAGE(bt::common::SmallBufferTraits, - bt::common::kMaxNumSlabs, true); +DECLARE_STATIC_SLAB_ALLOCATOR_STORAGE(bt::LargeBufferTraits, bt::kMaxNumSlabs, + true); +DECLARE_STATIC_SLAB_ALLOCATOR_STORAGE(bt::SmallBufferTraits, bt::kMaxNumSlabs, + true); diff --git a/src/connectivity/bluetooth/core/bt-host/common/slab_allocator.h b/src/connectivity/bluetooth/core/bt-host/common/slab_allocator.h index ad3c158a40c25e67d6afcd7bc6e2f4389d6dc19a..4de9164b9b5d1c75c17abc9e4898ac1185cdf3d1 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/slab_allocator.h +++ b/src/connectivity/bluetooth/core/bt-host/common/slab_allocator.h @@ -8,7 +8,6 @@ #include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" namespace bt { -namespace common { // NOTE: Tweak these as needed. constexpr size_t kSmallBufferSize = 64; @@ -17,9 +16,8 @@ constexpr size_t kLargeBufferSize = 2048; constexpr size_t kMaxNumSlabs = 100; constexpr size_t kSlabSize = 32767; -common::MutableByteBufferPtr NewSlabBuffer(size_t size); +MutableByteBufferPtr NewSlabBuffer(size_t size); -} // namespace common } // namespace bt #endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_SLAB_ALLOCATOR_H_ diff --git a/src/connectivity/bluetooth/core/bt-host/common/slab_allocator_traits.h b/src/connectivity/bluetooth/core/bt-host/common/slab_allocator_traits.h index 1149bf17ebe4f07ca86602c114aefa0963fd6243..620c5a9ead3944505b9163ce878092062b6a8be5 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/slab_allocator_traits.h +++ b/src/connectivity/bluetooth/core/bt-host/common/slab_allocator_traits.h @@ -5,12 +5,11 @@ #ifndef SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_SLAB_ALLOCATOR_TRAITS_H_ #define SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_SLAB_ALLOCATOR_TRAITS_H_ -#include <memory> - #include <fbl/slab_allocator.h> +#include <memory> + namespace bt { -namespace common { namespace internal { constexpr size_t kSlabOverhead = 16; @@ -19,12 +18,9 @@ constexpr size_t kSlabOverhead = 16; // SlabAllocatorTraits is a simple alias over fbl::StaticSlabAllocatorTraits // which enforces the use of std::unique_ptr. template <typename T, size_t ObjectSize, size_t NumBuffers> -using SlabAllocatorTraits = - fbl::StaticSlabAllocatorTraits<std::unique_ptr<T>, - ObjectSize * NumBuffers + - internal::kSlabOverhead>; +using SlabAllocatorTraits = fbl::StaticSlabAllocatorTraits< + std::unique_ptr<T>, ObjectSize * NumBuffers + internal::kSlabOverhead>; -} // namespace common } // namespace bt #endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_SLAB_ALLOCATOR_TRAITS_H_ diff --git a/src/connectivity/bluetooth/core/bt-host/common/slab_allocator_traits_unittest.cc b/src/connectivity/bluetooth/core/bt-host/common/slab_allocator_traits_unittest.cc index 5db2f171bc7b1c8f0f35fa79a9ac92bed5e1110b..c58969eb72b4e61c94486f50708ac544d44d89d3 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/slab_allocator_traits_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/slab_allocator_traits_unittest.cc @@ -7,7 +7,6 @@ #include "gtest/gtest.h" namespace bt { -namespace common { namespace { @@ -56,8 +55,7 @@ TEST(SlabAllocatedBufferTest, Basic) { } } // namespace -} // namespace common } // namespace bt // Creates no more than one slab. -DECLARE_STATIC_SLAB_ALLOCATOR_STORAGE(bt::common::test::TestTraits, 1, true); +DECLARE_STATIC_SLAB_ALLOCATOR_STORAGE(bt::test::TestTraits, 1, true); diff --git a/src/connectivity/bluetooth/core/bt-host/common/slab_allocator_unittest.cc b/src/connectivity/bluetooth/core/bt-host/common/slab_allocator_unittest.cc index 20647bc5398541ef72e70772ff5902ea8f49d447..8a0bb45952982e223416543ced7b4dbe63adf349 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/slab_allocator_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/slab_allocator_unittest.cc @@ -7,7 +7,6 @@ #include "gtest/gtest.h" namespace bt { -namespace common { namespace { TEST(SlabAllocatorTest, NewSlabBuffer) { @@ -29,5 +28,4 @@ TEST(SlabAllocatorTest, NewSlabBuffer) { } } // namespace -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/common/slab_buffer.h b/src/connectivity/bluetooth/core/bt-host/common/slab_buffer.h index 35cef441a956d05bdfb2df5f37005d187e53e993..87507fd39992bf489a628afa19679ed206c6bc72 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/slab_buffer.h +++ b/src/connectivity/bluetooth/core/bt-host/common/slab_buffer.h @@ -12,7 +12,6 @@ #include "src/connectivity/bluetooth/core/bt-host/common/slab_allocator_traits.h" namespace bt { -namespace common { template <size_t BackingBufferSize> class SlabBuffer : public MutableByteBuffer { @@ -39,7 +38,7 @@ class SlabBuffer : public MutableByteBuffer { // The backing backing buffer can have a different size from what was // requested. - common::StaticByteBuffer<BackingBufferSize> buffer_; + StaticByteBuffer<BackingBufferSize> buffer_; DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(SlabBuffer); }; @@ -71,7 +70,6 @@ class SlabBufferImpl } // namespace internal -} // namespace common } // namespace bt #endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_SLAB_BUFFER_H_ diff --git a/src/connectivity/bluetooth/core/bt-host/common/status.cc b/src/connectivity/bluetooth/core/bt-host/common/status.cc index 8cdd7fca72cf06459f396e86b0770d66a49888f8..f81ad693442f51453812d1a43c022547182970e1 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/status.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/status.cc @@ -5,7 +5,6 @@ #include "status.h" namespace bt { -namespace common { std::string HostErrorToString(HostError error) { switch (error) { @@ -41,5 +40,4 @@ std::string HostErrorToString(HostError error) { return "(unknown)"; } -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/common/status.h b/src/connectivity/bluetooth/core/bt-host/common/status.h index 4c8b78701906833176682e085581a2a4b07c3bd3..984fcfecd3f887f29d7aac0881858e5a82b4fff6 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/status.h +++ b/src/connectivity/bluetooth/core/bt-host/common/status.h @@ -6,18 +6,15 @@ #define SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_STATUS_H_ #include <stdarg.h> +#include <zircon/assert.h> #include <cstdint> #include <string> -#include <zircon/assert.h> - -#include "src/lib/fxl/strings/string_printf.h" - #include "src/connectivity/bluetooth/core/bt-host/common/log.h" +#include "src/lib/fxl/strings/string_printf.h" namespace bt { -namespace common { // Status types used for internal errors generated by the host enum class HostError : uint8_t { @@ -145,7 +142,6 @@ class Status { ProtocolErrorCode protocol_error_; }; -} // namespace common } // namespace bt // Macro to check and log any non-Success status of an event. @@ -159,7 +155,7 @@ class Status { // a failure. Evaluates to true if the status indicates failure. #define bt_is_error(status, flag, tag, fmt...) \ - (status.TestForErrorAndLogF(bt::common::LogSeverity::flag, tag, __FILE__, \ - __LINE__, fmt)) + (status.TestForErrorAndLogF(bt::LogSeverity::flag, tag, __FILE__, __LINE__, \ + fmt)) #endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_STATUS_H_ diff --git a/src/connectivity/bluetooth/core/bt-host/common/status_unittest.cc b/src/connectivity/bluetooth/core/bt-host/common/status_unittest.cc index 4de8240633f8e71a78f236708177f9f5c84976a8..31add4e8d18f31ce135f1f48eadc4f3d2f9bdaf5 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/status_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/status_unittest.cc @@ -7,7 +7,6 @@ #include "gtest/gtest.h" namespace bt { -namespace common { namespace { enum class TestError : uint8_t { @@ -44,5 +43,4 @@ TEST(StatusTest, ProtocolErrorAsInt) { } } // namespace -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/common/task_domain.h b/src/connectivity/bluetooth/core/bt-host/common/task_domain.h index 9ae859c28ff2fc3d07656a6fe93827718ef64a6e..9cec1f2e64d8c548dfa4ba1f216fa26f8f9c2ed0 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/task_domain.h +++ b/src/connectivity/bluetooth/core/bt-host/common/task_domain.h @@ -17,7 +17,6 @@ #include <string> namespace bt { -namespace common { // A task domain is a mixin for objects that maintain state that needs to be // accessed exclusively on a specific dispatcher. @@ -46,11 +45,11 @@ namespace common { // public: // // Initialize by spawning a thread with a dispatcher owned by this // // domain. -// MyObject() : common::TaskDomain<MyObject>(this, "my-thread") {} +// MyObject() : TaskDomain<MyObject>(this, "my-thread") {} // // // Initialize to run on |dispatcher|. // explicit MyObject(async_dispatcher_t* dispatcher) -// : common::TaskDomain<MyObject>(this, dispatcher) {} +// : TaskDomain<MyObject>(this, dispatcher) {} // // void CleanUp() // @@ -183,11 +182,10 @@ class TaskDomain { }; #define BT_FRIEND_TASK_DOMAIN(Type) BT_FRIEND_TASK_DOMAIN_FULL(Type, Type) -#define BT_FRIEND_TASK_DOMAIN_FULL(Type, RefCountedType) \ - friend class bt::common::TaskDomain<Type, RefCountedType>; \ - friend struct bt::common::internal::has_clean_up<Type> +#define BT_FRIEND_TASK_DOMAIN_FULL(Type, RefCountedType) \ + friend class bt::TaskDomain<Type, RefCountedType>; \ + friend struct bt::internal::has_clean_up<Type> -} // namespace common } // namespace bt #endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_TASK_DOMAIN_H_ diff --git a/src/connectivity/bluetooth/core/bt-host/common/task_domain_unittest.cc b/src/connectivity/bluetooth/core/bt-host/common/task_domain_unittest.cc index 864c9fb455f9922a05759a19b5ae8246d83cc04b..6528e6e616dc8984289ba59c984889cd65e7f352 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/task_domain_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/task_domain_unittest.cc @@ -9,7 +9,6 @@ #include "lib/gtest/real_loop_fixture.h" namespace bt { -namespace common { namespace { class TestObject : public fbl::RefCounted<TestObject>, @@ -68,5 +67,4 @@ TEST_F(TaskDomainTest, PostMessageAndCleanUp) { } } // namespace -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/common/test_helpers.h b/src/connectivity/bluetooth/core/bt-host/common/test_helpers.h index a5349b2338543cc837b1ef8751b5f8926432993b..5b64ab9740233dc767f24965a3e9caaa8c053cde 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/test_helpers.h +++ b/src/connectivity/bluetooth/core/bt-host/common/test_helpers.h @@ -8,8 +8,8 @@ #include <algorithm> #include <iostream> -#include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" #include "gtest/gtest.h" +#include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" #include "src/lib/fxl/strings/string_printf.h" // Run |statement| and return if a fatal test error occurred. Include the file @@ -38,7 +38,6 @@ } while (false) namespace bt { -namespace common { template <class InputIt> void PrintByteContainer(InputIt begin, InputIt end) { @@ -84,8 +83,8 @@ bool ContainersEqual(const Container1& expected, const uint8_t* actual_bytes, // Returns a managed pointer to a heap allocated MutableByteBuffer. template <typename... T> -common::MutableByteBufferPtr NewBuffer(T... bytes) { - return std::make_unique<common::StaticByteBuffer<sizeof...(T)>>( +MutableByteBufferPtr NewBuffer(T... bytes) { + return std::make_unique<StaticByteBuffer<sizeof...(T)>>( std::forward<T>(bytes)...); } @@ -93,7 +92,6 @@ common::MutableByteBufferPtr NewBuffer(T... bytes) { constexpr uint8_t UpperBits(const uint16_t x) { return x >> 8; } constexpr uint8_t LowerBits(const uint16_t x) { return x & 0x00FF; } -} // namespace common } // namespace bt #endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_TEST_HELPERS_H_ diff --git a/src/connectivity/bluetooth/core/bt-host/common/uint128.cc b/src/connectivity/bluetooth/core/bt-host/common/uint128.cc index 92c478ca690429c0ddd7a79ce556f3e0ddbbb521..e337d07119bd5bb07500e240e15c232809d9bf3e 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/uint128.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/uint128.cc @@ -7,9 +7,7 @@ #include "random.h" namespace bt { -namespace common { UInt128 RandomUInt128() { return Random<UInt128>(); } -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/common/uint128.h b/src/connectivity/bluetooth/core/bt-host/common/uint128.h index 2cc0a738640a565a775f45f9db807d89a233986e..fc24a93358ce07ce49bbaab7507c6a5374d72401 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/uint128.h +++ b/src/connectivity/bluetooth/core/bt-host/common/uint128.h @@ -9,7 +9,6 @@ #include <cstdint> namespace bt { -namespace common { // Represents a 128-bit (16-octet) unsigned integer. This is commonly used for // encryption keys and UUID values. @@ -21,7 +20,6 @@ static_assert(sizeof(UInt128) == 16, "UInt128 must take up exactly 16 bytes"); // TODO(armansito): Remove this in favor of using Random<UInt128>() directly. UInt128 RandomUInt128(); -} // namespace common } // namespace bt #endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_UINT128_H_ diff --git a/src/connectivity/bluetooth/core/bt-host/common/uuid.cc b/src/connectivity/bluetooth/core/bt-host/common/uuid.cc index ec44f6344be591a132d2482cef0e4f59596b76c8..0c34e9bba7af7e526340e3f12c53948cd5b914a2 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/uuid.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/uuid.cc @@ -4,17 +4,16 @@ #include "uuid.h" -#include <cinttypes> - #include <endian.h> #include <zircon/assert.h> +#include <cinttypes> + #include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" #include "src/lib/fxl/strings/string_number_conversions.h" #include "src/lib/fxl/strings/string_printf.h" namespace bt { -namespace common { namespace { // Format string that can be passed to sscanf. This allows sscanf to convert @@ -74,7 +73,7 @@ constexpr UInt128 UUID::kBaseUuid; constexpr size_t UUID::kBaseOffset; // static -bool UUID::FromBytes(const common::ByteBuffer& bytes, UUID* out_uuid) { +bool UUID::FromBytes(const ByteBuffer& bytes, UUID* out_uuid) { switch (bytes.size()) { case k16BitSize: *out_uuid = @@ -116,7 +115,7 @@ bool UUID::operator==(const UInt128& uuid128) const { return value_ == uuid128; } -bool UUID::CompareBytes(const common::ByteBuffer& bytes) const { +bool UUID::CompareBytes(const ByteBuffer& bytes) const { switch (bytes.size()) { case k16BitSize: return (*this == @@ -155,7 +154,7 @@ size_t UUID::CompactSize(bool allow_32bit) const { return 0; } -size_t UUID::ToBytes(common::MutableByteBuffer* bytes, bool allow_32bit) const { +size_t UUID::ToBytes(MutableByteBuffer* bytes, bool allow_32bit) const { size_t size = CompactSize(allow_32bit); size_t offset = (size == k128BitSize) ? 0u : kBaseOffset; bytes->Write(value_.data() + offset, size); @@ -216,5 +215,4 @@ bool StringToUuid(const std::string& uuid_string, UUID* out_uuid) { return true; } -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/common/uuid.h b/src/connectivity/bluetooth/core/bt-host/common/uuid.h index 1dbc09644da2483cf695c7e37e41dce7516b0039..dee440d85a5af27f4c5edbd59e35e88b50bddddf 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/uuid.h +++ b/src/connectivity/bluetooth/core/bt-host/common/uuid.h @@ -12,7 +12,6 @@ #include "src/connectivity/bluetooth/core/bt-host/common/uint128.h" namespace bt { -namespace common { // Represents a 128-bit Bluetooth UUID. This class allows UUID values to be // constructed in the official Bluetooth 16-bit, 32-bit, and 128-bit formats and @@ -22,7 +21,7 @@ class UUID final { // Constructs a UUID from |bytes|. |bytes| should contain a 16-, 32-, or // 128-bit UUID in little-endian byte order. Returns false if |bytes| contains // an unsupported size. - static bool FromBytes(const common::ByteBuffer& bytes, UUID* out_uuid); + static bool FromBytes(const ByteBuffer& bytes, UUID* out_uuid); constexpr explicit UUID(const UInt128& uuid128) : type_(Type::k128Bit), value_(uuid128) { @@ -61,7 +60,7 @@ class UUID final { // over PDUs. Returns false if |bytes| has an unaccepted size; the only // accepted sizes for are 2, 4, and 16 for 16-bit, 32-bit, and 128-bit // formats, respectively. - bool CompareBytes(const common::ByteBuffer& bytes) const; + bool CompareBytes(const ByteBuffer& bytes) const; // Returns a string representation of this UUID in the following format: // @@ -79,8 +78,7 @@ class UUID final { // Writes a little-endian representation of this UUID to |buffer|. Returns // the number of bytes used. there must be enough space in |buffer| to store // |CompactSize()| bytes. - size_t ToBytes(common::MutableByteBuffer* buffer, - bool allow_32bit = true) const; + size_t ToBytes(MutableByteBuffer* buffer, bool allow_32bit = true) const; // Returns the most compact representation of this UUID. If |allow_32bit| is // false, then a 32-bit UUIDs will default to 128-bit. The contents will be in @@ -215,15 +213,14 @@ inline bool operator!=(const UInt128& lhs, const UUID& rhs) { return rhs != lhs; } -} // namespace common } // namespace bt // Specialization of std::hash for std::unordered_set, std::unordered_map, etc. namespace std { template <> -struct hash<bt::common::UUID> { - size_t operator()(const bt::common::UUID& k) const { return k.Hash(); } +struct hash<bt::UUID> { + size_t operator()(const bt::UUID& k) const { return k.Hash(); } }; } // namespace std diff --git a/src/connectivity/bluetooth/core/bt-host/common/uuid_unittest.cc b/src/connectivity/bluetooth/core/bt-host/common/uuid_unittest.cc index 18b3444a582a3c1be763b64d6287243f2c0a2003..c534e3a47c173c2f821ee50f058fc833378e71db 100644 --- a/src/connectivity/bluetooth/core/bt-host/common/uuid_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/common/uuid_unittest.cc @@ -5,12 +5,10 @@ #include "uuid.h" #include "gtest/gtest.h" - #include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" namespace bt { -namespace common { namespace { // Variants of 16-bit ID 180d @@ -114,18 +112,18 @@ TEST(UUIDTest, 128Bit) { } TEST(UUIDTest, CompareBytes) { - auto kUuid16Bytes = common::CreateStaticByteBuffer(0x0d, 0x18); - auto kUuid32Bytes = common::CreateStaticByteBuffer(0x0d, 0x18, 0x00, 0x00); - auto kUuid128Bytes = common::CreateStaticByteBuffer( - 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, - 0x0d, 0x18, 0x00, 0x00); + auto kUuid16Bytes = CreateStaticByteBuffer(0x0d, 0x18); + auto kUuid32Bytes = CreateStaticByteBuffer(0x0d, 0x18, 0x00, 0x00); + auto kUuid128Bytes = + CreateStaticByteBuffer(0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0x0d, 0x18, 0x00, 0x00); constexpr UUID uuid(kId1As16); EXPECT_TRUE(uuid.CompareBytes(kUuid16Bytes)); EXPECT_TRUE(uuid.CompareBytes(kUuid32Bytes)); EXPECT_TRUE(uuid.CompareBytes(kUuid128Bytes)); - common::BufferView empty; + BufferView empty; EXPECT_FALSE(uuid.CompareBytes(empty)); } @@ -200,15 +198,15 @@ TEST(UUIDTest, StringToUuid16) { } TEST(UUIDTest, FromBytes) { - auto kUuid16Bytes = common::CreateStaticByteBuffer(0x0d, 0x18); - auto kUuid32Bytes = common::CreateStaticByteBuffer(0x0d, 0x18, 0x00, 0x00); - auto kUuid128Bytes = common::CreateStaticByteBuffer( - 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, - 0x0d, 0x18, 0x00, 0x00); + auto kUuid16Bytes = CreateStaticByteBuffer(0x0d, 0x18); + auto kUuid32Bytes = CreateStaticByteBuffer(0x0d, 0x18, 0x00, 0x00); + auto kUuid128Bytes = + CreateStaticByteBuffer(0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0x0d, 0x18, 0x00, 0x00); - auto kInvalid0 = common::CreateStaticByteBuffer(0x0d); - auto kInvalid1 = common::CreateStaticByteBuffer(0x0d, 0x18, 0x00); - common::BufferView kInvalid2; + auto kInvalid0 = CreateStaticByteBuffer(0x0d); + auto kInvalid1 = CreateStaticByteBuffer(0x0d, 0x18, 0x00); + BufferView kInvalid2; UUID uuid; @@ -249,57 +247,57 @@ TEST(UUIDTest, CompactSize) { } TEST(UUIDTest, ToBytes16) { - auto kUuid16Bytes = common::CreateStaticByteBuffer(0x0d, 0x18); + auto kUuid16Bytes = CreateStaticByteBuffer(0x0d, 0x18); UUID uuid(kId1As16); - common::DynamicByteBuffer bytes(uuid.CompactSize()); + DynamicByteBuffer bytes(uuid.CompactSize()); EXPECT_EQ(bytes.size(), uuid.ToBytes(&bytes)); - EXPECT_TRUE(common::ContainersEqual(kUuid16Bytes, bytes)); + EXPECT_TRUE(ContainersEqual(kUuid16Bytes, bytes)); uuid = UUID(kId1As32); EXPECT_EQ(bytes.size(), uuid.ToBytes(&bytes)); - EXPECT_TRUE(common::ContainersEqual(kUuid16Bytes, bytes)); + EXPECT_TRUE(ContainersEqual(kUuid16Bytes, bytes)); } TEST(UUIDTest, ToBytes32) { - auto kUuid32Bytes = common::CreateStaticByteBuffer(0xef, 0xbe, 0xad, 0xde); + auto kUuid32Bytes = CreateStaticByteBuffer(0xef, 0xbe, 0xad, 0xde); UUID uuid(kId2As32); - common::DynamicByteBuffer bytes(uuid.CompactSize()); + DynamicByteBuffer bytes(uuid.CompactSize()); EXPECT_EQ(bytes.size(), uuid.ToBytes(&bytes)); - EXPECT_TRUE(common::ContainersEqual(kUuid32Bytes, bytes)); + EXPECT_TRUE(ContainersEqual(kUuid32Bytes, bytes)); - common::StaticByteBuffer<16> bytes128; + StaticByteBuffer<16> bytes128; EXPECT_EQ(bytes128.size(), uuid.ToBytes(&bytes128, false /* allow_32bit */)); - EXPECT_TRUE(common::ContainersEqual(kId2As128, bytes128)); + EXPECT_TRUE(ContainersEqual(kId2As128, bytes128)); } TEST(UUIDTest, CompactView16) { - auto kUuid16Bytes = common::CreateStaticByteBuffer(0x0d, 0x18); + auto kUuid16Bytes = CreateStaticByteBuffer(0x0d, 0x18); UUID uuid(kId1As16); - common::BufferView view = uuid.CompactView(); - EXPECT_TRUE(common::ContainersEqual(kUuid16Bytes, view)); + BufferView view = uuid.CompactView(); + EXPECT_TRUE(ContainersEqual(kUuid16Bytes, view)); uuid = UUID(kId1As32); view = uuid.CompactView(); - EXPECT_TRUE(common::ContainersEqual(kUuid16Bytes, view)); + EXPECT_TRUE(ContainersEqual(kUuid16Bytes, view)); } TEST(UUIDTest, CompactView32) { - auto kUuid32Bytes = common::CreateStaticByteBuffer(0xef, 0xbe, 0xad, 0xde); + auto kUuid32Bytes = CreateStaticByteBuffer(0xef, 0xbe, 0xad, 0xde); UUID uuid(kId2As32); - common::BufferView view = uuid.CompactView(); - EXPECT_TRUE(common::ContainersEqual(kUuid32Bytes, view)); + BufferView view = uuid.CompactView(); + EXPECT_TRUE(ContainersEqual(kUuid32Bytes, view)); view = uuid.CompactView(false /* allow_32bit */); - EXPECT_TRUE(common::ContainersEqual(kId2As128, view)); + EXPECT_TRUE(ContainersEqual(kId2As128, view)); } TEST(UUIDTest, Hash) { @@ -311,5 +309,4 @@ TEST(UUIDTest, Hash) { } } // namespace -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/data/domain.cc b/src/connectivity/bluetooth/core/bt-host/data/domain.cc index d879a0668bb1fa538ad1433eaf3027211896ad11..0e4d979f6cfd2d49696c40d0608f29c607b8148d 100644 --- a/src/connectivity/bluetooth/core/bt-host/data/domain.cc +++ b/src/connectivity/bluetooth/core/bt-host/data/domain.cc @@ -14,20 +14,18 @@ namespace bt { namespace data { -class Impl final : public Domain, public common::TaskDomain<Impl, Domain> { +class Impl final : public Domain, public TaskDomain<Impl, Domain> { public: Impl(fxl::RefPtr<hci::Transport> hci, std::string thread_name) : Domain(), - common::TaskDomain<Impl, Domain>(this, std::move(thread_name)), + TaskDomain<Impl, Domain>(this, std::move(thread_name)), hci_(hci) { ZX_DEBUG_ASSERT(hci_); } // Second constructor used by CreateWithDispatcher. Impl(fxl::RefPtr<hci::Transport> hci, async_dispatcher_t* dispatcher) - : Domain(), - common::TaskDomain<Impl, Domain>(this, dispatcher), - hci_(hci) { + : Domain(), TaskDomain<Impl, Domain>(this, dispatcher), hci_(hci) { ZX_DEBUG_ASSERT(hci_); } @@ -48,9 +46,7 @@ class Impl final : public Domain, public common::TaskDomain<Impl, Domain> { }); } - void ShutDown() override { - common::TaskDomain<Impl, Domain>::ScheduleCleanUp(); - } + void ShutDown() override { TaskDomain<Impl, Domain>::ScheduleCleanUp(); } // Called by the domain dispatcher as a result of ScheduleCleanUp(). void CleanUp() { diff --git a/src/connectivity/bluetooth/core/bt-host/data/domain_unittest.cc b/src/connectivity/bluetooth/core/bt-host/data/domain_unittest.cc index aa72247d9f50260e5b1a573f297e1b2ec2cfb103..0fbb4604d75e6e6a763afb99a329fdc39a956017 100644 --- a/src/connectivity/bluetooth/core/bt-host/data/domain_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/data/domain_unittest.cc @@ -23,11 +23,6 @@ namespace { using bt::testing::TestController; using TestingBase = bt::testing::FakeControllerTest<TestController>; -using common::CreateStaticByteBuffer; -using common::LowerBits; -using common::StaticByteBuffer; -using common::UpperBits; - class DATA_DomainTest : public TestingBase { public: DATA_DomainTest() = default; diff --git a/src/connectivity/bluetooth/core/bt-host/data/socket_channel_relay.cc b/src/connectivity/bluetooth/core/bt-host/data/socket_channel_relay.cc index f8f11e545d73da642d8b887ca907ae179050eae9..3ce77d639b8ab2bf21ce40b88fa733ed9c2241f1 100644 --- a/src/connectivity/bluetooth/core/bt-host/data/socket_channel_relay.cc +++ b/src/connectivity/bluetooth/core/bt-host/data/socket_channel_relay.cc @@ -4,11 +4,11 @@ #include "socket_channel_relay.h" -#include <utility> - #include <lib/async/default.h> #include <zircon/assert.h> +#include <utility> + #include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" #include "src/connectivity/bluetooth/core/bt-host/common/log.h" @@ -74,7 +74,7 @@ bool SocketChannelRelay<ChannelT>::Activate() { const auto self = weak_ptr_factory_.GetWeakPtr(); const auto channel_id = channel_->id(); const bool activate_success = channel_->Activate( - [self, channel_id](common::ByteBufferPtr rx_data) { + [self, channel_id](ByteBufferPtr rx_data) { // Note: this lambda _may_ be invoked synchronously. if (self) { self->OnChannelDataReceived(std::move(rx_data)); @@ -166,7 +166,7 @@ void SocketChannelRelay<ChannelT>::OnSocketClosed(zx_status_t status) { template <typename ChannelT> void SocketChannelRelay<ChannelT>::OnChannelDataReceived( - common::ByteBufferPtr rx_data) { + ByteBufferPtr rx_data) { ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); // Note: kActivating is deliberately permitted, as ChannelImpl::Activate() // will synchronously deliver any queued frames. @@ -252,9 +252,8 @@ bool SocketChannelRelay<ChannelT>::CopyFromSocketToChannel() { // TODO(NET-1391): For low latency and low jitter, IWBN to avoid allocating // dynamic memory on every read. - bool write_success = - channel_->Send(std::make_unique<common::DynamicByteBuffer>( - common::BufferView(read_buf, n_bytes_read))); + bool write_success = channel_->Send(std::make_unique<DynamicByteBuffer>( + BufferView(read_buf, n_bytes_read))); if (!write_success) { bt_log(DEBUG, "l2cap", "Failed to write %zu bytes to channel %u", n_bytes_read, channel_->id()); @@ -277,7 +276,7 @@ void SocketChannelRelay<ChannelT>::ServiceSocketWriteQueue() { ZX_DEBUG_ASSERT(socket_write_queue_.front()); ZX_DEBUG_ASSERT(socket_write_queue_.front()->size()); - const common::ByteBuffer& rx_data = *socket_write_queue_.front(); + const ByteBuffer& rx_data = *socket_write_queue_.front(); size_t n_bytes_written = 0; write_res = socket_.write(0, rx_data.data(), rx_data.size(), &n_bytes_written); diff --git a/src/connectivity/bluetooth/core/bt-host/data/socket_channel_relay.h b/src/connectivity/bluetooth/core/bt-host/data/socket_channel_relay.h index f5e92a5c46200bd9b66d7a31a9adca7ae34e5938..ae087f31541ef3131d931071df53b4bb30b3c6d1 100644 --- a/src/connectivity/bluetooth/core/bt-host/data/socket_channel_relay.h +++ b/src/connectivity/bluetooth/core/bt-host/data/socket_channel_relay.h @@ -103,7 +103,7 @@ class SocketChannelRelay final { void OnSocketClosed(zx_status_t status); // Callbacks for ChannelT events. - void OnChannelDataReceived(common::ByteBufferPtr sdu); + void OnChannelDataReceived(ByteBufferPtr sdu); void OnChannelClosed(); // Copies any data currently available on |socket_| to |channel_|. Does not @@ -147,9 +147,9 @@ class SocketChannelRelay final { // SDU). This comes, however, at the cost of higher memory usage when the // number of SDUs is small. (libc++ uses a minimum of 4KB per deque.) // - // TODO(NET-1478): Switch to common::LinkedList. + // TODO(NET-1478): Switch to LinkedList. // TODO(NET-1476): We should set an upper bound on the size of this queue. - std::deque<common::ByteBufferPtr> socket_write_queue_; + std::deque<ByteBufferPtr> socket_write_queue_; const fxl::ThreadChecker thread_checker_; fxl::WeakPtrFactory<SocketChannelRelay> weak_ptr_factory_; // Keep last. diff --git a/src/connectivity/bluetooth/core/bt-host/data/socket_channel_relay_unittest.cc b/src/connectivity/bluetooth/core/bt-host/data/socket_channel_relay_unittest.cc index 57d48688441a5af556f0745a193f5e8dfa7d7daa..880323d8aac6e6a0ca5a97600cdfd9dbcf4f79a6 100644 --- a/src/connectivity/bluetooth/core/bt-host/data/socket_channel_relay_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/data/socket_channel_relay_unittest.cc @@ -4,15 +4,14 @@ #include "socket_channel_relay.h" -#include <memory> -#include <type_traits> - #include <lib/async-loop/cpp/loop.h> #include <zircon/assert.h> #include <zircon/compiler.h> -#include "gtest/gtest.h" +#include <memory> +#include <type_traits> +#include "gtest/gtest.h" #include "src/connectivity/bluetooth/core/bt-host/common/log.h" #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" #include "src/connectivity/bluetooth/core/bt-host/l2cap/fake_channel.h" @@ -54,7 +53,7 @@ class DATA_SocketChannelRelayTest : public ::testing::Test { for (const auto spam_size_bytes : {65536, 32768, 16384, 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1}) { - common::DynamicByteBuffer spam_data(spam_size_bytes); + DynamicByteBuffer spam_data(spam_size_bytes); spam_data.Fill(kSpamChar); do { size_t n_iter_bytes_written = 0; @@ -76,7 +75,7 @@ class DATA_SocketChannelRelayTest : public ::testing::Test { // bytes is not known, as a pending datagram may be larger than our read // buffer.) __WARN_UNUSED_RESULT bool DiscardFromSocket(size_t n_bytes_requested) { - common::DynamicByteBuffer received_data(n_bytes_requested); + DynamicByteBuffer received_data(n_bytes_requested); zx_status_t read_res; size_t n_total_bytes_read = 0; while (n_total_bytes_read < n_bytes_requested) { @@ -195,7 +194,7 @@ TEST_F(DATA_SocketChannelRelayLifetimeTest, TEST_F(DATA_SocketChannelRelayLifetimeTest, DestructionWithPendingSdusFromChannelDoesNotCrash) { ASSERT_TRUE(relay()->Activate()); - channel()->Receive(common::CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o')); + channel()->Receive(CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o')); DestroyRelay(); RunLoopUntilIdle(); } @@ -222,7 +221,7 @@ TEST_F(DATA_SocketChannelRelayLifetimeTest, ASSERT_TRUE(relay()->Activate()); ASSERT_TRUE(StuffSocket()); - channel()->Receive(common::CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o')); + channel()->Receive(CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o')); RunLoopUntilIdle(); ASSERT_FALSE(was_deactivation_callback_invoked()); @@ -233,7 +232,7 @@ TEST_F(DATA_SocketChannelRelayLifetimeTest, TEST_F(DATA_SocketChannelRelayLifetimeTest, OversizedDatagramDeactivatesRelay) { const size_t kMessageBufSize = channel()->tx_mtu() * 5; - common::DynamicByteBuffer large_message(kMessageBufSize); + DynamicByteBuffer large_message(kMessageBufSize); large_message.Fill('a'); ASSERT_TRUE(relay()->Activate()); @@ -292,16 +291,16 @@ class DATA_SocketChannelRelayDataPathTest : public DATA_SocketChannelRelayTest { private: RelayT relay_; - std::vector<common::ByteBufferPtr> sent_to_channel_; + std::vector<ByteBufferPtr> sent_to_channel_; }; // Fixture for tests which exercise the datapath from the controller. class DATA_SocketChannelRelayRxTest : public DATA_SocketChannelRelayDataPathTest { protected: - common::DynamicByteBuffer ReadDatagramFromSocket(const size_t dgram_len) { - common::DynamicByteBuffer socket_read_buffer( - dgram_len + 1); // +1 to detect trailing garbage. + DynamicByteBuffer ReadDatagramFromSocket(const size_t dgram_len) { + DynamicByteBuffer socket_read_buffer(dgram_len + + 1); // +1 to detect trailing garbage. size_t n_bytes_read = 0; const auto read_res = remote_socket()->read(0, socket_read_buffer.mutable_data(), @@ -311,15 +310,13 @@ class DATA_SocketChannelRelayRxTest zx_status_get_string(read_res)); return {}; } - return common::DynamicByteBuffer( - common::BufferView(socket_read_buffer, n_bytes_read)); + return DynamicByteBuffer(BufferView(socket_read_buffer, n_bytes_read)); } }; TEST_F(DATA_SocketChannelRelayRxTest, MessageFromChannelIsCopiedToSocketSynchronously) { - const auto kExpectedMessage = - common::CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o'); + const auto kExpectedMessage = CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o'); ASSERT_TRUE(relay()->Activate()); channel()->Receive(kExpectedMessage); // Note: we dispatch one task, to get the data from the FakeChannel to @@ -328,24 +325,24 @@ TEST_F(DATA_SocketChannelRelayRxTest, // zx::socket. RunLoopOnce(); - EXPECT_TRUE(common::ContainersEqual( - kExpectedMessage, ReadDatagramFromSocket(kExpectedMessage.size()))); + EXPECT_TRUE(ContainersEqual(kExpectedMessage, + ReadDatagramFromSocket(kExpectedMessage.size()))); } TEST_F(DATA_SocketChannelRelayRxTest, MultipleSdusFromChannelAreCopiedToSocketPreservingSduBoundaries) { const auto kExpectedMessage1 = - common::CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o'); + CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o'); const auto kExpectedMessage2 = - common::CreateStaticByteBuffer('g', 'o', 'o', 'd', 'b', 'y', 'e'); + CreateStaticByteBuffer('g', 'o', 'o', 'd', 'b', 'y', 'e'); ASSERT_TRUE(relay()->Activate()); channel()->Receive(kExpectedMessage1); channel()->Receive(kExpectedMessage2); RunLoopUntilIdle(); - EXPECT_TRUE(common::ContainersEqual( + EXPECT_TRUE(ContainersEqual( kExpectedMessage1, ReadDatagramFromSocket(kExpectedMessage1.size()))); - EXPECT_TRUE(common::ContainersEqual( + EXPECT_TRUE(ContainersEqual( kExpectedMessage2, ReadDatagramFromSocket(kExpectedMessage2.size()))); } @@ -354,16 +351,15 @@ TEST_F(DATA_SocketChannelRelayRxTest, size_t n_junk_bytes = StuffSocket(); ASSERT_TRUE(n_junk_bytes); - const auto kExpectedMessage = - common::CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o'); + const auto kExpectedMessage = CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o'); ASSERT_TRUE(relay()->Activate()); channel()->Receive(kExpectedMessage); RunLoopUntilIdle(); ASSERT_TRUE(DiscardFromSocket(n_junk_bytes)); RunLoopUntilIdle(); - EXPECT_TRUE(common::ContainersEqual( - kExpectedMessage, ReadDatagramFromSocket(kExpectedMessage.size()))); + EXPECT_TRUE(ContainersEqual(kExpectedMessage, + ReadDatagramFromSocket(kExpectedMessage.size()))); } TEST_F(DATA_SocketChannelRelayRxTest, CanQueueAndWriteMultipleSDUs) { @@ -371,9 +367,9 @@ TEST_F(DATA_SocketChannelRelayRxTest, CanQueueAndWriteMultipleSDUs) { ASSERT_TRUE(n_junk_bytes); const auto kExpectedMessage1 = - common::CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o'); + CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o'); const auto kExpectedMessage2 = - common::CreateStaticByteBuffer('g', 'o', 'o', 'd', 'b', 'y', 'e'); + CreateStaticByteBuffer('g', 'o', 'o', 'd', 'b', 'y', 'e'); ASSERT_TRUE(relay()->Activate()); channel()->Receive(kExpectedMessage1); channel()->Receive(kExpectedMessage2); @@ -384,9 +380,9 @@ TEST_F(DATA_SocketChannelRelayRxTest, CanQueueAndWriteMultipleSDUs) { // one shot, rather than re-arming the async::Wait for each SDU. RunLoopOnce(); - EXPECT_TRUE(common::ContainersEqual( + EXPECT_TRUE(ContainersEqual( kExpectedMessage1, ReadDatagramFromSocket(kExpectedMessage1.size()))); - EXPECT_TRUE(common::ContainersEqual( + EXPECT_TRUE(ContainersEqual( kExpectedMessage2, ReadDatagramFromSocket(kExpectedMessage2.size()))); } @@ -401,7 +397,7 @@ TEST_F(DATA_SocketChannelRelayRxTest, // |remote_socket()|. constexpr size_t kLargeSduSize = 1023; zx_status_t write_res = ZX_ERR_INTERNAL; - common::DynamicByteBuffer spam_sdu(kLargeSduSize); + DynamicByteBuffer spam_sdu(kLargeSduSize); size_t n_junk_bytes = 0; size_t n_junk_datagrams = 0; spam_sdu.Fill('s'); @@ -420,8 +416,8 @@ TEST_F(DATA_SocketChannelRelayRxTest, ASSERT_NE(socket_buffer_size, n_junk_bytes) << "Need non-zero free space in socket buffer."; - common::DynamicByteBuffer hello_sdu(kLargeSduSize); - common::DynamicByteBuffer goodbye_sdu(kLargeSduSize); + DynamicByteBuffer hello_sdu(kLargeSduSize); + DynamicByteBuffer goodbye_sdu(kLargeSduSize); hello_sdu.Fill('h'); goodbye_sdu.Fill('g'); ASSERT_TRUE(relay()->Activate()); @@ -430,29 +426,29 @@ TEST_F(DATA_SocketChannelRelayRxTest, RunLoopUntilIdle(); // Free up space for just the first SDU. - ASSERT_TRUE(common::ContainersEqual(spam_sdu, - ReadDatagramFromSocket(spam_sdu.size()))); + ASSERT_TRUE( + ContainersEqual(spam_sdu, ReadDatagramFromSocket(spam_sdu.size()))); n_junk_datagrams -= 1; RunLoopUntilIdle(); // Free up space for just the second SDU. - ASSERT_TRUE(common::ContainersEqual(spam_sdu, - ReadDatagramFromSocket(spam_sdu.size()))); + ASSERT_TRUE( + ContainersEqual(spam_sdu, ReadDatagramFromSocket(spam_sdu.size()))); n_junk_datagrams -= 1; RunLoopUntilIdle(); // Discard spam. while (n_junk_datagrams) { - ASSERT_TRUE(common::ContainersEqual( - spam_sdu, ReadDatagramFromSocket(spam_sdu.size()))); + ASSERT_TRUE( + ContainersEqual(spam_sdu, ReadDatagramFromSocket(spam_sdu.size()))); n_junk_datagrams -= 1; } // Read out our expected datagrams, verifying that boundaries are preserved. - EXPECT_TRUE(common::ContainersEqual( - hello_sdu, ReadDatagramFromSocket(hello_sdu.size()))); - EXPECT_TRUE(common::ContainersEqual( - goodbye_sdu, ReadDatagramFromSocket(goodbye_sdu.size()))); + EXPECT_TRUE( + ContainersEqual(hello_sdu, ReadDatagramFromSocket(hello_sdu.size()))); + EXPECT_TRUE( + ContainersEqual(goodbye_sdu, ReadDatagramFromSocket(goodbye_sdu.size()))); EXPECT_EQ(0u, ReadDatagramFromSocket(1u).size()) << "Found unexpected datagram"; } @@ -461,9 +457,9 @@ TEST_F(DATA_SocketChannelRelayRxTest, OldestSDUIsDroppedOnOverflow) { size_t n_junk_bytes = StuffSocket(); ASSERT_TRUE(n_junk_bytes); - const auto kSentMessage1 = common::CreateStaticByteBuffer(1); - const auto kSentMessage2 = common::CreateStaticByteBuffer(2); - const auto kSentMessage3 = common::CreateStaticByteBuffer(3); + const auto kSentMessage1 = CreateStaticByteBuffer(1); + const auto kSentMessage2 = CreateStaticByteBuffer(2); + const auto kSentMessage3 = CreateStaticByteBuffer(3); ASSERT_TRUE(relay()->Activate()); channel()->Receive(kSentMessage1); channel()->Receive(kSentMessage2); @@ -473,27 +469,27 @@ TEST_F(DATA_SocketChannelRelayRxTest, OldestSDUIsDroppedOnOverflow) { ASSERT_TRUE(DiscardFromSocket(n_junk_bytes)); RunLoopUntilIdle(); - EXPECT_TRUE(common::ContainersEqual( - kSentMessage2, ReadDatagramFromSocket(kSentMessage2.size()))); - EXPECT_TRUE(common::ContainersEqual( - kSentMessage3, ReadDatagramFromSocket(kSentMessage3.size()))); + EXPECT_TRUE(ContainersEqual(kSentMessage2, + ReadDatagramFromSocket(kSentMessage2.size()))); + EXPECT_TRUE(ContainersEqual(kSentMessage3, + ReadDatagramFromSocket(kSentMessage3.size()))); } TEST_F(DATA_SocketChannelRelayRxTest, SdusReceivedBeforeChannelActivationAreCopiedToSocket) { const auto kExpectedMessage1 = - common::CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o'); + CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o'); const auto kExpectedMessage2 = - common::CreateStaticByteBuffer('g', 'o', 'o', 'd', 'b', 'y', 'e'); + CreateStaticByteBuffer('g', 'o', 'o', 'd', 'b', 'y', 'e'); channel()->Receive(kExpectedMessage1); channel()->Receive(kExpectedMessage2); ASSERT_TRUE(relay()->Activate()); // Note: we omit RunLoopOnce()/RunLoopUntilIdle(), as Channel activation // delivers the messages synchronously. - EXPECT_TRUE(common::ContainersEqual( + EXPECT_TRUE(ContainersEqual( kExpectedMessage1, ReadDatagramFromSocket(kExpectedMessage1.size()))); - EXPECT_TRUE(common::ContainersEqual( + EXPECT_TRUE(ContainersEqual( kExpectedMessage2, ReadDatagramFromSocket(kExpectedMessage2.size()))); } @@ -502,8 +498,8 @@ TEST_F(DATA_SocketChannelRelayRxTest, ASSERT_TRUE(StuffSocket()); ASSERT_TRUE(relay()->Activate()); - const auto kExpectedMessage1 = common::CreateStaticByteBuffer('h'); - const auto kExpectedMessage2 = common::CreateStaticByteBuffer('i'); + const auto kExpectedMessage1 = CreateStaticByteBuffer('h'); + const auto kExpectedMessage2 = CreateStaticByteBuffer('i'); channel()->Receive(kExpectedMessage1); channel()->Receive(kExpectedMessage2); RunLoopUntilIdle(); @@ -515,16 +511,15 @@ TEST_F(DATA_SocketChannelRelayRxTest, channel()->Close(); // Read past all of the spam from StuffSocket(). - common::DynamicByteBuffer dgram; + DynamicByteBuffer dgram; do { dgram = ReadDatagramFromSocket(1u); } while (dgram.size() && dgram[0] == kSpamChar); // First non-spam message should be kExpectedMessage1, and second should be // kExpectedMessage2. - EXPECT_TRUE(common::ContainersEqual(kExpectedMessage1, dgram)); - EXPECT_TRUE( - common::ContainersEqual(kExpectedMessage2, ReadDatagramFromSocket(1u))); + EXPECT_TRUE(ContainersEqual(kExpectedMessage1, dgram)); + EXPECT_TRUE(ContainersEqual(kExpectedMessage2, ReadDatagramFromSocket(1u))); } TEST_F(DATA_SocketChannelRelayRxTest, @@ -533,7 +528,7 @@ TEST_F(DATA_SocketChannelRelayRxTest, // SDU synchronously to the SocketChannelRelay. Asynchronous delivery could // compromise the test's validity, since that would allow OnSocketClosed() to // be invoked before OnChannelDataReceived(). - channel()->Receive(common::CreateStaticByteBuffer(kGoodChar)); + channel()->Receive(CreateStaticByteBuffer(kGoodChar)); CloseRemoteSocket(); ASSERT_TRUE(relay()->Activate()); } @@ -545,7 +540,7 @@ TEST_F( size_t n_junk_bytes = StuffSocket(); ASSERT_TRUE(n_junk_bytes); - channel()->Receive(common::CreateStaticByteBuffer(kGoodChar)); + channel()->Receive(CreateStaticByteBuffer(kGoodChar)); RunLoopUntilIdle(); ASSERT_TRUE(DiscardFromSocket(n_junk_bytes)); @@ -560,7 +555,7 @@ TEST_F(DATA_SocketChannelRelayRxTest, size_t n_junk_bytes = StuffSocket(); ASSERT_TRUE(n_junk_bytes); - channel()->Receive(common::CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o')); + channel()->Receive(CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o')); RunLoopUntilIdle(); channel()->Close(); // Triggers relay deactivation. @@ -580,8 +575,7 @@ TEST_F(DATA_SocketChannelRelayRxTest, using DATA_SocketChannelRelayTxTest = DATA_SocketChannelRelayDataPathTest; TEST_F(DATA_SocketChannelRelayTxTest, SduFromSocketIsCopiedToChannel) { - const auto kExpectedMessage = - common::CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o'); + const auto kExpectedMessage = CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o'); ASSERT_TRUE(relay()->Activate()); size_t n_bytes_written = 0; @@ -596,13 +590,12 @@ TEST_F(DATA_SocketChannelRelayTxTest, SduFromSocketIsCopiedToChannel) { EXPECT_EQ(1u, sdus.size()); ASSERT_TRUE(sdus[0]); EXPECT_EQ(kExpectedMessage.size(), sdus[0]->size()); - EXPECT_TRUE(common::ContainersEqual(kExpectedMessage, *sdus[0])); + EXPECT_TRUE(ContainersEqual(kExpectedMessage, *sdus[0])); } TEST_F(DATA_SocketChannelRelayTxTest, MultipleSdusFromSocketAreCopiedToChannel) { - const auto kExpectedMessage = - common::CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o'); + const auto kExpectedMessage = CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o'); const size_t kNumMessages = 3; ASSERT_TRUE(relay()->Activate()); @@ -621,15 +614,14 @@ TEST_F(DATA_SocketChannelRelayTxTest, ASSERT_TRUE(sdus[0]); ASSERT_TRUE(sdus[1]); ASSERT_TRUE(sdus[2]); - EXPECT_TRUE(common::ContainersEqual(kExpectedMessage, *sdus[0])); - EXPECT_TRUE(common::ContainersEqual(kExpectedMessage, *sdus[1])); - EXPECT_TRUE(common::ContainersEqual(kExpectedMessage, *sdus[2])); + EXPECT_TRUE(ContainersEqual(kExpectedMessage, *sdus[0])); + EXPECT_TRUE(ContainersEqual(kExpectedMessage, *sdus[1])); + EXPECT_TRUE(ContainersEqual(kExpectedMessage, *sdus[2])); } TEST_F(DATA_SocketChannelRelayTxTest, MultipleSdusAreCopiedToChannelInOneRelayTask) { - const auto kExpectedMessage = - common::CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o'); + const auto kExpectedMessage = CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o'); const size_t kNumMessages = 3; ASSERT_TRUE(relay()->Activate()); @@ -650,14 +642,14 @@ TEST_F(DATA_SocketChannelRelayTxTest, ASSERT_TRUE(sdus[0]); ASSERT_TRUE(sdus[1]); ASSERT_TRUE(sdus[2]); - EXPECT_TRUE(common::ContainersEqual(kExpectedMessage, *sdus[0])); - EXPECT_TRUE(common::ContainersEqual(kExpectedMessage, *sdus[1])); - EXPECT_TRUE(common::ContainersEqual(kExpectedMessage, *sdus[2])); + EXPECT_TRUE(ContainersEqual(kExpectedMessage, *sdus[0])); + EXPECT_TRUE(ContainersEqual(kExpectedMessage, *sdus[1])); + EXPECT_TRUE(ContainersEqual(kExpectedMessage, *sdus[2])); } TEST_F(DATA_SocketChannelRelayTxTest, OversizedSduIsDropped) { const size_t kMessageBufSize = channel()->tx_mtu() * 5; - common::DynamicByteBuffer large_message(kMessageBufSize); + DynamicByteBuffer large_message(kMessageBufSize); large_message.Fill(kGoodChar); ASSERT_TRUE(relay()->Activate()); @@ -673,11 +665,11 @@ TEST_F(DATA_SocketChannelRelayTxTest, OversizedSduIsDropped) { } TEST_F(DATA_SocketChannelRelayTxTest, ValidSduAfterOversizedSduIsIgnored) { - const auto kSentMsg = common::CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o'); + const auto kSentMsg = CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o'); ASSERT_TRUE(relay()->Activate()); { - common::DynamicByteBuffer dropped_msg(channel()->tx_mtu() + 1); + DynamicByteBuffer dropped_msg(channel()->tx_mtu() + 1); size_t n_bytes_written = 0; zx_status_t write_res = ZX_ERR_INTERNAL; dropped_msg.Fill(kGoodChar); diff --git a/src/connectivity/bluetooth/core/bt-host/fidl/gatt_client_server.cc b/src/connectivity/bluetooth/core/bt-host/fidl/gatt_client_server.cc index 3310b79239111670fb645548f442839e0f241231..c29bfb878fc11efaee9bd5e531d4c1cd91b2d23a 100644 --- a/src/connectivity/bluetooth/core/bt-host/fidl/gatt_client_server.cc +++ b/src/connectivity/bluetooth/core/bt-host/fidl/gatt_client_server.cc @@ -31,7 +31,7 @@ GattClientServer::GattClientServer(bt::gatt::PeerId peer_id, void GattClientServer::ListServices(::fidl::VectorPtr<::std::string> fidl_uuids, ListServicesCallback callback) { // Parse the UUID list. - std::vector<bt::common::UUID> uuids; + std::vector<bt::UUID> uuids; if (!fidl_uuids.is_null()) { // Allocate all at once and convert in-place. uuids.resize(fidl_uuids->size()); diff --git a/src/connectivity/bluetooth/core/bt-host/fidl/gatt_remote_service_server.cc b/src/connectivity/bluetooth/core/bt-host/fidl/gatt_remote_service_server.cc index 07fdc525596d147f204c094c3daec57eb3136616..2aa4606dcd2b7252b7053246a58e8727dcaffd83 100644 --- a/src/connectivity/bluetooth/core/bt-host/fidl/gatt_remote_service_server.cc +++ b/src/connectivity/bluetooth/core/bt-host/fidl/gatt_remote_service_server.cc @@ -12,8 +12,8 @@ using fuchsia::bluetooth::gatt::Characteristic; using fuchsia::bluetooth::gatt::CharacteristicPtr; using fuchsia::bluetooth::gatt::Descriptor; -using bt::common::ByteBuffer; -using bt::common::MutableBufferView; +using bt::ByteBuffer; +using bt::MutableBufferView; using bt::gatt::IdType; using bt::gatt::RemoteCharacteristic; @@ -77,8 +77,7 @@ void GattRemoteServiceServer::DiscoverCharacteristics( } } - callback(fidl_helpers::StatusToFidl(status, ""), - std::move(fidl_chrcs)); + callback(fidl_helpers::StatusToFidl(status, ""), std::move(fidl_chrcs)); }; service_->DiscoverCharacteristics(std::move(res_cb)); @@ -86,8 +85,8 @@ void GattRemoteServiceServer::DiscoverCharacteristics( void GattRemoteServiceServer::ReadCharacteristic( uint64_t id, ReadCharacteristicCallback callback) { - auto cb = [callback = std::move(callback)]( - bt::att::Status status, const bt::common::ByteBuffer& value) { + auto cb = [callback = std::move(callback)](bt::att::Status status, + const bt::ByteBuffer& value) { // We always reply with a non-null value. std::vector<uint8_t> vec; @@ -108,8 +107,8 @@ void GattRemoteServiceServer::ReadCharacteristic( void GattRemoteServiceServer::ReadLongCharacteristic( uint64_t id, uint16_t offset, uint16_t max_bytes, ReadLongCharacteristicCallback callback) { - auto cb = [callback = std::move(callback)]( - bt::att::Status status, const bt::common::ByteBuffer& value) { + auto cb = [callback = std::move(callback)](bt::att::Status status, + const bt::ByteBuffer& value) { // We always reply with a non-null value. std::vector<uint8_t> vec; @@ -146,8 +145,8 @@ void GattRemoteServiceServer::WriteCharacteristicWithoutResponse( void GattRemoteServiceServer::ReadDescriptor(uint64_t id, ReadDescriptorCallback callback) { - auto cb = [callback = std::move(callback)]( - bt::att::Status status, const bt::common::ByteBuffer& value) { + auto cb = [callback = std::move(callback)](bt::att::Status status, + const bt::ByteBuffer& value) { // We always reply with a non-null value. std::vector<uint8_t> vec; @@ -168,8 +167,8 @@ void GattRemoteServiceServer::ReadDescriptor(uint64_t id, void GattRemoteServiceServer::ReadLongDescriptor( uint64_t id, uint16_t offset, uint16_t max_bytes, ReadLongDescriptorCallback callback) { - auto cb = [callback = std::move(callback)]( - bt::att::Status status, const bt::common::ByteBuffer& value) { + auto cb = [callback = std::move(callback)](bt::att::Status status, + const bt::ByteBuffer& value) { // We always reply with a non-null value. std::vector<uint8_t> vec; diff --git a/src/connectivity/bluetooth/core/bt-host/fidl/gatt_server_server.cc b/src/connectivity/bluetooth/core/bt-host/fidl/gatt_server_server.cc index 0fc851eb12e41ceb35fd520f3ea8e206244bea7d..5ffbd42e17d1ab242df450432d4917b065a59056 100644 --- a/src/connectivity/bluetooth/core/bt-host/fidl/gatt_server_server.cc +++ b/src/connectivity/bluetooth/core/bt-host/fidl/gatt_server_server.cc @@ -77,8 +77,8 @@ DescriptorResult NewDescriptor(const Descriptor& fidl_desc) { auto read_reqs = ParseSecurityRequirements(fidl_desc.permissions->read); auto write_reqs = ParseSecurityRequirements(fidl_desc.permissions->write); - bt::common::UUID type; - if (!bt::common::StringToUuid(fidl_desc.type, &type)) { + bt::UUID type; + if (!bt::StringToUuid(fidl_desc.type, &type)) { return DescriptorResult("Invalid descriptor UUID"); } @@ -107,8 +107,8 @@ CharacteristicResult NewCharacteristic(const Characteristic& fidl_chrc) { auto write_reqs = ParseSecurityRequirements(fidl_chrc.permissions->write); auto update_reqs = ParseSecurityRequirements(fidl_chrc.permissions->update); - bt::common::UUID type; - if (!bt::common::StringToUuid(fidl_chrc.type, &type)) { + bt::UUID type; + if (!bt::StringToUuid(fidl_chrc.type, &type)) { return CharacteristicResult("Invalid characteristic UUID"); } @@ -229,8 +229,8 @@ void GattServerServer::PublishService( return; } - bt::common::UUID service_type; - if (!bt::common::StringToUuid(service_info.type, &service_type)) { + bt::UUID service_type; + if (!bt::StringToUuid(service_info.type, &service_type)) { auto error = fidl_helpers::NewFidlError(ErrorCode::INVALID_ARGUMENTS, "Invalid service UUID"); callback(std::move(error)); @@ -262,7 +262,7 @@ void GattServerServer::PublishService( if (self) { self->OnReadRequest(svc_id, id, offset, std::move(responder)); } else { - responder(bt::att::ErrorCode::kUnlikelyError, bt::common::BufferView()); + responder(bt::att::ErrorCode::kUnlikelyError, bt::BufferView()); } }; auto write_handler = [self](auto svc_id, auto id, auto offset, @@ -325,14 +325,14 @@ void GattServerServer::OnReadRequest(bt::gatt::IdType service_id, bt::gatt::ReadResponder responder) { auto iter = services_.find(service_id); if (iter == services_.end()) { - responder(bt::att::ErrorCode::kUnlikelyError, bt::common::BufferView()); + responder(bt::att::ErrorCode::kUnlikelyError, bt::BufferView()); return; } auto cb = [responder = std::move(responder)](fidl::VectorPtr<uint8_t> value, auto error_code) { responder(GattErrorCodeFromFidl(error_code, true /* is_read */), - bt::common::BufferView(value->data(), value->size())); + bt::BufferView(value->data(), value->size())); }; auto* delegate = iter->second->delegate(); @@ -342,7 +342,7 @@ void GattServerServer::OnReadRequest(bt::gatt::IdType service_id, void GattServerServer::OnWriteRequest(bt::gatt::IdType service_id, bt::gatt::IdType id, uint16_t offset, - const bt::common::ByteBuffer& value, + const bt::ByteBuffer& value, bt::gatt::WriteResponder responder) { auto iter = services_.find(service_id); if (iter == services_.end()) { diff --git a/src/connectivity/bluetooth/core/bt-host/fidl/gatt_server_server.h b/src/connectivity/bluetooth/core/bt-host/fidl/gatt_server_server.h index 441395530bbb86e34318b9ee33c0b7d60beb88e9..98dd031805a6fd5eb1c23130caf3a94a06d0665d 100644 --- a/src/connectivity/bluetooth/core/bt-host/fidl/gatt_server_server.h +++ b/src/connectivity/bluetooth/core/bt-host/fidl/gatt_server_server.h @@ -51,7 +51,7 @@ class GattServerServer // Called when a remote device issues a write request to one of our services. void OnWriteRequest(bt::gatt::IdType service_id, bt::gatt::IdType id, - uint16_t offset, const bt::common::ByteBuffer& value, + uint16_t offset, const bt::ByteBuffer& value, bt::gatt::WriteResponder responder); // Called when a remote device has configured notifications or indications on diff --git a/src/connectivity/bluetooth/core/bt-host/fidl/helpers.cc b/src/connectivity/bluetooth/core/bt-host/fidl/helpers.cc index 28dd4b46d69538bed081bbfc2b710b382d60c507..1012156feeea7f5aa4b78291aeff6b22df0ff8f7 100644 --- a/src/connectivity/bluetooth/core/bt-host/fidl/helpers.cc +++ b/src/connectivity/bluetooth/core/bt-host/fidl/helpers.cc @@ -64,29 +64,29 @@ fhost::SecurityProperties SecurityPropsToFidl( return result; } -bt::common::DeviceAddress::Type BondingAddrTypeFromFidl( +bt::DeviceAddress::Type BondingAddrTypeFromFidl( const fhost::AddressType& type) { switch (type) { case fhost::AddressType::LE_RANDOM: - return bt::common::DeviceAddress::Type::kLERandom; + return bt::DeviceAddress::Type::kLERandom; case fhost::AddressType::LE_PUBLIC: - return bt::common::DeviceAddress::Type::kLEPublic; + return bt::DeviceAddress::Type::kLEPublic; case fhost::AddressType::BREDR: - return bt::common::DeviceAddress::Type::kBREDR; + return bt::DeviceAddress::Type::kBREDR; default: ZX_PANIC("invalid address type: %u", static_cast<unsigned int>(type)); break; } - return bt::common::DeviceAddress::Type::kBREDR; + return bt::DeviceAddress::Type::kBREDR; } -fhost::AddressType BondingAddrTypeToFidl(bt::common::DeviceAddress::Type type) { +fhost::AddressType BondingAddrTypeToFidl(bt::DeviceAddress::Type type) { switch (type) { - case bt::common::DeviceAddress::Type::kLERandom: + case bt::DeviceAddress::Type::kLERandom: return fhost::AddressType::LE_RANDOM; - case bt::common::DeviceAddress::Type::kLEPublic: + case bt::DeviceAddress::Type::kLEPublic: return fhost::AddressType::LE_PUBLIC; - case bt::common::DeviceAddress::Type::kBREDR: + case bt::DeviceAddress::Type::kBREDR: return fhost::AddressType::BREDR; default: // Anonymous is not a valid address type to use for bonding, so we treat @@ -129,32 +129,32 @@ fhost::RemoteKey KeyToFidl(const bt::sm::Key& key) { } // namespace -std::optional<bt::common::PeerId> PeerIdFromString(const std::string& id) { +std::optional<bt::PeerId> PeerIdFromString(const std::string& id) { uint64_t value; if (!fxl::StringToNumberWithError<decltype(value)>(id, &value, fxl::Base::k16)) { return std::nullopt; } - return bt::common::PeerId(value); + return bt::PeerId(value); } -ErrorCode HostErrorToFidl(bt::common::HostError host_error) { +ErrorCode HostErrorToFidl(bt::HostError host_error) { switch (host_error) { - case bt::common::HostError::kFailed: + case bt::HostError::kFailed: return ErrorCode::FAILED; - case bt::common::HostError::kTimedOut: + case bt::HostError::kTimedOut: return ErrorCode::TIMED_OUT; - case bt::common::HostError::kInvalidParameters: + case bt::HostError::kInvalidParameters: return ErrorCode::INVALID_ARGUMENTS; - case bt::common::HostError::kCanceled: + case bt::HostError::kCanceled: return ErrorCode::CANCELED; - case bt::common::HostError::kInProgress: + case bt::HostError::kInProgress: return ErrorCode::IN_PROGRESS; - case bt::common::HostError::kNotSupported: + case bt::HostError::kNotSupported: return ErrorCode::NOT_SUPPORTED; - case bt::common::HostError::kNotFound: + case bt::HostError::kNotFound: return ErrorCode::NOT_FOUND; - case bt::common::HostError::kProtocolError: + case bt::HostError::kProtocolError: return ErrorCode::PROTOCOL_ERROR; default: break; @@ -194,7 +194,7 @@ bt::sm::IOCapability IoCapabilityFromFidl(fctrl::InputCapabilityType input, bt::sm::PairingData PairingDataFromFidl(const fhost::LEData& data) { bt::sm::PairingData result; - result.identity_address = bt::common::DeviceAddress( + result.identity_address = bt::DeviceAddress( BondingAddrTypeFromFidl(data.address_type), data.address); if (data.ltk) { result.ltk = LtkFromFidl(*data.ltk); @@ -208,9 +208,7 @@ bt::sm::PairingData PairingDataFromFidl(const fhost::LEData& data) { return result; } -bt::common::UInt128 LocalKeyFromFidl(const fhost::LocalKey& key) { - return key.value; -} +bt::UInt128 LocalKeyFromFidl(const fhost::LocalKey& key) { return key.value; } std::optional<bt::sm::LTK> BrEdrKeyFromFidl(const fhost::BREDRData& data) { if (data.link_key) { @@ -388,7 +386,7 @@ bool IsScanFilterValid(const fble::ScanFilter& fidl_filter) { return true; for (const auto& uuid_str : *fidl_filter.service_uuids) { - if (!bt::common::IsStringValidUuid(uuid_str)) + if (!bt::IsStringValidUuid(uuid_str)) return false; } @@ -400,10 +398,10 @@ bool PopulateDiscoveryFilter(const fble::ScanFilter& fidl_filter, ZX_DEBUG_ASSERT(out_filter); if (fidl_filter.service_uuids) { - std::vector<bt::common::UUID> uuids; + std::vector<bt::UUID> uuids; for (const auto& uuid_str : *fidl_filter.service_uuids) { - bt::common::UUID uuid; - if (!bt::common::StringToUuid(uuid_str, &uuid)) { + bt::UUID uuid; + if (!bt::StringToUuid(uuid_str, &uuid)) { bt_log(TRACE, "bt-host", "invalid parameters given to scan filter"); return false; } @@ -439,10 +437,10 @@ bool PopulateDiscoveryFilter(const fble::ScanFilter& fidl_filter, // static fidl::VectorPtr<uint8_t> -fidl::TypeConverter<fidl::VectorPtr<uint8_t>, bt::common::ByteBuffer>::Convert( - const bt::common::ByteBuffer& from) { +fidl::TypeConverter<fidl::VectorPtr<uint8_t>, bt::ByteBuffer>::Convert( + const bt::ByteBuffer& from) { auto to = fidl::VectorPtr<uint8_t>::New(from.size()); - bt::common::MutableBufferView view(to->data(), to->size()); + bt::MutableBufferView view(to->data(), to->size()); view.Write(from); return to; } diff --git a/src/connectivity/bluetooth/core/bt-host/fidl/helpers.h b/src/connectivity/bluetooth/core/bt-host/fidl/helpers.h index c32dc193c0456ca697c74f5a42bbb53f8e6c93e0..04bc475b1bef221c5df5c362f4f0811aff487162 100644 --- a/src/connectivity/bluetooth/core/bt-host/fidl/helpers.h +++ b/src/connectivity/bluetooth/core/bt-host/fidl/helpers.h @@ -37,18 +37,18 @@ namespace fidl_helpers { // TODO(BT-305): Temporary logic for converting between the stack identifier // type (integer) and FIDL identifier type (string). Remove these once all FIDL // interfaces have been converted to use integer IDs. -std::optional<bt::common::PeerId> PeerIdFromString(const std::string& id); +std::optional<bt::PeerId> PeerIdFromString(const std::string& id); -// Functions for generating a FIDL bluetooth::common::Status +// Functions for generating a FIDL bluetooth::Status -fuchsia::bluetooth::ErrorCode HostErrorToFidl(bt::common::HostError host_error); +fuchsia::bluetooth::ErrorCode HostErrorToFidl(bt::HostError host_error); fuchsia::bluetooth::Status NewFidlError( fuchsia::bluetooth::ErrorCode error_code, std::string description); template <typename ProtocolErrorCode> fuchsia::bluetooth::Status StatusToFidl( - const bt::common::Status<ProtocolErrorCode>& status, std::string msg = "") { + const bt::Status<ProtocolErrorCode>& status, std::string msg = "") { fuchsia::bluetooth::Status fidl_status; if (status.is_success()) { return fidl_status; @@ -81,8 +81,7 @@ fuchsia::bluetooth::control::RemoteDevicePtr NewRemoteDevicePtr( // Functions to convert Host FIDL library objects. bt::sm::PairingData PairingDataFromFidl( const fuchsia::bluetooth::host::LEData& data); -bt::common::UInt128 LocalKeyFromFidl( - const fuchsia::bluetooth::host::LocalKey& key); +bt::UInt128 LocalKeyFromFidl(const fuchsia::bluetooth::host::LocalKey& key); std::optional<bt::sm::LTK> BrEdrKeyFromFidl( const fuchsia::bluetooth::host::BREDRData& data); fuchsia::bluetooth::host::BondingData NewBondingData( @@ -90,7 +89,7 @@ fuchsia::bluetooth::host::BondingData NewBondingData( // Functions to construct FIDL LE library objects from library objects. fuchsia::bluetooth::le::AdvertisingDataPtr NewAdvertisingData( - const bt::common::ByteBuffer& advertising_data); + const bt::ByteBuffer& advertising_data); fuchsia::bluetooth::le::RemoteDevicePtr NewLERemoteDevice( const bt::gap::Peer& peer); @@ -107,10 +106,10 @@ bool PopulateDiscoveryFilter( } // namespace fidl_helpers } // namespace bthost -// fidl::TypeConverter specializations for common::ByteBuffer and friends. +// fidl::TypeConverter specializations for ByteBuffer and friends. template <> -struct fidl::TypeConverter<fidl::VectorPtr<uint8_t>, bt::common::ByteBuffer> { - static fidl::VectorPtr<uint8_t> Convert(const bt::common::ByteBuffer& from); +struct fidl::TypeConverter<fidl::VectorPtr<uint8_t>, bt::ByteBuffer> { + static fidl::VectorPtr<uint8_t> Convert(const bt::ByteBuffer& from); }; #endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_FIDL_HELPERS_H_ diff --git a/src/connectivity/bluetooth/core/bt-host/fidl/host_server.cc b/src/connectivity/bluetooth/core/bt-host/fidl/host_server.cc index 12700bc1aec4699c1a744da71b14b4d1689c4130..b59043c04410939799d6790c01a0c13078642840 100644 --- a/src/connectivity/bluetooth/core/bt-host/fidl/host_server.cc +++ b/src/connectivity/bluetooth/core/bt-host/fidl/host_server.cc @@ -26,7 +26,7 @@ namespace bthost { -using bt::gap::PeerId; +using bt::PeerId; using bt::sm::IOCapability; using fidl_helpers::NewFidlError; using fidl_helpers::PeerIdFromString; @@ -129,7 +129,7 @@ void HostServer::SetDeviceClass( NewFidlError(ErrorCode::INVALID_ARGUMENTS, "Can't Set Device Class")); return; } - bt::common::DeviceClass dev_class(device_class.value); + bt::DeviceClass dev_class(device_class.value); adapter()->SetDeviceClass( dev_class, [callback = std::move(callback)](auto status) { callback(fidl_helpers::StatusToFidl(status, "Can't Set Device Class")); @@ -284,7 +284,7 @@ void HostServer::AddBondedDevices(::std::vector<BondingData> bonds, continue; } - bt::common::DeviceAddress address; + bt::DeviceAddress address; bt::sm::PairingData le_bond_data; if (bond.le) { if (bond.bredr && bond.le->address != bond.bredr->address) { @@ -305,8 +305,8 @@ void HostServer::AddBondedDevices(::std::vector<BondingData> bonds, std::optional<bt::sm::LTK> bredr_link_key; if (bond.bredr) { // Dual-mode peers will have a BR/EDR-typed address. - address = bt::common::DeviceAddress( - bt::common::DeviceAddress::Type::kBREDR, bond.bredr->address); + address = bt::DeviceAddress(bt::DeviceAddress::Type::kBREDR, + bond.bredr->address); bredr_link_key = fidl_helpers::BrEdrKeyFromFidl(*bond.bredr); } @@ -347,7 +347,7 @@ void HostServer::RegisterLowEnergyConnection( bt::gap::LowEnergyConnectionRefPtr conn_ref, bool auto_connect) { ZX_DEBUG_ASSERT(conn_ref); - bt::gap::PeerId id = conn_ref->peer_identifier(); + bt::PeerId id = conn_ref->peer_identifier(); auto iter = le_connections_.find(id); if (iter != le_connections_.end()) { bt_log(WARN, "bt-host", "peer already connected; reference dropped"); @@ -755,7 +755,7 @@ void HostServer::OnPeerUpdated(const bt::gap::Peer& peer) { this->binding()->events().OnDeviceUpdated(std::move(*fidl_device)); } -void HostServer::OnPeerRemoved(bt::gap::PeerId identifier) { +void HostServer::OnPeerRemoved(bt::PeerId identifier) { // TODO(armansito): Notify only if the peer is connectable for symmetry with // OnPeerUpdated? this->binding()->events().OnDeviceRemoved(identifier.ToString()); diff --git a/src/connectivity/bluetooth/core/bt-host/fidl/host_server.h b/src/connectivity/bluetooth/core/bt-host/fidl/host_server.h index 7a0f87c7fc496ffc10a4d337ad081eb291e97e8a..a62e15bca6229dd695b7acba58f7fa180049356d 100644 --- a/src/connectivity/bluetooth/core/bt-host/fidl/host_server.h +++ b/src/connectivity/bluetooth/core/bt-host/fidl/host_server.h @@ -81,24 +81,23 @@ class HostServer : public AdapterServerBase<fuchsia::bluetooth::host::Host>, // bt::gap::PairingDelegate overrides: bt::sm::IOCapability io_capability() const override; - void CompletePairing(bt::gap::PeerId id, bt::sm::Status status) override; - void ConfirmPairing(bt::gap::PeerId id, ConfirmCallback confirm) override; - void DisplayPasskey(bt::gap::PeerId id, uint32_t passkey, + void CompletePairing(bt::PeerId id, bt::sm::Status status) override; + void ConfirmPairing(bt::PeerId id, ConfirmCallback confirm) override; + void DisplayPasskey(bt::PeerId id, uint32_t passkey, ConfirmCallback confirm) override; - void RequestPasskey(bt::gap::PeerId id, - PasskeyResponseCallback respond) override; + void RequestPasskey(bt::PeerId id, PasskeyResponseCallback respond) override; // Called by |adapter()->peer_cache()| when a peer is updated. void OnPeerUpdated(const bt::gap::Peer& peer); // Called by |adapter()->peer_cache()| when a peer is removed. - void OnPeerRemoved(bt::gap::PeerId identifier); + void OnPeerRemoved(bt::PeerId identifier); // Called by |adapter()->peer_cache()| when a peer is bonded. void OnPeerBonded(const bt::gap::Peer& peer); - void ConnectLowEnergy(bt::gap::PeerId id, ConnectCallback callback); - void ConnectBrEdr(bt::gap::PeerId peer_id, ConnectCallback callback); + void ConnectLowEnergy(bt::PeerId id, ConnectCallback callback); + void ConnectBrEdr(bt::PeerId peer_id, ConnectCallback callback); // Called when a connection is established to a peer, either when initiated // by a user via a client of Host.fidl, or automatically by the GAP adapter @@ -152,7 +151,7 @@ class HostServer : public AdapterServerBase<fuchsia::bluetooth::host::Host>, // auto-connected by the system. // TODO(armansito): Consider storing auto-connected references separately from // directly connected references. - std::unordered_map<bt::gap::PeerId, bt::gap::LowEnergyConnectionRefPtr> + std::unordered_map<bt::PeerId, bt::gap::LowEnergyConnectionRefPtr> le_connections_; // Keep this as the last member to make sure that all weak pointers are diff --git a/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_central_server.cc b/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_central_server.cc index 439c58e82156d7cddc82632ca87080fe8194997b..8d1195566f4475d5ca1440a889766779f2897f19 100644 --- a/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_central_server.cc +++ b/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_central_server.cc @@ -260,8 +260,7 @@ void LowEnergyCentralServer::NotifyScanStateChanged(bool scanning) { binding()->events().OnScanStateChanged(scanning); } -void LowEnergyCentralServer::NotifyPeripheralDisconnected( - bt::gap::PeerId peer_id) { +void LowEnergyCentralServer::NotifyPeripheralDisconnected(bt::PeerId peer_id) { binding()->events().OnPeripheralDisconnected(peer_id.ToString()); } diff --git a/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_central_server.h b/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_central_server.h index 63f827cdad46253a907eb01457a2b65f2b6ef4ac..13cdd73ce5128d3bf24be98a543df6e0c5292262 100644 --- a/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_central_server.h +++ b/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_central_server.h @@ -53,7 +53,7 @@ class LowEnergyCentralServer // Notifies the delegate that the device with the given identifier has been // disconnected. - void NotifyPeripheralDisconnected(bt::gap::PeerId peer_id); + void NotifyPeripheralDisconnected(bt::PeerId peer_id); // The GATT host is used to instantiate GATT Clients upon connection. fbl::RefPtr<GattHost> gatt_host_; @@ -68,7 +68,7 @@ class LowEnergyCentralServer // a. nullptr, if a connect request to this device is currently pending. // b. a valid reference if this Central is holding a connection reference to // this device. - std::unordered_map<bt::gap::PeerId, bt::gap::LowEnergyConnectionRefPtr> + std::unordered_map<bt::PeerId, bt::gap::LowEnergyConnectionRefPtr> connections_; // Keep this as the last member to make sure that all weak pointers are diff --git a/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_peripheral_server.cc b/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_peripheral_server.cc index 987573b02a97ec0c8fa40577e8ff90f649cd4f53..84270424f1f88fbb4f9ebd723ab6815645a32b5d 100644 --- a/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_peripheral_server.cc +++ b/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_peripheral_server.cc @@ -29,11 +29,11 @@ namespace { std::string MessageFromStatus(bt::hci::Status status) { switch (status.error()) { - case bt::common::HostError::kNoError: + case bt::HostError::kNoError: return "Success"; - case bt::common::HostError::kNotSupported: + case bt::HostError::kNotSupported: return "Maximum advertisement amount reached"; - case bt::common::HostError::kInvalidParameters: + case bt::HostError::kInvalidParameters: return "Advertisement exceeds maximum allowed length"; default: return status.ToString(); diff --git a/src/connectivity/bluetooth/core/bt-host/fidl/profile_server.cc b/src/connectivity/bluetooth/core/bt-host/fidl/profile_server.cc index 1382fb803c263c9e0c2e5da6bf114cd50f83c9b1..6511da205154db2b347e0f8e300932c0247959db 100644 --- a/src/connectivity/bluetooth/core/bt-host/fidl/profile_server.cc +++ b/src/connectivity/bluetooth/core/bt-host/fidl/profile_server.cc @@ -64,7 +64,7 @@ bool FidlToDataElement(const fidlbredr::DataElement& fidl, if (!fidl.data.is_uuid()) { return false; } - bt::common::UUID uuid; + bt::UUID uuid; bool success = StringToUuid(fidl.data.uuid(), &uuid); if (!success) { return false; @@ -154,7 +154,7 @@ fidlbredr::DataElementPtr DataElementToFidl(const bt::sdp::DataElement* in) { } case bt::sdp::DataElement::Type::kUuid: { elem->type = DataElementType::UUID; - auto uuid = in->Get<bt::common::UUID>(); + auto uuid = in->Get<bt::UUID>(); ZX_DEBUG_ASSERT(uuid); elem->data.uuid() = uuid->ToString(); return elem; @@ -202,7 +202,7 @@ fidlbredr::ProtocolDescriptorPtr DataElementToProtocolDescriptor( if (in->type() != bt::sdp::DataElement::Type::kSequence) { return nullptr; } - const auto protocol_uuid = in->At(0)->Get<bt::common::UUID>(); + const auto protocol_uuid = in->At(0)->Get<bt::UUID>(); if (!protocol_uuid) { return nullptr; } @@ -227,7 +227,7 @@ fidlbredr::ProfileDescriptorPtr DataElementToProfileDescriptor( if (!profile_elem) { return nullptr; } - const auto profile_uuid = profile_elem->Get<bt::common::UUID>(); + const auto profile_uuid = profile_elem->Get<bt::UUID>(); if (!profile_uuid) { return nullptr; } @@ -271,7 +271,7 @@ void AddProtocolDescriptorList( fidl::ToUnderlying(descriptor.protocol), protocol_params.ToString().c_str()); rec->AddProtocolDescriptor( - id, bt::common::UUID(static_cast<uint16_t>(descriptor.protocol)), + id, bt::UUID(static_cast<uint16_t>(descriptor.protocol)), std::move(protocol_params)); } } @@ -304,12 +304,12 @@ void ProfileServer::AddService(fidlbredr::ServiceDefinition definition, ZX_DEBUG_ASSERT(sdp); bt::sdp::ServiceRecord rec; - std::vector<bt::common::UUID> classes; + std::vector<bt::UUID> classes; for (auto& uuid_str : definition.service_class_uuids) { - bt::common::UUID uuid; + bt::UUID uuid; bt_log(SPEW, "profile_server", "Setting Service Class UUID %s", uuid_str.c_str()); - bool success = bt::common::StringToUuid(uuid_str, &uuid); + bool success = bt::StringToUuid(uuid_str, &uuid); ZX_DEBUG_ASSERT(success); classes.emplace_back(std::move(uuid)); } @@ -329,7 +329,7 @@ void ProfileServer::AddService(fidlbredr::ServiceDefinition definition, for (const auto& profile : definition.profile_descriptors) { bt_log(SPEW, "profile_server", "Adding Profile %#x v%d.%d", profile.profile_id, profile.major_version, profile.minor_version); - rec.AddProfile(bt::common::UUID(uint16_t(profile.profile_id)), + rec.AddProfile(bt::UUID(uint16_t(profile.profile_id)), profile.major_version, profile.minor_version); } @@ -386,7 +386,7 @@ void ProfileServer::RemoveService(uint64_t service_id) { void ProfileServer::AddSearch( fidlbredr::ServiceClassProfileIdentifier service_uuid, std::vector<uint16_t> attr_ids) { - bt::common::UUID search_uuid(static_cast<uint32_t>(service_uuid)); + bt::UUID search_uuid(static_cast<uint32_t>(service_uuid)); std::unordered_set<bt::sdp::AttributeId> attributes(attr_ids.begin(), attr_ids.end()); if (!attr_ids.empty()) { @@ -451,7 +451,7 @@ void ProfileServer::OnChannelConnected( } void ProfileServer::OnServiceFound( - bt::common::PeerId peer_id, + bt::PeerId peer_id, const std::map<bt::sdp::AttributeId, bt::sdp::DataElement>& attributes) { // Convert ProfileDescriptor Attribute auto it = attributes.find(bt::sdp::kBluetoothProfileDescriptorList); diff --git a/src/connectivity/bluetooth/core/bt-host/fidl/profile_server.h b/src/connectivity/bluetooth/core/bt-host/fidl/profile_server.h index bf5bba381831d3558cf478956214404f4c7a0e48..e2cab139120299fedbd8e2a37c746ac3f3d9b44d 100644 --- a/src/connectivity/bluetooth/core/bt-host/fidl/profile_server.h +++ b/src/connectivity/bluetooth/core/bt-host/fidl/profile_server.h @@ -45,7 +45,7 @@ class ProfileServer // Callback for services found on connected device void OnServiceFound( - bt::common::PeerId peer_id, + bt::PeerId peer_id, const std::map<bt::sdp::AttributeId, bt::sdp::DataElement>& attributes); // Registered service IDs handed out, correlated with Service Handles. diff --git a/src/connectivity/bluetooth/core/bt-host/gap/adapter.cc b/src/connectivity/bluetooth/core/bt-host/gap/adapter.cc index 402062e85c724260ef5676f786a159b2cfd6698f..3c9450311ae0cc5465c44e3797ce1e4fade4f8ba 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/adapter.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/adapter.cc @@ -49,7 +49,7 @@ std::string GetHostname() { Adapter::Adapter(fxl::RefPtr<hci::Transport> hci, fbl::RefPtr<data::Domain> data_domain, fbl::RefPtr<gatt::GATT> gatt) - : identifier_(common::Random<AdapterId>()), + : identifier_(Random<AdapterId>()), dispatcher_(async_get_default_dispatcher()), hci_(hci), init_state_(State::kNotInitialized), @@ -192,8 +192,7 @@ void Adapter::ShutDown() { CleanUp(); } -bool Adapter::AddBondedPeer(PeerId identifier, - const common::DeviceAddress& address, +bool Adapter::AddBondedPeer(PeerId identifier, const DeviceAddress& address, const sm::PairingData& le_bond_data, const std::optional<sm::LTK>& link_key) { return peer_cache()->AddBondedPeer(identifier, address, le_bond_data, @@ -219,7 +218,7 @@ void Adapter::SetLocalName(std::string name, hci::StatusCallback callback) { } auto write_name = hci::CommandPacket::New( hci::kWriteLocalName, sizeof(hci::WriteLocalNameCommandParams)); - auto name_buf = common::MutableBufferView( + auto name_buf = MutableBufferView( write_name->mutable_view() ->mutable_payload<hci::WriteLocalNameCommandParams>() ->local_name, @@ -239,7 +238,7 @@ void Adapter::SetLocalName(std::string name, hci::StatusCallback callback) { }); } -void Adapter::SetDeviceClass(common::DeviceClass dev_class, +void Adapter::SetDeviceClass(DeviceClass dev_class, hci::StatusCallback callback) { auto write_dev_class = hci::CommandPacket::New( hci::kWriteClassOfDevice, sizeof(hci::WriteClassOfDeviceCommandParams)); @@ -529,8 +528,8 @@ void Adapter::InitializeStep4(InitializeCallback callback) { } // We use the public controller address as the local LE identity address. - common::DeviceAddress adapter_identity(common::DeviceAddress::Type::kLEPublic, - state_.controller_address()); + DeviceAddress adapter_identity(DeviceAddress::Type::kLEPublic, + state_.controller_address()); // Initialize the LE local address manager. le_address_manager_ = std::make_unique<LowEnergyAddressManager>( @@ -559,8 +558,8 @@ void Adapter::InitializeStep4(InitializeCallback callback) { // Initialize the BR/EDR manager objects if the controller supports BR/EDR. if (state_.IsBREDRSupported()) { - common::DeviceAddress local_bredr_address( - common::DeviceAddress::Type::kBREDR, state_.controller_address()); + DeviceAddress local_bredr_address(DeviceAddress::Type::kBREDR, + state_.controller_address()); bredr_connection_manager_ = std::make_unique<BrEdrConnectionManager>( hci_, &peer_cache_, local_bredr_address, data_domain_, @@ -592,8 +591,8 @@ void Adapter::InitializeStep4(InitializeCallback callback) { // Set the default device class - a computer with audio. // TODO(BT-641): set this from a platform configuration file - common::DeviceClass dev_class(common::DeviceClass::MajorClass::kComputer); - dev_class.SetServiceClasses({common::DeviceClass::ServiceClass::kAudio}); + DeviceClass dev_class(DeviceClass::MajorClass::kComputer); + dev_class.SetServiceClasses({DeviceClass::ServiceClass::kAudio}); SetDeviceClass(dev_class, [](const auto&) {}); // This completes the initialization sequence. diff --git a/src/connectivity/bluetooth/core/bt-host/gap/adapter.h b/src/connectivity/bluetooth/core/bt-host/gap/adapter.h index db3bd1b44e461b25c0f79829bf845900364034cc..9bcb4697f1a11d134fd6e877689fda9a81fbe5bd 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/adapter.h +++ b/src/connectivity/bluetooth/core/bt-host/gap/adapter.h @@ -43,7 +43,7 @@ class LowEnergyAdvertisingManager; class LowEnergyDiscoveryManager; // TODO(BT-734): Consider removing this identifier from the bt-host layer. -class AdapterId : public common::Identifier<uint64_t> { +class AdapterId : public Identifier<uint64_t> { public: constexpr explicit AdapterId(uint64_t value) : Identifier<uint64_t>(value) {} AdapterId() = default; @@ -152,7 +152,7 @@ class Adapter final { // Add a previously bonded device to the peer cache and set it up for // auto-connect procedures. - bool AddBondedPeer(PeerId identifier, const common::DeviceAddress& address, + bool AddBondedPeer(PeerId identifier, const DeviceAddress& address, const sm::PairingData& le_bond_data, const std::optional<sm::LTK>& link_key); @@ -170,8 +170,7 @@ class Adapter final { void SetLocalName(std::string name, hci::StatusCallback callback); // Sets the Device Class of this adapter. - void SetDeviceClass(common::DeviceClass dev_class, - hci::StatusCallback callback); + void SetDeviceClass(DeviceClass dev_class, hci::StatusCallback callback); // Assign a callback to be notified when a connection is automatically // established to a bonded LE peer in the directed connectable mode (Vol 3, diff --git a/src/connectivity/bluetooth/core/bt-host/gap/adapter_state.h b/src/connectivity/bluetooth/core/bt-host/gap/adapter_state.h index b7eab2605384eb6e7301e6615accabb6ee8c4fcf..49c654364f47154cea1ec22f99e4782ee0d21268 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/adapter_state.h +++ b/src/connectivity/bluetooth/core/bt-host/gap/adapter_state.h @@ -5,10 +5,10 @@ #ifndef SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_GAP_ADAPTER_STATE_H_ #define SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_GAP_ADAPTER_STATE_H_ -#include <cstdint> - #include <zircon/assert.h> +#include <cstdint> + #include "src/connectivity/bluetooth/core/bt-host/common/device_address.h" #include "src/connectivity/bluetooth/core/bt-host/gap/gap.h" #include "src/connectivity/bluetooth/core/bt-host/gap/low_energy_state.h" @@ -34,7 +34,7 @@ class AdapterState final { // device's identity address. This value can be zero if a Public Device // Address is not used. // - On BR/EDR/LE this is the LE Public Device Address AND the BD_ADDR. - const common::DeviceAddressBytes& controller_address() const { + const DeviceAddressBytes& controller_address() const { return controller_address_; } @@ -97,7 +97,7 @@ class AdapterState final { uint8_t supported_commands_[64]; // BD_ADDR (for classic) and Public Device Address (for LE). - common::DeviceAddressBytes controller_address_; + DeviceAddressBytes controller_address_; // The BR/EDR ACL data buffer size. We store this here as it is needed on // dual-mode controllers even if the host stack is compiled for LE-only. diff --git a/src/connectivity/bluetooth/core/bt-host/gap/adapter_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gap/adapter_unittest.cc index ce29c7eae957420aa4e1192fbf242fe29d220e93..eb34b554ca7106eca36446ae36e522e5fe5520e8 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/adapter_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/adapter_unittest.cc @@ -22,8 +22,6 @@ namespace bt { namespace gap { namespace { -using common::DeviceAddress; -using common::HostError; using testing::FakeController; using testing::FakePeer; using TestingBase = testing::FakeControllerTest<FakeController>; diff --git a/src/connectivity/bluetooth/core/bt-host/gap/advertising_data.cc b/src/connectivity/bluetooth/core/bt-host/gap/advertising_data.cc index 62805ae78efe75ea2052091fc467d54919e09083..8525484d1109373ff4c311ecaa5640fd3f7f99d8 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/advertising_data.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/advertising_data.cc @@ -23,7 +23,7 @@ template <typename T> struct fidl::TypeConverter<fidl::VectorPtr<unsigned char>, T> { static fidl::VectorPtr<unsigned char> Convert(const T& input) { - static_assert(std::is_base_of<bt::common::ByteBuffer, T>::value, ""); + static_assert(std::is_base_of<bt::ByteBuffer, T>::value, ""); fidl::VectorPtr<unsigned char> result = fidl::VectorPtr<unsigned char>::New(input.size()); @@ -37,12 +37,6 @@ namespace ble = fuchsia::bluetooth::le; namespace bt { namespace gap { -using common::BufferView; -using common::ByteBuffer; -using common::DynamicByteBuffer; -using common::MutableByteBuffer; -using common::UUID; - namespace { using UuidFunction = fit::function<void(const UUID&)>; diff --git a/src/connectivity/bluetooth/core/bt-host/gap/advertising_data.h b/src/connectivity/bluetooth/core/bt-host/gap/advertising_data.h index 0620431f68f419c4fc7008d8d78a1e661f0c44e8..20d5dfc29d504737d951705db87c61879d52270d 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/advertising_data.h +++ b/src/connectivity/bluetooth/core/bt-host/gap/advertising_data.h @@ -45,8 +45,7 @@ class AdvertisingData { // error, and true otherwise. |out_ad| is not guaranteed to be in any state // unless we return true. Does not clear |out_ad| so this function can be used // to merge multiple field blocks. - static bool FromBytes(const common::ByteBuffer& data, - AdvertisingData* out_ad); + static bool FromBytes(const ByteBuffer& data, AdvertisingData* out_ad); // Populate AdvertisingData |out_ad| from the corresponding FIDL object // |fidl_ad|. Overwrites existing contents of |out_ad|. Returns false if @@ -62,26 +61,25 @@ class AdvertisingData { // Add a UUID to the set of services advertised. // These service UUIDs will automatically be compressed to be represented in // the smallest space possible. - void AddServiceUuid(const common::UUID& uuid); + void AddServiceUuid(const UUID& uuid); // Get the service UUIDs represented in this advertisement. - const std::unordered_set<common::UUID>& service_uuids() const; + const std::unordered_set<UUID>& service_uuids() const; // Set some service data for the service specified by |uuid|. - void SetServiceData(const common::UUID& uuid, const common::ByteBuffer& data); + void SetServiceData(const UUID& uuid, const ByteBuffer& data); // Get a set of which UUIDs have service data in this advertisement. - const std::unordered_set<common::UUID> service_data_uuids() const; + const std::unordered_set<UUID> service_data_uuids() const; // View the currently set service data for |uuid|. // This view is not stable; it should be used only ephemerally. // Returns an empty BufferView if no service data is set for |uuid| - const common::BufferView service_data(const common::UUID& uuid) const; + const BufferView service_data(const UUID& uuid) const; // Set some Manufacturer specific data for the company identified by // |company_id| - void SetManufacturerData(const uint16_t company_id, - const common::BufferView& data); + void SetManufacturerData(const uint16_t company_id, const BufferView& data); // Get a set of which IDs have manufacturer data in this advertisement. const std::unordered_set<uint16_t> manufacturer_data_ids() const; @@ -92,7 +90,7 @@ class AdvertisingData { // NOTE: it is valid to send a manufacturer data with no data. Check that one // exists using manufacturer_data_ids() first. // This view is not stable; it should be used only ephemerally. - const common::BufferView manufacturer_data(const uint16_t company_id) const; + const BufferView manufacturer_data(const uint16_t company_id) const; // Sets the local TX Power // TODO(jamuraa): add documentation about where to get this number from @@ -127,7 +125,7 @@ class AdvertisingData { // Writes the byte representation of this to |buffer|. // Returns false without modifying |buffer| if there is not enough space // (if the buffer size is less than block_size()) - bool WriteBlock(common::MutableByteBuffer* buffer) const; + bool WriteBlock(MutableByteBuffer* buffer) const; // Makes a FIDL object that holds the same data fuchsia::bluetooth::le::AdvertisingDataPtr AsLEAdvertisingData() const; @@ -142,9 +140,9 @@ class AdvertisingData { std::optional<std::string> local_name_; std::optional<int8_t> tx_power_; std::optional<uint16_t> appearance_; - std::unordered_set<common::UUID> service_uuids_; - std::unordered_map<uint16_t, common::DynamicByteBuffer> manufacturer_data_; - std::unordered_map<common::UUID, common::DynamicByteBuffer> service_data_; + std::unordered_set<UUID> service_uuids_; + std::unordered_map<uint16_t, DynamicByteBuffer> manufacturer_data_; + std::unordered_map<UUID, DynamicByteBuffer> service_data_; std::unordered_set<std::string> uris_; @@ -163,7 +161,7 @@ class AdvertisingDataReader { public: // |data| must point to a valid piece of memory for the duration in which this // object is to remain alive. - explicit AdvertisingDataReader(const common::ByteBuffer& data); + explicit AdvertisingDataReader(const ByteBuffer& data); // Returns false if the fields of |data| have been formatted incorrectly. For // example, this could happen if the length of an advertising data structure @@ -173,7 +171,7 @@ class AdvertisingDataReader { // Returns the data and type fields of the next advertising data structure in // |out_data| and |out_type|. Returns false if there is no more data to read // or if the data is formatted incorrectly. - bool GetNextField(DataType* out_type, common::BufferView* out_data); + bool GetNextField(DataType* out_type, BufferView* out_data); // Returns true if there is more data to read. Returns false if the end of // data has been reached or if the current segment is malformed in a way that @@ -182,7 +180,7 @@ class AdvertisingDataReader { private: bool is_valid_; - common::BufferView remaining_; + BufferView remaining_; }; // Used for writing data in TLV-format as described at the beginning of the file @@ -192,18 +190,18 @@ class AdvertisingDataWriter { // |buffer| is the piece of memory on which this AdvertisingDataWriter should // operate. The buffer must out-live this instance and must point to a valid // piece of memory. - explicit AdvertisingDataWriter(common::MutableByteBuffer* buffer); + explicit AdvertisingDataWriter(MutableByteBuffer* buffer); // Writes the given piece of type/tag and data into the next available segment // in the underlying buffer. Returns false if there isn't enough space left in // the buffer for writing. Returns true on success. - bool WriteField(DataType type, const common::ByteBuffer& data); + bool WriteField(DataType type, const ByteBuffer& data); // The total number of bytes that have been written into the buffer. size_t bytes_written() const { return bytes_written_; } private: - common::MutableByteBuffer* buffer_; + MutableByteBuffer* buffer_; size_t bytes_written_; }; diff --git a/src/connectivity/bluetooth/core/bt-host/gap/advertising_data_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gap/advertising_data_unittest.cc index ac3a99286dec80f347028c6a7493971c473880bc..34223dcd67a1e6b1a8a41ebd883043ec5d4fa7e2 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/advertising_data_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/advertising_data_unittest.cc @@ -5,7 +5,6 @@ #include "src/connectivity/bluetooth/core/bt-host/gap/advertising_data.h" #include "gtest/gtest.h" - #include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" @@ -25,7 +24,7 @@ constexpr char kId3AsString[] = "12341234-0000-1000-8000-00805f9b34fb"; constexpr size_t kRandomDataSize = 100; TEST(GAP_AdvertisingDataTest, ReaderEmptyData) { - common::BufferView empty; + BufferView empty; AdvertisingDataReader reader(empty); EXPECT_FALSE(reader.is_valid()); EXPECT_FALSE(reader.HasMoreData()); @@ -41,11 +40,11 @@ TEST(GAP_AdvertisingDataTest, EncodeKnownURI) { AdvertisingData data; data.AddURI("https://abc.xyz"); - auto bytes = common::CreateStaticByteBuffer(0x0B, 0x24, 0x17, '/', '/', 'a', - 'b', 'c', '.', 'x', 'y', 'z'); + auto bytes = CreateStaticByteBuffer(0x0B, 0x24, 0x17, '/', '/', 'a', 'b', 'c', + '.', 'x', 'y', 'z'); EXPECT_EQ(bytes.size(), data.CalculateBlockSize()); - common::DynamicByteBuffer block(data.CalculateBlockSize()); + DynamicByteBuffer block(data.CalculateBlockSize()); data.WriteBlock(&block); EXPECT_TRUE(ContainersEqual(bytes, block)); } @@ -54,36 +53,35 @@ TEST(GAP_AdvertisingDataTest, EncodeUnknownURI) { AdvertisingData data; data.AddURI("flubs:xyz"); - auto bytes = common::CreateStaticByteBuffer(0x0B, 0x24, 0x01, 'f', 'l', 'u', - 'b', 's', ':', 'x', 'y', 'z'); + auto bytes = CreateStaticByteBuffer(0x0B, 0x24, 0x01, 'f', 'l', 'u', 'b', 's', + ':', 'x', 'y', 'z'); size_t block_size = data.CalculateBlockSize(); EXPECT_EQ(bytes.size(), block_size); - common::DynamicByteBuffer block(block_size); + DynamicByteBuffer block(block_size); data.WriteBlock(&block); EXPECT_TRUE(ContainersEqual(bytes, block)); } TEST(GAP_AdvertisingDataTest, CompressServiceUUIDs) { AdvertisingData data; - data.AddServiceUuid(common::UUID(kId1As16)); - data.AddServiceUuid(common::UUID(kId2As16)); + data.AddServiceUuid(UUID(kId1As16)); + data.AddServiceUuid(UUID(kId2As16)); EXPECT_EQ(1 + 1 + (sizeof(uint16_t) * 2), data.CalculateBlockSize()); - auto bytes = - common::CreateStaticByteBuffer(0x05, 0x02, 0x12, 0x02, 0x22, 0x11); + auto bytes = CreateStaticByteBuffer(0x05, 0x02, 0x12, 0x02, 0x22, 0x11); size_t block_size = data.CalculateBlockSize(); EXPECT_EQ(bytes.size(), block_size); - common::DynamicByteBuffer block(block_size); + DynamicByteBuffer block(block_size); data.WriteBlock(&block); EXPECT_TRUE(ContainersEqual(bytes, block)); } TEST(GAP_AdvertisingDataTest, ParseBlock) { - auto bytes = common::CreateStaticByteBuffer( + auto bytes = CreateStaticByteBuffer( // Complete 16-bit UUIDs 0x05, 0x03, 0x12, 0x02, 0x22, 0x11, // Incomplete list of 32-bit UUIDs @@ -129,7 +127,7 @@ TEST(GAP_AdvertisingDataTest, ParseFIDL) { ASSERT_EQ(2u, data.service_uuids().size()); EXPECT_EQ("Test💖", *(data.local_name())); - common::UUID uuid1(kId1As16); + UUID uuid1(kId1As16); EXPECT_EQ(1u, data.service_data_uuids().size()); EXPECT_EQ(4u, data.service_data(uuid1).size()); @@ -159,7 +157,7 @@ TEST(GAP_AdvertisingDataTest, ParseFIDLFailsWithMalformedServiceDataUuid) { } TEST(GAP_AdvertisingDataTest, ManufacturerZeroLength) { - auto bytes = common::CreateStaticByteBuffer( + auto bytes = CreateStaticByteBuffer( // Complete 16-bit UUIDs 0x05, 0x03, 0x12, 0x02, 0x22, 0x11, // Manufacturer Data with no data @@ -178,7 +176,7 @@ TEST(GAP_AdvertisingDataTest, ManufacturerZeroLength) { TEST(GAP_AdvertisingDataTest, ServiceData) { // A typical Eddystone-URL beacon advertisement // to "https://fuchsia.cl" - auto bytes = common::CreateStaticByteBuffer( + auto bytes = CreateStaticByteBuffer( // Complete 16-bit UUIDs, 0xFEAA 0x03, 0x03, 0xAA, 0xFE, // Eddystone Service (0xFEAA) Data: @@ -189,7 +187,7 @@ TEST(GAP_AdvertisingDataTest, ServiceData) { 'f', 'u', 'c', 'h', 's', 'i', 'a', '.', 'c', 'l'); AdvertisingData data; - common::UUID eddystone((uint16_t)0xFEAA); + UUID eddystone((uint16_t)0xFEAA); EXPECT_EQ(0u, data.service_data_uuids().size()); @@ -204,8 +202,8 @@ TEST(GAP_AdvertisingDataTest, ServiceData) { TEST(GAP_AdvertisingDataTest, Equality) { AdvertisingData one, two; - common::UUID gatt(kGattUuid); - common::UUID eddy(kEddystoneUuid); + UUID gatt(kGattUuid); + UUID eddy(kEddystoneUuid); // Service UUIDs EXPECT_EQ(two, one); @@ -215,8 +213,8 @@ TEST(GAP_AdvertisingDataTest, Equality) { EXPECT_EQ(two, one); // Even when the bytes are the same but from different places - auto bytes = common::CreateStaticByteBuffer(0x01, 0x02, 0x03, 0x04); - auto same = common::CreateStaticByteBuffer(0x01, 0x02, 0x03, 0x04); + auto bytes = CreateStaticByteBuffer(0x01, 0x02, 0x03, 0x04); + auto same = CreateStaticByteBuffer(0x01, 0x02, 0x03, 0x04); two.SetManufacturerData(0x0123, bytes.view()); EXPECT_NE(two, one); one.SetManufacturerData(0x0123, same.view()); @@ -242,9 +240,9 @@ TEST(GAP_AdvertisingDataTest, Equality) { } TEST(GAP_AdvertisingDataTest, Copy) { - common::UUID gatt(kGattUuid); - common::UUID eddy(kEddystoneUuid); - common::StaticByteBuffer<kRandomDataSize> rand_data; + UUID gatt(kGattUuid); + UUID eddy(kEddystoneUuid); + StaticByteBuffer<kRandomDataSize> rand_data; rand_data.FillWithRandomBytes(); AdvertisingData source; @@ -263,16 +261,15 @@ TEST(GAP_AdvertisingDataTest, Copy) { source.SetLocalName("fuchsia"); EXPECT_FALSE(dest.local_name()); - auto bytes = common::CreateStaticByteBuffer(0x01, 0x02, 0x03); + auto bytes = CreateStaticByteBuffer(0x01, 0x02, 0x03); source.SetManufacturerData(0x0123, bytes.view()); - EXPECT_TRUE( - common::ContainersEqual(rand_data, dest.manufacturer_data(0x0123))); + EXPECT_TRUE(ContainersEqual(rand_data, dest.manufacturer_data(0x0123))); } TEST(GAP_AdvertisingDataTest, Move) { - common::UUID gatt(kGattUuid); - common::UUID eddy(kEddystoneUuid); - common::StaticByteBuffer<kRandomDataSize> rand_data; + UUID gatt(kGattUuid); + UUID eddy(kEddystoneUuid); + StaticByteBuffer<kRandomDataSize> rand_data; rand_data.FillWithRandomBytes(); AdvertisingData source; @@ -293,12 +290,11 @@ TEST(GAP_AdvertisingDataTest, Move) { dest.uris()); EXPECT_TRUE(ContainersEqual(rand_data, dest.manufacturer_data(0x0123))); - EXPECT_EQ(std::unordered_set<common::UUID>({gatt, eddy}), - dest.service_uuids()); + EXPECT_EQ(std::unordered_set<UUID>({gatt, eddy}), dest.service_uuids()); } TEST(GAP_AdvertisingDataTest, Uris) { - auto bytes = common::CreateStaticByteBuffer( + auto bytes = CreateStaticByteBuffer( // Uri: "https://abc.xyz" 0x0B, 0x24, 0x17, '/', '/', 'a', 'b', 'c', '.', 'x', 'y', 'z', // Uri: "flubs:abc" @@ -316,34 +312,34 @@ TEST(GAP_AdvertisingDataTest, Uris) { TEST(GAP_AdvertisingDataTest, ReaderMalformedData) { // TLV length exceeds the size of the payload - auto bytes0 = common::CreateStaticByteBuffer(0x01); + auto bytes0 = CreateStaticByteBuffer(0x01); AdvertisingDataReader reader(bytes0); EXPECT_FALSE(reader.is_valid()); EXPECT_FALSE(reader.HasMoreData()); - auto bytes = common::CreateStaticByteBuffer(0x05, 0x00, 0x00, 0x00, 0x00); + auto bytes = CreateStaticByteBuffer(0x05, 0x00, 0x00, 0x00, 0x00); reader = AdvertisingDataReader(bytes); EXPECT_FALSE(reader.is_valid()); EXPECT_FALSE(reader.HasMoreData()); // TLV length is 0. This is not considered malformed. Data should be valid but // should not return more data. - bytes = common::CreateStaticByteBuffer(0x00, 0x00, 0x00, 0x00, 0x00); + bytes = CreateStaticByteBuffer(0x00, 0x00, 0x00, 0x00, 0x00); reader = AdvertisingDataReader(bytes); EXPECT_TRUE(reader.is_valid()); EXPECT_FALSE(reader.HasMoreData()); // First field is valid, second field is not. DataType type; - common::BufferView data; - bytes = common::CreateStaticByteBuffer(0x02, 0x00, 0x00, 0x02, 0x00); + BufferView data; + bytes = CreateStaticByteBuffer(0x02, 0x00, 0x00, 0x02, 0x00); reader = AdvertisingDataReader(bytes); EXPECT_FALSE(reader.is_valid()); EXPECT_FALSE(reader.HasMoreData()); EXPECT_FALSE(reader.GetNextField(&type, &data)); // First field is valid, second field has length 0. - bytes = common::CreateStaticByteBuffer(0x02, 0x00, 0x00, 0x00, 0x00); + bytes = CreateStaticByteBuffer(0x02, 0x00, 0x00, 0x00, 0x00); reader = AdvertisingDataReader(bytes); EXPECT_TRUE(reader.is_valid()); EXPECT_TRUE(reader.HasMoreData()); @@ -353,25 +349,24 @@ TEST(GAP_AdvertisingDataTest, ReaderMalformedData) { } TEST(GAP_AdvertisingDataTest, ReaderParseFields) { - auto bytes = common::CreateStaticByteBuffer(0x02, 0x01, 0x00, 0x05, 0x09, 'T', - 'e', 's', 't'); + auto bytes = + CreateStaticByteBuffer(0x02, 0x01, 0x00, 0x05, 0x09, 'T', 'e', 's', 't'); AdvertisingDataReader reader(bytes); EXPECT_TRUE(reader.is_valid()); EXPECT_TRUE(reader.HasMoreData()); DataType type; - common::BufferView data; + BufferView data; EXPECT_TRUE(reader.GetNextField(&type, &data)); EXPECT_EQ(DataType::kFlags, type); EXPECT_EQ(1u, data.size()); - EXPECT_TRUE( - common::ContainersEqual(common::CreateStaticByteBuffer(0x00), data)); + EXPECT_TRUE(ContainersEqual(CreateStaticByteBuffer(0x00), data)); EXPECT_TRUE(reader.HasMoreData()); EXPECT_TRUE(reader.GetNextField(&type, &data)); EXPECT_EQ(DataType::kCompleteLocalName, type); EXPECT_EQ(4u, data.size()); - EXPECT_TRUE(common::ContainersEqual(std::string("Test"), data)); + EXPECT_TRUE(ContainersEqual(std::string("Test"), data)); EXPECT_FALSE(reader.HasMoreData()); EXPECT_FALSE(reader.GetNextField(&type, &data)); @@ -394,35 +389,35 @@ TEST(GAP_AdvertisingDataTest, WriteField) { // for each TLV field). constexpr char kBufferSize = StringSize(kValue0) + StringSize(kValue1) + StringSize(kValue2) + 6; - common::StaticByteBuffer<kBufferSize> buffer; + StaticByteBuffer<kBufferSize> buffer; AdvertisingDataWriter writer(&buffer); EXPECT_EQ(0u, writer.bytes_written()); // We write malformed values here for testing purposes. - EXPECT_TRUE(writer.WriteField(DataType::kFlags, common::BufferView(kValue0))); + EXPECT_TRUE(writer.WriteField(DataType::kFlags, BufferView(kValue0))); EXPECT_EQ(StringSize(kValue0) + 2, writer.bytes_written()); - EXPECT_TRUE(writer.WriteField(DataType::kShortenedLocalName, - common::BufferView(kValue1))); + EXPECT_TRUE( + writer.WriteField(DataType::kShortenedLocalName, BufferView(kValue1))); EXPECT_EQ(StringSize(kValue0) + 2 + StringSize(kValue1) + 2, writer.bytes_written()); // Trying to write kValue3 should fail because there isn't enough room left in // the buffer. - EXPECT_FALSE(writer.WriteField(DataType::kCompleteLocalName, - common::BufferView(kValue3))); + EXPECT_FALSE( + writer.WriteField(DataType::kCompleteLocalName, BufferView(kValue3))); // Writing kValue2 should fill up the buffer. - EXPECT_TRUE(writer.WriteField(DataType::kCompleteLocalName, - common::BufferView(kValue2))); - EXPECT_FALSE(writer.WriteField(DataType::kCompleteLocalName, - common::BufferView(kValue3))); + EXPECT_TRUE( + writer.WriteField(DataType::kCompleteLocalName, BufferView(kValue2))); + EXPECT_FALSE( + writer.WriteField(DataType::kCompleteLocalName, BufferView(kValue3))); EXPECT_EQ(buffer.size(), writer.bytes_written()); // Verify the contents. DataType type; - common::BufferView value; + BufferView value; AdvertisingDataReader reader(buffer); EXPECT_TRUE(reader.is_valid()); diff --git a/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager.cc b/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager.cc index 56c96f44f65c49659c33e633457d8d400f0beae3..42e1e17279db62dc1f8df5024a60777fe2eb7381 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager.cc @@ -16,8 +16,6 @@ namespace bt { namespace gap { -using common::DeviceAddress; -using common::HostError; using std::unique_ptr; using ConnectionState = Peer::ConnectionState; @@ -148,7 +146,7 @@ void BrEdrConnectionManager::SetConnectable(bool connectable, self->page_scan_interval_ = 0; self->page_scan_window_ = 0; } else if (status) { - cb(hci::Status(common::HostError::kFailed)); + cb(hci::Status(HostError::kFailed)); return; } cb(status); @@ -165,7 +163,7 @@ void BrEdrConnectionManager::SetConnectable(bool connectable, return; } if (!self) { - cb(hci::Status(common::HostError::kFailed)); + cb(hci::Status(HostError::kFailed)); return; } SetPageScanEnabled(true, self->hci_, self->dispatcher_, std::move(cb)); @@ -180,7 +178,7 @@ void BrEdrConnectionManager::SetPairingDelegate( PeerId BrEdrConnectionManager::GetPeerId(hci::ConnectionHandle handle) const { auto it = connections_.find(handle); if (it == connections_.end()) { - return common::kInvalidPeerId; + return kInvalidPeerId; } auto* peer = cache_->FindByAddress(it->second.link().peer_address()); @@ -204,7 +202,7 @@ bool BrEdrConnectionManager::OpenL2capChannel(PeerId peer_id, l2cap::PSM psm, } BrEdrConnectionManager::SearchId BrEdrConnectionManager::AddServiceSearch( - const common::UUID& uuid, std::unordered_set<sdp::AttributeId> attributes, + const UUID& uuid, std::unordered_set<sdp::AttributeId> attributes, BrEdrConnectionManager::SearchCallback callback) { return discoverer_.AddSearch(uuid, std::move(attributes), std::move(callback)); @@ -237,7 +235,7 @@ void BrEdrConnectionManager::WritePageScanSettings(uint16_t interval, if (!hci_cmd_runner_->IsReady()) { // TODO(jamuraa): could run the three "settings" commands in parallel and // remove the sequence runner. - cb(hci::Status(common::HostError::kInProgress)); + cb(hci::Status(HostError::kInProgress)); return; } @@ -538,8 +536,7 @@ void BrEdrConnectionManager::OnLinkKeyRequest(const hci::EventPacket& event) { ZX_DEBUG_ASSERT(event.event_code() == hci::kLinkKeyRequestEventCode); const auto& params = event.view().payload<hci::LinkKeyRequestParams>(); - common::DeviceAddress addr(common::DeviceAddress::Type::kBREDR, - params.bd_addr); + DeviceAddress addr(DeviceAddress::Type::kBREDR, params.bd_addr); auto* peer = cache_->FindByAddress(addr); if (!peer || !peer->bredr()->bonded()) { @@ -587,8 +584,7 @@ void BrEdrConnectionManager::OnLinkKeyNotification( const auto& params = event.view().payload<hci::LinkKeyNotificationEventParams>(); - common::DeviceAddress addr(common::DeviceAddress::Type::kBREDR, - params.bd_addr); + DeviceAddress addr(DeviceAddress::Type::kBREDR, params.bd_addr); bt_log(TRACE, "gap-bredr", "got link key (type %u) for address %s", params.key_type, addr.ToString().c_str()); @@ -624,7 +620,7 @@ void BrEdrConnectionManager::OnLinkKeyNotification( return; } - common::UInt128 key_value; + UInt128 key_value; std::copy(params.link_key, ¶ms.link_key[key_value.size()], key_value.begin()); sm::LTK key(sec_props, hci::LinkKey(key_value, 0, 0)); diff --git a/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager.h b/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager.h index 88ee1334c3f32fa12b3c12599a791301bf1b113c..fc7a9a55729aa28c297236883bb3c639a6a7da89 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager.h +++ b/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager.h @@ -54,7 +54,7 @@ class BrEdrConnection final { class BrEdrConnectionManager final { public: BrEdrConnectionManager(fxl::RefPtr<hci::Transport> hci, PeerCache* peer_cache, - common::DeviceAddress local_address, + DeviceAddress local_address, fbl::RefPtr<data::Domain> data_domain, bool use_interlaced_scan); ~BrEdrConnectionManager(); @@ -69,7 +69,7 @@ class BrEdrConnectionManager final { void SetPairingDelegate(fxl::WeakPtr<PairingDelegate> delegate); // Retrieves the peer id that is connected to the connection |handle|. - // Returns common::kInvalidPeerId if no such peer exists. + // Returns kInvalidPeerId if no such peer exists. PeerId GetPeerId(hci::ConnectionHandle handle) const; // Opens a new L2CAP channel to service |psm| on |peer_id|. Returns false if @@ -89,7 +89,7 @@ class BrEdrConnectionManager final { // TODO(BT-785): Make identifcal searches just search once using SearchCallback = sdp::ServiceDiscoverer::ResultCallback; using SearchId = sdp::ServiceDiscoverer::SearchId; - SearchId AddServiceSearch(const common::UUID& uuid, + SearchId AddServiceSearch(const UUID& uuid, std::unordered_set<sdp::AttributeId> attributes, SearchCallback callback); @@ -109,14 +109,14 @@ class BrEdrConnectionManager final { [[nodiscard]] bool Connect(PeerId peer_id, ConnectResultCallback callback); // Intialize a GAP-level ACL connection from the hci connection_handle - void InitializeConnection(common::DeviceAddress addr, + void InitializeConnection(DeviceAddress addr, hci::ConnectionHandle connection_handle); // Called when an outgoing connection fails to establish - void OnConnectFailure(hci::Status status, common::PeerId peer_id); + void OnConnectFailure(hci::Status status, PeerId peer_id); // Called to cancel an outgoing connection request - void SendCreateConnectionCancelCommand(common::DeviceAddress addr); + void SendCreateConnectionCancelCommand(DeviceAddress addr); // Disconnects any existing BR/EDR connection to |peer_id|. Returns false if // |peer_id| is not a recognized BR/EDR peer or the corresponding peer is @@ -156,7 +156,7 @@ class BrEdrConnectionManager final { void EstablishConnection(Peer* peer, hci::Status status, std::unique_ptr<hci::Connection> conn_ptr); - Peer* FindOrInitPeer(common::DeviceAddress addr); + Peer* FindOrInitPeer(DeviceAddress addr); // Called when we complete a pending request. Initiates a new connection // attempt for the next peer in the pending list, if any. @@ -183,7 +183,7 @@ class BrEdrConnectionManager final { // This object must outlive this instance. PeerCache* cache_; - const common::DeviceAddress local_address_; + const DeviceAddress local_address_; fbl::RefPtr<data::Domain> data_domain_; diff --git a/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager_unittest.cc index a204071705fe3f2dcc522aaef426f59b3aae2949..6f96adeeb1bb2bfd6cb4642550a1daed6e97f533 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager_unittest.cc @@ -21,12 +21,6 @@ namespace { using bt::testing::CommandTransaction; -using common::DeviceAddress; -using common::DynamicByteBuffer; -using common::kInvalidPeerId; -using common::LowerBits; -using common::UpperBits; - using TestingBase = bt::testing::FakeControllerTest<bt::testing::TestController>; @@ -44,13 +38,13 @@ const DeviceAddress kTestDevAddr2(DeviceAddress::Type::kBREDR, // clang-format off -const auto kReadScanEnable = common::CreateStaticByteBuffer( +const auto kReadScanEnable = CreateStaticByteBuffer( LowerBits(hci::kReadScanEnable), UpperBits(hci::kReadScanEnable), 0x00 // No parameters ); #define READ_SCAN_ENABLE_RSP(scan_enable) \ - common::CreateStaticByteBuffer(hci::kCommandCompleteEventCode, 0x05, 0xF0, \ + CreateStaticByteBuffer(hci::kCommandCompleteEventCode, 0x05, 0xF0, \ LowerBits(hci::kReadScanEnable), \ UpperBits(hci::kReadScanEnable), \ hci::kSuccess, (scan_enable)) @@ -63,7 +57,7 @@ const auto kReadScanEnableRspBoth = READ_SCAN_ENABLE_RSP(0x03); #undef READ_SCAN_ENABLE_RSP #define WRITE_SCAN_ENABLE_CMD(scan_enable) \ - common::CreateStaticByteBuffer(LowerBits(hci::kWriteScanEnable), \ + CreateStaticByteBuffer(LowerBits(hci::kWriteScanEnable), \ UpperBits(hci::kWriteScanEnable), 0x01, \ (scan_enable)) @@ -75,13 +69,13 @@ const auto kWriteScanEnableBoth = WRITE_SCAN_ENABLE_CMD(0x03); #undef WRITE_SCAN_ENABLE_CMD #define COMMAND_COMPLETE_RSP(opcode) \ - common::CreateStaticByteBuffer(hci::kCommandCompleteEventCode, 0x04, 0xF0, \ + CreateStaticByteBuffer(hci::kCommandCompleteEventCode, 0x04, 0xF0, \ LowerBits((opcode)), UpperBits((opcode)), \ hci::kSuccess); const auto kWriteScanEnableRsp = COMMAND_COMPLETE_RSP(hci::kWriteScanEnable); -const auto kWritePageScanActivity = common::CreateStaticByteBuffer( +const auto kWritePageScanActivity = CreateStaticByteBuffer( LowerBits(hci::kWritePageScanActivity), UpperBits(hci::kWritePageScanActivity), 0x04, // parameter_total_size (4 bytes) @@ -92,7 +86,7 @@ const auto kWritePageScanActivity = common::CreateStaticByteBuffer( const auto kWritePageScanActivityRsp = COMMAND_COMPLETE_RSP(hci::kWritePageScanActivity); -const auto kWritePageScanType = common::CreateStaticByteBuffer( +const auto kWritePageScanType = CreateStaticByteBuffer( LowerBits(hci::kWritePageScanType), UpperBits(hci::kWritePageScanType), 0x01, // parameter_total_size (1 byte) 0x01 // Interlaced scan @@ -103,40 +97,40 @@ const auto kWritePageScanTypeRsp = #define COMMAND_STATUS_RSP(opcode, statuscode) \ - common::CreateStaticByteBuffer(hci::kCommandStatusEventCode, 0x04, \ + CreateStaticByteBuffer(hci::kCommandStatusEventCode, 0x04, \ (statuscode), 0xF0, \ LowerBits((opcode)), UpperBits((opcode))); // clang-format on -const auto kConnectionRequest = common::CreateStaticByteBuffer( - hci::kConnectionRequestEventCode, - 0x0A, // parameter_total_size (10 byte payload) - TEST_DEV_ADDR_BYTES_LE, // peer address - 0x00, 0x1F, 0x00, // class_of_device (unspecified) - 0x01 // link_type (ACL) -); +const auto kConnectionRequest = + CreateStaticByteBuffer(hci::kConnectionRequestEventCode, + 0x0A, // parameter_total_size (10 byte payload) + TEST_DEV_ADDR_BYTES_LE, // peer address + 0x00, 0x1F, 0x00, // class_of_device (unspecified) + 0x01 // link_type (ACL) + ); const auto kAcceptConnectionRequest = - common::CreateStaticByteBuffer(LowerBits(hci::kAcceptConnectionRequest), - UpperBits(hci::kAcceptConnectionRequest), - 0x07, // parameter_total_size (7 bytes) - TEST_DEV_ADDR_BYTES_LE, // peer address - 0x00 // role (become master) + CreateStaticByteBuffer(LowerBits(hci::kAcceptConnectionRequest), + UpperBits(hci::kAcceptConnectionRequest), + 0x07, // parameter_total_size (7 bytes) + TEST_DEV_ADDR_BYTES_LE, // peer address + 0x00 // role (become master) ); const auto kAcceptConnectionRequestRsp = COMMAND_STATUS_RSP( hci::kAcceptConnectionRequest, hci::StatusCode::kSuccess); -const auto kConnectionComplete = common::CreateStaticByteBuffer( - hci::kConnectionCompleteEventCode, - 0x0B, // parameter_total_size (11 byte payload) - hci::StatusCode::kSuccess, // status - 0xAA, 0x0B, // connection_handle - TEST_DEV_ADDR_BYTES_LE, // peer address - 0x01, // link_type (ACL) - 0x00 // encryption not enabled -); +const auto kConnectionComplete = + CreateStaticByteBuffer(hci::kConnectionCompleteEventCode, + 0x0B, // parameter_total_size (11 byte payload) + hci::StatusCode::kSuccess, // status + 0xAA, 0x0B, // connection_handle + TEST_DEV_ADDR_BYTES_LE, // peer address + 0x01, // link_type (ACL) + 0x00 // encryption not enabled + ); -const auto kConnectionCompleteError = common::CreateStaticByteBuffer( +const auto kConnectionCompleteError = CreateStaticByteBuffer( hci::kConnectionCompleteEventCode, 0x0B, // parameter_total_size (11 byte payload) hci::StatusCode::kConnectionFailedToBeEstablished, // status @@ -146,17 +140,17 @@ const auto kConnectionCompleteError = common::CreateStaticByteBuffer( 0x00 // encryption not enabled ); -const auto kConnectionCompleteCanceled = common::CreateStaticByteBuffer( - hci::kConnectionCompleteEventCode, - 0x0B, // parameter_total_size (11 byte payload) - hci::StatusCode::kUnknownConnectionId, // status - 0x00, 0x00, // connection_handle - TEST_DEV_ADDR_BYTES_LE, // peer address - 0x01, // link_type (ACL) - 0x00 // encryption not enabled -); +const auto kConnectionCompleteCanceled = + CreateStaticByteBuffer(hci::kConnectionCompleteEventCode, + 0x0B, // parameter_total_size (11 byte payload) + hci::StatusCode::kUnknownConnectionId, // status + 0x00, 0x00, // connection_handle + TEST_DEV_ADDR_BYTES_LE, // peer address + 0x01, // link_type (ACL) + 0x00 // encryption not enabled + ); -const auto kCreateConnection = common::CreateStaticByteBuffer( +const auto kCreateConnection = CreateStaticByteBuffer( LowerBits(hci::kCreateConnection), UpperBits(hci::kCreateConnection), 0x0d, // parameter_total_size (13 bytes) TEST_DEV_ADDR_BYTES_LE, // peer address @@ -175,16 +169,16 @@ const auto kCreateConnectionRspError = COMMAND_STATUS_RSP( hci::kCreateConnection, hci::StatusCode::kConnectionFailedToBeEstablished); const auto kCreateConnectionCancel = - common::CreateStaticByteBuffer(LowerBits(hci::kCreateConnectionCancel), - UpperBits(hci::kCreateConnectionCancel), - 0x06, // parameter_total_size (6 bytes) - TEST_DEV_ADDR_BYTES_LE // peer address + CreateStaticByteBuffer(LowerBits(hci::kCreateConnectionCancel), + UpperBits(hci::kCreateConnectionCancel), + 0x06, // parameter_total_size (6 bytes) + TEST_DEV_ADDR_BYTES_LE // peer address ); const auto kCreateConnectionCancelRsp = COMMAND_COMPLETE_RSP(hci::kCreateConnectionCancel); -const auto kRemoteNameRequest = common::CreateStaticByteBuffer( +const auto kRemoteNameRequest = CreateStaticByteBuffer( LowerBits(hci::kRemoteNameRequest), UpperBits(hci::kRemoteNameRequest), 0x0a, // parameter_total_size (10 bytes) TEST_DEV_ADDR_BYTES_LE, // peer address @@ -195,7 +189,7 @@ const auto kRemoteNameRequest = common::CreateStaticByteBuffer( const auto kRemoteNameRequestRsp = COMMAND_STATUS_RSP(hci::kRemoteNameRequest, hci::StatusCode::kSuccess); -const auto kRemoteNameRequestComplete = common::CreateStaticByteBuffer( +const auto kRemoteNameRequestComplete = CreateStaticByteBuffer( hci::kRemoteNameRequestCompleteEventCode, 0x20, // parameter_total_size (32) hci::StatusCode::kSuccess, // status @@ -206,59 +200,58 @@ const auto kRemoteNameRequestComplete = common::CreateStaticByteBuffer( // Everything after the 0x00 should be ignored. ); const auto kReadRemoteVersionInfo = - common::CreateStaticByteBuffer(LowerBits(hci::kReadRemoteVersionInfo), - UpperBits(hci::kReadRemoteVersionInfo), - 0x02, // Parameter_total_size (2 bytes) - 0xAA, 0x0B // connection_handle + CreateStaticByteBuffer(LowerBits(hci::kReadRemoteVersionInfo), + UpperBits(hci::kReadRemoteVersionInfo), + 0x02, // Parameter_total_size (2 bytes) + 0xAA, 0x0B // connection_handle ); const auto kReadRemoteVersionInfoRsp = COMMAND_STATUS_RSP(hci::kReadRemoteVersionInfo, hci::StatusCode::kSuccess); const auto kRemoteVersionInfoComplete = - common::CreateStaticByteBuffer(hci::kReadRemoteVersionInfoCompleteEventCode, - 0x08, // parameter_total_size (8 bytes) - hci::StatusCode::kSuccess, // status - 0xAA, 0x0B, // connection_handle - hci::HCIVersion::k4_2, // lmp_version - 0xE0, 0x00, // manufacturer_name (Google) - 0xAD, 0xDE // lmp_subversion (anything) + CreateStaticByteBuffer(hci::kReadRemoteVersionInfoCompleteEventCode, + 0x08, // parameter_total_size (8 bytes) + hci::StatusCode::kSuccess, // status + 0xAA, 0x0B, // connection_handle + hci::HCIVersion::k4_2, // lmp_version + 0xE0, 0x00, // manufacturer_name (Google) + 0xAD, 0xDE // lmp_subversion (anything) ); const auto kReadRemoteSupportedFeatures = - common::CreateStaticByteBuffer(LowerBits(hci::kReadRemoteSupportedFeatures), - UpperBits(hci::kReadRemoteSupportedFeatures), - 0x02, // parameter_total_size (2 bytes) - 0xAA, 0x0B // connection_handle + CreateStaticByteBuffer(LowerBits(hci::kReadRemoteSupportedFeatures), + UpperBits(hci::kReadRemoteSupportedFeatures), + 0x02, // parameter_total_size (2 bytes) + 0xAA, 0x0B // connection_handle ); const auto kReadRemoteSupportedFeaturesRsp = COMMAND_STATUS_RSP( hci::kReadRemoteSupportedFeatures, hci::StatusCode::kSuccess); -const auto kReadRemoteSupportedFeaturesComplete = - common::CreateStaticByteBuffer( - hci::kReadRemoteSupportedFeaturesCompleteEventCode, - 0x0B, // parameter_total_size (11 bytes) - hci::StatusCode::kSuccess, // status - 0xAA, 0x0B, // connection_handle, - 0xFF, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x80 - // lmp_features - // Set: 3 slot packets, 5 slot packets, Encryption, Timing Accuracy, - // Role Switch, Hold Mode, Sniff Mode, LE Supported, Extended Features - ); +const auto kReadRemoteSupportedFeaturesComplete = CreateStaticByteBuffer( + hci::kReadRemoteSupportedFeaturesCompleteEventCode, + 0x0B, // parameter_total_size (11 bytes) + hci::StatusCode::kSuccess, // status + 0xAA, 0x0B, // connection_handle, + 0xFF, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x80 + // lmp_features + // Set: 3 slot packets, 5 slot packets, Encryption, Timing Accuracy, + // Role Switch, Hold Mode, Sniff Mode, LE Supported, Extended Features +); const auto kReadRemoteExtended1 = - common::CreateStaticByteBuffer(LowerBits(hci::kReadRemoteExtendedFeatures), - UpperBits(hci::kReadRemoteExtendedFeatures), - 0x03, // parameter_total_size (3 bytes) - 0xAA, 0x0B, // connection_handle - 0x01 // page_number (1) + CreateStaticByteBuffer(LowerBits(hci::kReadRemoteExtendedFeatures), + UpperBits(hci::kReadRemoteExtendedFeatures), + 0x03, // parameter_total_size (3 bytes) + 0xAA, 0x0B, // connection_handle + 0x01 // page_number (1) ); const auto kReadRemoteExtendedFeaturesRsp = COMMAND_STATUS_RSP( hci::kReadRemoteExtendedFeatures, hci::StatusCode::kSuccess); -const auto kReadRemoteExtended1Complete = common::CreateStaticByteBuffer( +const auto kReadRemoteExtended1Complete = CreateStaticByteBuffer( hci::kReadRemoteExtendedFeaturesCompleteEventCode, 0x0D, // parameter_total_size (13 bytes) hci::StatusCode::kSuccess, // status @@ -272,25 +265,25 @@ const auto kReadRemoteExtended1Complete = common::CreateStaticByteBuffer( ); const auto kReadRemoteExtended2 = - common::CreateStaticByteBuffer(LowerBits(hci::kReadRemoteExtendedFeatures), - UpperBits(hci::kReadRemoteExtendedFeatures), - 0x03, // parameter_total_size (3 bytes) - 0xAA, 0x0B, // connection_handle - 0x02 // page_number (2) + CreateStaticByteBuffer(LowerBits(hci::kReadRemoteExtendedFeatures), + UpperBits(hci::kReadRemoteExtendedFeatures), + 0x03, // parameter_total_size (3 bytes) + 0xAA, 0x0B, // connection_handle + 0x02 // page_number (2) ); -const auto kReadRemoteExtended2Complete = common::CreateStaticByteBuffer( - hci::kReadRemoteExtendedFeaturesCompleteEventCode, - 0x0D, // parameter_total_size (13 bytes) - hci::StatusCode::kSuccess, // status - 0xAA, 0x0B, // connection_handle, - 0x02, // page_number - 0x03, // max_page_number (3 pages) - 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0xFF, 0x00 - // lmp_features - All the bits should be ignored. -); +const auto kReadRemoteExtended2Complete = + CreateStaticByteBuffer(hci::kReadRemoteExtendedFeaturesCompleteEventCode, + 0x0D, // parameter_total_size (13 bytes) + hci::StatusCode::kSuccess, // status + 0xAA, 0x0B, // connection_handle, + 0x02, // page_number + 0x03, // max_page_number (3 pages) + 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0xFF, 0x00 + // lmp_features - All the bits should be ignored. + ); -const auto kDisconnect = common::CreateStaticByteBuffer( +const auto kDisconnect = CreateStaticByteBuffer( LowerBits(hci::kDisconnect), UpperBits(hci::kDisconnect), 0x03, // parameter_total_size (3 bytes) 0xAA, 0x0B, // connection_handle @@ -300,13 +293,13 @@ const auto kDisconnect = common::CreateStaticByteBuffer( const auto kDisconnectRsp = COMMAND_STATUS_RSP(hci::kDisconnect, hci::StatusCode::kSuccess); -const auto kDisconnectionComplete = common::CreateStaticByteBuffer( - hci::kDisconnectionCompleteEventCode, - 0x04, // parameter_total_size (4 bytes) - hci::StatusCode::kSuccess, // status - 0xAA, 0x0B, // connection_handle - 0x13 // Reason (Remote User Terminated Connection) -); +const auto kDisconnectionComplete = + CreateStaticByteBuffer(hci::kDisconnectionCompleteEventCode, + 0x04, // parameter_total_size (4 bytes) + hci::StatusCode::kSuccess, // status + 0xAA, 0x0B, // connection_handle + 0x13 // Reason (Remote User Terminated Connection) + ); class BrEdrConnectionManagerTest : public TestingBase { public: @@ -637,14 +630,14 @@ TEST_F(GAP_BrEdrConnectionManagerTest, RemoteDisconnect) { } const auto kRemoteNameRequestCompleteFailed = - common::CreateStaticByteBuffer(hci::kRemoteNameRequestCompleteEventCode, - 0x01, // parameter_total_size (1 bytes) - hci::StatusCode::kHardwareFailure); + CreateStaticByteBuffer(hci::kRemoteNameRequestCompleteEventCode, + 0x01, // parameter_total_size (1 bytes) + hci::StatusCode::kHardwareFailure); const auto kReadRemoteSupportedFeaturesCompleteFailed = - common::CreateStaticByteBuffer(hci::kRemoteNameRequestCompleteEventCode, - 0x01, // parameter_total_size (1 bytes) - hci::StatusCode::kHardwareFailure); + CreateStaticByteBuffer(hci::kRemoteNameRequestCompleteEventCode, + 0x01, // parameter_total_size (1 bytes) + hci::StatusCode::kHardwareFailure); // Test: if the interrogation fails, we disconnect. // - Receiving extra responses after a command fails will not fail @@ -675,12 +668,12 @@ TEST_F(GAP_BrEdrConnectionManagerTest, IncommingConnectionFailedInterrogation) { } const auto kCapabilitiesRequest = - common::CreateStaticByteBuffer(hci::kIOCapabilityRequestEventCode, - 0x06, // parameter_total_size (6 bytes) - TEST_DEV_ADDR_BYTES_LE // address + CreateStaticByteBuffer(hci::kIOCapabilityRequestEventCode, + 0x06, // parameter_total_size (6 bytes) + TEST_DEV_ADDR_BYTES_LE // address ); -const auto kCapabilitiesRequestReply = common::CreateStaticByteBuffer( +const auto kCapabilitiesRequestReply = CreateStaticByteBuffer( LowerBits(hci::kIOCapabilityRequestReply), UpperBits(hci::kIOCapabilityRequestReply), 0x09, // parameter_total_size (9 bytes) @@ -691,11 +684,11 @@ const auto kCapabilitiesRequestReply = common::CreateStaticByteBuffer( ); const auto kCapabilitiesRequestReplyRsp = - common::CreateStaticByteBuffer(hci::kCommandCompleteEventCode, 0x0A, 0xF0, - LowerBits(hci::kIOCapabilityRequestReply), - UpperBits(hci::kIOCapabilityRequestReply), - hci::kSuccess, // status - TEST_DEV_ADDR_BYTES_LE // peer address + CreateStaticByteBuffer(hci::kCommandCompleteEventCode, 0x0A, 0xF0, + LowerBits(hci::kIOCapabilityRequestReply), + UpperBits(hci::kIOCapabilityRequestReply), + hci::kSuccess, // status + TEST_DEV_ADDR_BYTES_LE // peer address ); // Test: sends replies to Capability Requests @@ -712,19 +705,19 @@ TEST_F(GAP_BrEdrConnectionManagerTest, CapabilityRequest) { EXPECT_EQ(1, transaction_count()); } -const auto kUserConfirmationRequest = common::CreateStaticByteBuffer( - hci::kUserConfirmationRequestEventCode, - 0x0A, // parameter_total_size (10 byte payload) - TEST_DEV_ADDR_BYTES_LE, // peer address - 0x00, 0x00, 0x00, 0x00 // numeric value 000000 -); +const auto kUserConfirmationRequest = + CreateStaticByteBuffer(hci::kUserConfirmationRequestEventCode, + 0x0A, // parameter_total_size (10 byte payload) + TEST_DEV_ADDR_BYTES_LE, // peer address + 0x00, 0x00, 0x00, 0x00 // numeric value 000000 + ); -const auto kConfirmationRequestReply = common::CreateStaticByteBuffer( - LowerBits(hci::kUserConfirmationRequestReply), - UpperBits(hci::kUserConfirmationRequestReply), - 0x06, // parameter_total_size (6 bytes) - TEST_DEV_ADDR_BYTES_LE // peer address -); +const auto kConfirmationRequestReply = + CreateStaticByteBuffer(LowerBits(hci::kUserConfirmationRequestReply), + UpperBits(hci::kUserConfirmationRequestReply), + 0x06, // parameter_total_size (6 bytes) + TEST_DEV_ADDR_BYTES_LE // peer address + ); const auto kConfirmationRequestReplyRsp = COMMAND_COMPLETE_RSP(hci::kUserConfirmationRequestReply); @@ -742,24 +735,24 @@ TEST_F(GAP_BrEdrConnectionManagerTest, ConfirmationRequest) { } const auto kLinkKeyRequest = - common::CreateStaticByteBuffer(hci::kLinkKeyRequestEventCode, - 0x06, // parameter_total_size (6 bytes) - TEST_DEV_ADDR_BYTES_LE // peer address + CreateStaticByteBuffer(hci::kLinkKeyRequestEventCode, + 0x06, // parameter_total_size (6 bytes) + TEST_DEV_ADDR_BYTES_LE // peer address ); const auto kLinkKeyRequestNegativeReply = - common::CreateStaticByteBuffer(LowerBits(hci::kLinkKeyRequestNegativeReply), - UpperBits(hci::kLinkKeyRequestNegativeReply), - 0x06, // parameter_total_size (6 bytes) - TEST_DEV_ADDR_BYTES_LE // peer address + CreateStaticByteBuffer(LowerBits(hci::kLinkKeyRequestNegativeReply), + UpperBits(hci::kLinkKeyRequestNegativeReply), + 0x06, // parameter_total_size (6 bytes) + TEST_DEV_ADDR_BYTES_LE // peer address ); const auto kLinkKeyRequestNegativeReplyRsp = - common::CreateStaticByteBuffer(hci::kCommandCompleteEventCode, 0x0A, 0xF0, - LowerBits(hci::kLinkKeyRequestNegativeReply), - UpperBits(hci::kLinkKeyRequestNegativeReply), - hci::kSuccess, // status - TEST_DEV_ADDR_BYTES_LE // peer address + CreateStaticByteBuffer(hci::kCommandCompleteEventCode, 0x0A, 0xF0, + LowerBits(hci::kLinkKeyRequestNegativeReply), + UpperBits(hci::kLinkKeyRequestNegativeReply), + hci::kSuccess, // status + TEST_DEV_ADDR_BYTES_LE // peer address ); // Test: replies negative to Link Key Requests for unknown and unbonded peers @@ -805,7 +798,7 @@ const sm::LTK kLinkKey( sm::SecurityProperties(hci::LinkKeyType::kAuthenticatedCombination192), kRawKey); -const auto kLinkKeyNotification = common::CreateStaticByteBuffer( +const auto kLinkKeyNotification = CreateStaticByteBuffer( hci::kLinkKeyNotificationEventCode, 0x17, // parameter_total_size (17 bytes) TEST_DEV_ADDR_BYTES_LE, // peer address @@ -814,7 +807,7 @@ const auto kLinkKeyNotification = common::CreateStaticByteBuffer( 0x04 // key type (Unauthenticated Combination Key generated from P-192) ); -const auto kLinkKeyRequestReply = common::CreateStaticByteBuffer( +const auto kLinkKeyRequestReply = CreateStaticByteBuffer( LowerBits(hci::kLinkKeyRequestReply), UpperBits(hci::kLinkKeyRequestReply), 0x16, // parameter_total_size (22 bytes) TEST_DEV_ADDR_BYTES_LE, // peer address @@ -822,7 +815,7 @@ const auto kLinkKeyRequestReply = common::CreateStaticByteBuffer( 0xca, 0x1e, 0xca, 0xfe // link key ); -const auto kLinkKeyRequestReplyRsp = common::CreateStaticByteBuffer( +const auto kLinkKeyRequestReplyRsp = CreateStaticByteBuffer( hci::kCommandCompleteEventCode, 0x0A, 0xF0, LowerBits(hci::kLinkKeyRequestReply), UpperBits(hci::kLinkKeyRequestReply), hci::kSuccess, // status @@ -859,7 +852,7 @@ TEST_F(GAP_BrEdrConnectionManagerTest, RecallLinkKeyForBondedPeer) { QueueDisconnection(kConnectionHandle); } -const auto kLinkKeyNotificationChanged = common::CreateStaticByteBuffer( +const auto kLinkKeyNotificationChanged = CreateStaticByteBuffer( hci::kLinkKeyNotificationEventCode, 0x17, // parameter_total_size (17 bytes) TEST_DEV_ADDR_BYTES_LE, // peer address @@ -868,7 +861,7 @@ const auto kLinkKeyNotificationChanged = common::CreateStaticByteBuffer( 0x06 // key type (Changed Combination Key) ); -const auto kLinkKeyRequestReplyChanged = common::CreateStaticByteBuffer( +const auto kLinkKeyRequestReplyChanged = CreateStaticByteBuffer( LowerBits(hci::kLinkKeyRequestReply), UpperBits(hci::kLinkKeyRequestReply), 0x16, // parameter_total_size (22 bytes) TEST_DEV_ADDR_BYTES_LE, // peer address @@ -958,7 +951,7 @@ TEST_F(GAP_BrEdrConnectionManagerTest, UnbondedPeerChangeLinkKey) { QueueDisconnection(kConnectionHandle); } -const auto kLinkKeyNotificationLegacy = common::CreateStaticByteBuffer( +const auto kLinkKeyNotificationLegacy = CreateStaticByteBuffer( hci::kLinkKeyNotificationEventCode, 0x17, // parameter_total_size (17 bytes) TEST_DEV_ADDR_BYTES_LE, // peer address @@ -1079,7 +1072,7 @@ TEST_F(GAP_BrEdrConnectionManagerTest, ServiceSearch) { [&sdp_chan, &sdp_request_tid](auto new_chan) { new_chan->SetSendCallback( [&sdp_request_tid](auto packet) { - const auto kSearchExpectedParams = common::CreateStaticByteBuffer( + const auto kSearchExpectedParams = CreateStaticByteBuffer( // ServiceSearchPattern 0x35, 0x03, // Sequence uint8 3 bytes 0x19, 0x11, 0x0B, // UUID (kAudioSink) @@ -1112,9 +1105,9 @@ TEST_F(GAP_BrEdrConnectionManagerTest, ServiceSearch) { ASSERT_EQ(0u, search_cb_count); sdp::ServiceSearchAttributeResponse rsp; - rsp.SetAttribute(0, sdp::kServiceId, sdp::DataElement(common::UUID())); + rsp.SetAttribute(0, sdp::kServiceId, sdp::DataElement(UUID())); auto rsp_ptr = rsp.GetPDU(0xFFFF /* max attribute bytes */, *sdp_request_tid, - common::BufferView()); + BufferView()); sdp_chan->Receive(*rsp_ptr); @@ -1212,7 +1205,7 @@ TEST_F(GAP_BrEdrConnectionManagerTest, AddServiceSearchAll) { [&sdp_chan, &sdp_request_tid](auto new_chan) { new_chan->SetSendCallback( [&sdp_request_tid](auto packet) { - const auto kSearchExpectedParams = common::CreateStaticByteBuffer( + const auto kSearchExpectedParams = CreateStaticByteBuffer( // ServiceSearchPattern 0x35, 0x03, // Sequence uint8 3 bytes 0x19, 0x11, 0x0B, // UUID (kAudioSink) @@ -1245,9 +1238,9 @@ TEST_F(GAP_BrEdrConnectionManagerTest, AddServiceSearchAll) { ASSERT_EQ(0u, search_cb_count); sdp::ServiceSearchAttributeResponse rsp; - rsp.SetAttribute(0, sdp::kServiceId, sdp::DataElement(common::UUID())); + rsp.SetAttribute(0, sdp::kServiceId, sdp::DataElement(UUID())); auto rsp_ptr = rsp.GetPDU(0xFFFF /* max attribute bytes */, *sdp_request_tid, - common::BufferView()); + BufferView()); sdp_chan->Receive(*rsp_ptr); @@ -1359,7 +1352,7 @@ TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSinglePeerFailure) { test_device()->QueueCommandTransaction(CommandTransaction( kCreateConnection, {&kCreateConnectionRsp, &kConnectionCompleteError})); - hci::Status status(common::HostError::kFailed); + hci::Status status(HostError::kFailed); bool callback_run = false; auto callback = [&status, &callback_run](auto cb_status, auto conn_ref) { @@ -1402,7 +1395,7 @@ TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSinglePeerTimeout) { RunLoopFor(kBrEdrCreateConnectionTimeout); RunLoopFor(kBrEdrCreateConnectionTimeout); EXPECT_FALSE(status); - EXPECT_EQ(common::HostError::kTimedOut, status.error()) << status.ToString(); + EXPECT_EQ(HostError::kTimedOut, status.error()) << status.ToString(); EXPECT_TRUE(NotConnected(peer)); } @@ -1418,7 +1411,7 @@ TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSinglePeer) { QueueDisconnection(kConnectionHandle); // Initialize as error to verify that |callback| assigns success. - hci::Status status(common::HostError::kFailed); + hci::Status status(HostError::kFailed); BrEdrConnection* conn_ref; auto callback = [&status, &conn_ref](auto cb_status, auto cb_conn_ref) { EXPECT_TRUE(cb_conn_ref); @@ -1448,7 +1441,7 @@ TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSinglePeerAlreadyConnected) { QueueDisconnection(kConnectionHandle); // Initialize as error to verify that |callback| assigns success. - hci::Status status(common::HostError::kFailed); + hci::Status status(HostError::kFailed); int num_callbacks = 0; BrEdrConnection* conn_ref; auto callback = [&status, &conn_ref, &num_callbacks](auto cb_status, @@ -1493,7 +1486,7 @@ TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSinglePeerTwoInFlight) { QueueDisconnection(kConnectionHandle); // Initialize as error to verify that |callback| assigns success. - hci::Status status(common::HostError::kFailed); + hci::Status status(HostError::kFailed); int num_callbacks = 0; BrEdrConnection* conn_ref; auto callback = [&status, &conn_ref, &num_callbacks](auto cb_status, @@ -1547,7 +1540,7 @@ TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSecondPeerFirstTimesOut) { }; // Initialize as error to verify that |callback_b| assigns success. - hci::Status status_b(common::HostError::kFailed); + hci::Status status_b(HostError::kFailed); BrEdrConnection* connection; auto callback_b = [&status_b, &connection](auto cb_status, auto cb_conn_ref) { EXPECT_TRUE(cb_conn_ref); diff --git a/src/connectivity/bluetooth/core/bt-host/gap/bredr_discovery_manager.cc b/src/connectivity/bluetooth/core/bt-host/gap/bredr_discovery_manager.cc index 49a32e588f532c3a9c8b0c4c3b1ba4181cc239b3..996d4d12c697bc55b39d023fdb4a4f4a5bb4c7b4 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/bredr_discovery_manager.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/bredr_discovery_manager.cc @@ -33,8 +33,8 @@ std::unordered_set<Peer*> ProcessInquiryResult(PeerCache* cache, const auto& result = event.view().payload<EventParamType>(); for (int i = 0; i < result.num_responses; i++) { - common::DeviceAddress addr(common::DeviceAddress::Type::kBREDR, - result.responses[i].bd_addr); + DeviceAddress addr(DeviceAddress::Type::kBREDR, + result.responses[i].bd_addr); Peer* peer = cache->FindByAddress(addr); if (!peer) { peer = cache->NewPeer(addr, true); @@ -277,8 +277,7 @@ void BrEdrDiscoveryManager::ExtendedInquiryResult( const auto& result = event.view().payload<hci::ExtendedInquiryResultEventParams>(); - common::DeviceAddress addr(common::DeviceAddress::Type::kBREDR, - result.bd_addr); + DeviceAddress addr(DeviceAddress::Type::kBREDR, result.bd_addr); Peer* peer = cache_->FindByAddress(addr); if (!peer) { peer = cache_->NewPeer(addr, true); diff --git a/src/connectivity/bluetooth/core/bt-host/gap/bredr_discovery_manager_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gap/bredr_discovery_manager_unittest.cc index 32e131603c2fcf37ece1752687b73a34b0461d8f..ab689200a2050aa8b6d73e9efc2323ff209029b7 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/bredr_discovery_manager_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/bredr_discovery_manager_unittest.cc @@ -16,27 +16,22 @@ namespace { using bt::testing::CommandTransaction; -using common::DeviceAddress; -using common::DeviceAddressBytes; -using common::LowerBits; -using common::UpperBits; - using TestingBase = bt::testing::FakeControllerTest<bt::testing::TestController>; // clang-format off #define COMMAND_COMPLETE_RSP(opcode) \ - common::CreateStaticByteBuffer(hci::kCommandCompleteEventCode, 0x04, 0xF0, \ + CreateStaticByteBuffer(hci::kCommandCompleteEventCode, 0x04, 0xF0, \ LowerBits((opcode)), UpperBits((opcode)), \ hci::kSuccess) #define COMMAND_STATUS_RSP(opcode, statuscode) \ - common::CreateStaticByteBuffer(hci::kCommandStatusEventCode, 0x04, \ + CreateStaticByteBuffer(hci::kCommandStatusEventCode, 0x04, \ (statuscode), 0xF0, \ LowerBits((opcode)), UpperBits((opcode))) -const auto kWriteInquiryActivity = common::CreateStaticByteBuffer( +const auto kWriteInquiryActivity = CreateStaticByteBuffer( LowerBits(hci::kWriteInquiryScanActivity), UpperBits(hci::kWriteInquiryScanActivity), 0x04, // Param total size 0xE1, 0x01, // Inquiry Scan Interval @@ -45,7 +40,7 @@ const auto kWriteInquiryActivity = common::CreateStaticByteBuffer( const auto kWriteInquiryActivityRsp = COMMAND_COMPLETE_RSP(hci::kWriteInquiryScanActivity); -const auto kWriteInquiryType = common::CreateStaticByteBuffer( +const auto kWriteInquiryType = CreateStaticByteBuffer( LowerBits(hci::kWriteInquiryScanType), UpperBits(hci::kWriteInquiryScanType), 0x01, // Param total size 0x01 // Interlaced Inquiry Scan @@ -104,7 +99,7 @@ class BrEdrDiscoveryManagerTest : public TestingBase { using GAP_BrEdrDiscoveryManagerTest = BrEdrDiscoveryManagerTest; // clang-format off -const auto kInquiry = common::CreateStaticByteBuffer( +const auto kInquiry = CreateStaticByteBuffer( LowerBits(hci::kInquiry), UpperBits(hci::kInquiry), 0x05, // Paramreter total size 0x33, 0x8B, 0x9E, // GIAC @@ -116,13 +111,13 @@ const auto kInquiryRsp = COMMAND_STATUS_RSP(hci::kInquiry, hci::kSuccess); const auto kInquiryRspError = COMMAND_STATUS_RSP(hci::kInquiry, hci::kHardwareFailure); -const auto kInquiryComplete = common::CreateStaticByteBuffer( +const auto kInquiryComplete = CreateStaticByteBuffer( hci::kInquiryCompleteEventCode, 0x01, // parameter_total_size (1 bytes) hci::kSuccess ); -const auto kInquiryCompleteError = common::CreateStaticByteBuffer( +const auto kInquiryCompleteError = CreateStaticByteBuffer( hci::kInquiryCompleteEventCode, 0x01, // parameter_total_size (1 bytes) hci::kHardwareFailure @@ -141,7 +136,7 @@ const DeviceAddress kLeAliasAddress2(DeviceAddress::Type::kLEPublic, const DeviceAddress kDeviceAddress3(DeviceAddress::Type::kBREDR, {BD_ADDR(0x03)}); -const auto kInquiryResult = common::CreateStaticByteBuffer( +const auto kInquiryResult = CreateStaticByteBuffer( hci::kInquiryResultEventCode, 0x0F, // parameter_total_size (15 bytes) 0x01, // num_responses @@ -153,7 +148,7 @@ const auto kInquiryResult = common::CreateStaticByteBuffer( 0x00, 0x00 // clock_offset[0] ); -const auto kRSSIInquiryResult = common::CreateStaticByteBuffer( +const auto kRSSIInquiryResult = CreateStaticByteBuffer( hci::kInquiryResultWithRSSIEventCode, 0x0F, // parameter_total_size (15 bytes) 0x01, // num_responses @@ -165,7 +160,7 @@ const auto kRSSIInquiryResult = common::CreateStaticByteBuffer( 0xEC // RSSI (-20dBm) ); -#define REMOTE_NAME_REQUEST(addr1) common::CreateStaticByteBuffer( \ +#define REMOTE_NAME_REQUEST(addr1) CreateStaticByteBuffer( \ LowerBits(hci::kRemoteNameRequest), UpperBits(hci::kRemoteNameRequest), \ 0x0a, /* parameter_total_size (10 bytes) */ \ BD_ADDR(addr1), /* BD_ADDR */ \ @@ -183,7 +178,7 @@ const auto kRemoteNameRequestRsp = #undef COMMAND_STATUS_RSP -const auto kRemoteNameRequestComplete1 = common::CreateStaticByteBuffer( +const auto kRemoteNameRequestComplete1 = CreateStaticByteBuffer( hci::kRemoteNameRequestCompleteEventCode, 0x20, // parameter_total_size (32) hci::StatusCode::kSuccess, // status @@ -193,7 +188,7 @@ const auto kRemoteNameRequestComplete1 = common::CreateStaticByteBuffer( // remote name (Fuchsia 💖) // Everything after the 0x00 should be ignored. ); -const auto kRemoteNameRequestComplete2 = common::CreateStaticByteBuffer( +const auto kRemoteNameRequestComplete2 = CreateStaticByteBuffer( hci::kRemoteNameRequestCompleteEventCode, 0x10, // parameter_total_size (16) hci::StatusCode::kSuccess, // status @@ -201,7 +196,7 @@ const auto kRemoteNameRequestComplete2 = common::CreateStaticByteBuffer( 'S', 'a', 'p', 'p', 'h', 'i', 'r', 'e', 0x00 // remote name (Sapphire) ); -const auto kExtendedInquiryResult = common::CreateStaticByteBuffer( +const auto kExtendedInquiryResult = CreateStaticByteBuffer( hci::kExtendedInquiryResultEventCode, 0xFF, // parameter_total_size (255 bytes) 0x01, // num_responses @@ -236,14 +231,14 @@ const auto kExtendedInquiryResult = common::CreateStaticByteBuffer( #undef BD_ADDR -const auto kInqCancel = common::CreateStaticByteBuffer( +const auto kInqCancel = CreateStaticByteBuffer( LowerBits(hci::kInquiryCancel), UpperBits(hci::kInquiryCancel), // opcode 0x00 // parameter_total_size ); const auto kInqCancelRsp = COMMAND_COMPLETE_RSP(hci::kInquiryCancel); -const auto kSetExtendedMode = common::CreateStaticByteBuffer( +const auto kSetExtendedMode = CreateStaticByteBuffer( LowerBits(hci::kWriteInquiryMode), UpperBits(hci::kWriteInquiryMode), 0x01, // parameter_total_size 0x02 // Extended Inquiry Result or Inquiry Result with RSSI @@ -251,13 +246,13 @@ const auto kSetExtendedMode = common::CreateStaticByteBuffer( const auto kSetExtendedModeRsp = COMMAND_COMPLETE_RSP(hci::kWriteInquiryMode); -const auto kReadScanEnable = common::CreateStaticByteBuffer( +const auto kReadScanEnable = CreateStaticByteBuffer( LowerBits(hci::kReadScanEnable), UpperBits(hci::kReadScanEnable), 0x00 // No parameters ); #define READ_SCAN_ENABLE_RSP(scan_enable) \ - common::CreateStaticByteBuffer(hci::kCommandCompleteEventCode, 0x05, 0xF0, \ + CreateStaticByteBuffer(hci::kCommandCompleteEventCode, 0x05, 0xF0, \ LowerBits(hci::kReadScanEnable), \ UpperBits(hci::kReadScanEnable), \ hci::kSuccess, (scan_enable)) @@ -270,7 +265,7 @@ const auto kReadScanEnableRspBoth = READ_SCAN_ENABLE_RSP(0x03); #undef READ_SCAN_ENABLE_RSP #define WRITE_SCAN_ENABLE_CMD(scan_enable) \ - common::CreateStaticByteBuffer(LowerBits(hci::kWriteScanEnable), \ + CreateStaticByteBuffer(LowerBits(hci::kWriteScanEnable), \ UpperBits(hci::kWriteScanEnable), 0x01, \ (scan_enable)) @@ -527,7 +522,7 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, RequestDiscoveryError) { [&session](auto status, auto cb_session) { EXPECT_FALSE(status); EXPECT_FALSE(cb_session); - EXPECT_EQ(common::HostError::kProtocolError, status.error()); + EXPECT_EQ(HostError::kProtocolError, status.error()); EXPECT_EQ(hci::kHardwareFailure, status.protocol_error()); }); diff --git a/src/connectivity/bluetooth/core/bt-host/gap/bredr_interrogator.cc b/src/connectivity/bluetooth/core/bt-host/gap/bredr_interrogator.cc index 59ef5485903d6bc017574b9c9df48169bb11087d..5d6ee36ecd3eac1311f3a5beedafcf1176073804 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/bredr_interrogator.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/bredr_interrogator.cc @@ -20,7 +20,7 @@ BrEdrInterrogator::Interrogation::Interrogation(hci::ConnectionPtr conn, } BrEdrInterrogator::Interrogation::~Interrogation() { - Finish(hci::Status(common::HostError::kFailed)); + Finish(hci::Status(HostError::kFailed)); } void BrEdrInterrogator::Interrogation::Finish(hci::Status status) { @@ -64,7 +64,7 @@ void BrEdrInterrogator::Start(PeerId device_id, hci::ConnectionPtr conn_ptr, Peer* device = cache_->FindById(device_id); if (!device) { - Complete(device_id, hci::Status(common::HostError::kFailed)); + Complete(device_id, hci::Status(HostError::kFailed)); return; } @@ -96,7 +96,7 @@ void BrEdrInterrogator::Cancel(PeerId device_id) { return; } - it->second->Finish(hci::Status(common::HostError::kCanceled)); + it->second->Finish(hci::Status(HostError::kCanceled)); self->pending_.erase(it); }); } @@ -104,7 +104,7 @@ void BrEdrInterrogator::Cancel(PeerId device_id) { void BrEdrInterrogator::MaybeComplete(PeerId device_id) { Peer* device = cache_->FindById(device_id); if (!device) { - Complete(device_id, hci::Status(common::HostError::kFailed)); + Complete(device_id, hci::Status(HostError::kFailed)); return; } if (!device->name()) { @@ -140,7 +140,7 @@ void BrEdrInterrogator::Complete(PeerId device_id, hci::Status status) { void BrEdrInterrogator::MakeRemoteNameRequest(PeerId device_id) { Peer* device = cache_->FindById(device_id); if (!device) { - Complete(device_id, hci::Status(common::HostError::kFailed)); + Complete(device_id, hci::Status(HostError::kFailed)); return; } ZX_DEBUG_ASSERT(device->bredr()); @@ -189,7 +189,7 @@ void BrEdrInterrogator::MakeRemoteNameRequest(PeerId device_id) { } Peer* device = self->cache_->FindById(device_id); if (!device) { - self->Complete(device_id, hci::Status(common::HostError::kFailed)); + self->Complete(device_id, hci::Status(HostError::kFailed)); return; } device->SetName(std::string(params.remote_name, params.remote_name + len)); @@ -238,7 +238,7 @@ void BrEdrInterrogator::ReadRemoteVersionInformation( Peer* device = self->cache_->FindById(device_id); if (!device) { - self->Complete(device_id, hci::Status(common::HostError::kFailed)); + self->Complete(device_id, hci::Status(HostError::kFailed)); return; } device->set_version(params.lmp_version, params.manufacturer_name, @@ -288,7 +288,7 @@ void BrEdrInterrogator::ReadRemoteFeatures(PeerId device_id, Peer* device = self->cache_->FindById(device_id); if (!device) { - self->Complete(device_id, hci::Status(common::HostError::kFailed)); + self->Complete(device_id, hci::Status(HostError::kFailed)); return; } device->SetFeaturePage(0, le64toh(params.lmp_features)); @@ -345,7 +345,7 @@ void BrEdrInterrogator::ReadRemoteExtendedFeatures(PeerId device_id, Peer* device = self->cache_->FindById(device_id); if (!device) { - self->Complete(device_id, hci::Status(common::HostError::kFailed)); + self->Complete(device_id, hci::Status(HostError::kFailed)); return; } device->SetFeaturePage(params.page_number, le64toh(params.lmp_features)); diff --git a/src/connectivity/bluetooth/core/bt-host/gap/connection_request.h b/src/connectivity/bluetooth/core/bt-host/gap/connection_request.h index 98e77842295340aa0af7f6f15168f3dfe5e37ce2..47684abbf8197d1ef541a0111840fa38aed6c04f 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/connection_request.h +++ b/src/connectivity/bluetooth/core/bt-host/gap/connection_request.h @@ -24,7 +24,7 @@ class ConnectionRequest final { using OnComplete = fit::function<void(hci::Status, ConnectionRef)>; using RefFactory = fit::function<ConnectionRef()>; - ConnectionRequest(const common::DeviceAddress& addr, OnComplete&& callback) + ConnectionRequest(const DeviceAddress& addr, OnComplete&& callback) : address_(addr) { callbacks_.push_back(std::move(callback)); } @@ -40,10 +40,10 @@ class ConnectionRequest final { callback(status, generate_ref()); } - common::DeviceAddress address() const { return address_; } + DeviceAddress address() const { return address_; } private: - common::DeviceAddress address_; + DeviceAddress address_; std::list<OnComplete> callbacks_; DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(ConnectionRequest); diff --git a/src/connectivity/bluetooth/core/bt-host/gap/discovery_filter.cc b/src/connectivity/bluetooth/core/bt-host/gap/discovery_filter.cc index 5be56e5d75d34516c93c0260fcd7181b47a6fe50..efdaa7ae1bd4c4e527756f46de07a98f985730d5 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/discovery_filter.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/discovery_filter.cc @@ -14,8 +14,8 @@ namespace bt { namespace gap { namespace { -bool MatchUuids(const std::vector<common::UUID>& uuids, - const common::BufferView& data, size_t uuid_size) { +bool MatchUuids(const std::vector<UUID>& uuids, const BufferView& data, + size_t uuid_size) { if (data.size() % uuid_size) { bt_log(WARN, "gap", "malformed service UUIDs list"); return false; @@ -23,7 +23,7 @@ bool MatchUuids(const std::vector<common::UUID>& uuids, size_t uuid_count = data.size() / uuid_size; for (size_t i = 0; i < uuid_count; i++) { - const common::BufferView uuid_bytes(data.data() + i * uuid_size, uuid_size); + const BufferView uuid_bytes(data.data() + i * uuid_size, uuid_size); for (const auto& uuid : uuids) { if (uuid.CompareBytes(uuid_bytes)) return true; @@ -40,9 +40,9 @@ void DiscoveryFilter::SetGeneralDiscoveryFlags() { static_cast<uint8_t>(AdvFlag::kLELimitedDiscoverableMode)); } -bool DiscoveryFilter::MatchLowEnergyResult( - const common::ByteBuffer& advertising_data, bool connectable, - int8_t rssi) const { +bool DiscoveryFilter::MatchLowEnergyResult(const ByteBuffer& advertising_data, + bool connectable, + int8_t rssi) const { // No need to iterate over |advertising_data| for the |connectable_| filter. if (connectable_ && *connectable_ != connectable) return false; @@ -67,7 +67,7 @@ bool DiscoveryFilter::MatchLowEnergyResult( return false; DataType type; - common::BufferView data; + BufferView data; while (reader.GetNextField(&type, &data)) { switch (type) { case DataType::kFlags: { diff --git a/src/connectivity/bluetooth/core/bt-host/gap/discovery_filter.h b/src/connectivity/bluetooth/core/bt-host/gap/discovery_filter.h index d3e4076d03fe9d9a7a9165bc86eade4463db2f86..83ec4ed9bac66f3fc9a0338e7c975e2ed6263b4c 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/discovery_filter.h +++ b/src/connectivity/bluetooth/core/bt-host/gap/discovery_filter.h @@ -13,9 +13,7 @@ namespace bt { -namespace common { class ByteBuffer; -} // namespace common namespace gap { @@ -48,7 +46,7 @@ class DiscoveryFilter final { // // Passing an empty value for |service_uuids| effectively disables this // filter. - void set_service_uuids(const std::vector<common::UUID>& service_uuids) { + void set_service_uuids(const std::vector<UUID>& service_uuids) { service_uuids_ = service_uuids; } @@ -103,14 +101,14 @@ class DiscoveryFilter final { // Returns true, if the given LE scan result satisfies this filter. Otherwise // returns false. |advertising_data| should include scan response data, if // any. - bool MatchLowEnergyResult(const common::ByteBuffer& advertising_data, + bool MatchLowEnergyResult(const ByteBuffer& advertising_data, bool connectable, int8_t rssi) const; // Clears all the fields of this filter. void Reset(); private: - std::vector<common::UUID> service_uuids_; + std::vector<UUID> service_uuids_; std::string name_substring_; std::optional<uint8_t> flags_; bool all_flags_required_; diff --git a/src/connectivity/bluetooth/core/bt-host/gap/discovery_filter_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gap/discovery_filter_unittest.cc index 3fa1a693d6a6a638e73b64da54548ef64678294f..3f57930ba573018e932f4808779d8f19f6788333 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/discovery_filter_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/discovery_filter_unittest.cc @@ -5,7 +5,6 @@ #include "src/connectivity/bluetooth/core/bt-host/gap/discovery_filter.h" #include "gtest/gtest.h" - #include "src/connectivity/bluetooth/core/bt-host/hci/low_energy_scanner.h" namespace bt { @@ -13,10 +12,9 @@ namespace gap { namespace { TEST(GAP_DiscoveryFilterTest, Flags) { - const common::BufferView kEmptyData; - const auto kInvalidFlagsData = common::CreateStaticByteBuffer(0x01, 0x01); - const auto kValidFlagsData = - common::CreateStaticByteBuffer(0x02, 0x01, 0b101); + const BufferView kEmptyData; + const auto kInvalidFlagsData = CreateStaticByteBuffer(0x01, 0x01); + const auto kValidFlagsData = CreateStaticByteBuffer(0x02, 0x01, 0b101); DiscoveryFilter filter; @@ -114,7 +112,7 @@ TEST(GAP_DiscoveryFilterTest, Flags) { } TEST(GAP_DiscoveryFilterTest, Connectable) { - common::BufferView empty; + BufferView empty; DiscoveryFilter filter; // Empty filter should match both. @@ -136,25 +134,25 @@ TEST(GAP_DiscoveryFilterTest, 16BitServiceUuids) { constexpr uint16_t kUuid0 = 0x180d; constexpr uint16_t kUuid1 = 0x1800; - const common::BufferView kEmptyData; + const BufferView kEmptyData; // Below, "Incomplete" refers to the "Incomplete Service UUIDs" field while // "Complete" refers to "Complete Service UUIDs". - const auto kIncompleteEmpty = common::CreateStaticByteBuffer(0x01, 0x02); + const auto kIncompleteEmpty = CreateStaticByteBuffer(0x01, 0x02); const auto kIncompleteNoMatch = - common::CreateStaticByteBuffer(0x05, 0x02, 0x01, 0x02, 0x03, 0x04); + CreateStaticByteBuffer(0x05, 0x02, 0x01, 0x02, 0x03, 0x04); const auto kIncompleteMatch1 = - common::CreateStaticByteBuffer(0x05, 0x02, 0x01, 0x02, 0x0d, 0x18); + CreateStaticByteBuffer(0x05, 0x02, 0x01, 0x02, 0x0d, 0x18); const auto kIncompleteMatch2 = - common::CreateStaticByteBuffer(0x05, 0x02, 0x00, 0x18, 0x03, 0x04); - const auto kCompleteEmpty = common::CreateStaticByteBuffer(0x01, 0x03); + CreateStaticByteBuffer(0x05, 0x02, 0x00, 0x18, 0x03, 0x04); + const auto kCompleteEmpty = CreateStaticByteBuffer(0x01, 0x03); const auto kCompleteNoMatch = - common::CreateStaticByteBuffer(0x05, 0x03, 0x01, 0x02, 0x03, 0x04); + CreateStaticByteBuffer(0x05, 0x03, 0x01, 0x02, 0x03, 0x04); const auto kCompleteMatch1 = - common::CreateStaticByteBuffer(0x05, 0x03, 0x01, 0x02, 0x0d, 0x18); + CreateStaticByteBuffer(0x05, 0x03, 0x01, 0x02, 0x0d, 0x18); const auto kCompleteMatch2 = - common::CreateStaticByteBuffer(0x05, 0x03, 0x00, 0x18, 0x03, 0x04); + CreateStaticByteBuffer(0x05, 0x03, 0x00, 0x18, 0x03, 0x04); DiscoveryFilter filter; @@ -181,8 +179,7 @@ TEST(GAP_DiscoveryFilterTest, 16BitServiceUuids) { filter.MatchLowEnergyResult(kCompleteMatch2, false, hci::kRSSIInvalid)); // Filter for kUuid0 and kUuid1. - filter.set_service_uuids( - std::vector<common::UUID>{common::UUID(kUuid0), common::UUID(kUuid1)}); + filter.set_service_uuids(std::vector<UUID>{UUID(kUuid0), UUID(kUuid1)}); EXPECT_FALSE( filter.MatchLowEnergyResult(kEmptyData, false, hci::kRSSIInvalid)); EXPECT_FALSE( @@ -207,24 +204,24 @@ TEST(GAP_DiscoveryFilterTest, 32BitServiceUuids) { constexpr uint16_t kUuid0 = 0x180d; constexpr uint16_t kUuid1 = 0x1800; - const common::BufferView kEmptyData; + const BufferView kEmptyData; // Below, "Incomplete" refers to the "Incomplete Service UUIDs" field while // "Complete" refers to "Complete Service UUIDs". - const auto kIncompleteEmpty = common::CreateStaticByteBuffer(0x01, 0x04); - const auto kIncompleteNoMatch = common::CreateStaticByteBuffer( + const auto kIncompleteEmpty = CreateStaticByteBuffer(0x01, 0x04); + const auto kIncompleteNoMatch = CreateStaticByteBuffer( 0x09, 0x04, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08); - const auto kIncompleteMatch1 = common::CreateStaticByteBuffer( + const auto kIncompleteMatch1 = CreateStaticByteBuffer( 0x09, 0x04, 0x01, 0x02, 0x03, 0x04, 0x0d, 0x18, 0x00, 0x00); - const auto kIncompleteMatch2 = common::CreateStaticByteBuffer( + const auto kIncompleteMatch2 = CreateStaticByteBuffer( 0x09, 0x04, 0x00, 0x18, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04); - const auto kCompleteEmpty = common::CreateStaticByteBuffer(0x01, 0x05); - const auto kCompleteNoMatch = common::CreateStaticByteBuffer( + const auto kCompleteEmpty = CreateStaticByteBuffer(0x01, 0x05); + const auto kCompleteNoMatch = CreateStaticByteBuffer( 0x09, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08); - const auto kCompleteMatch1 = common::CreateStaticByteBuffer( + const auto kCompleteMatch1 = CreateStaticByteBuffer( 0x09, 0x05, 0x01, 0x02, 0x03, 0x04, 0x0d, 0x18, 0x00, 0x00); - const auto kCompleteMatch2 = common::CreateStaticByteBuffer( + const auto kCompleteMatch2 = CreateStaticByteBuffer( 0x09, 0x05, 0x00, 0x18, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04); DiscoveryFilter filter; @@ -252,8 +249,7 @@ TEST(GAP_DiscoveryFilterTest, 32BitServiceUuids) { filter.MatchLowEnergyResult(kCompleteMatch2, false, hci::kRSSIInvalid)); // Filter for kUuid0 and kUuid1. - filter.set_service_uuids( - std::vector<common::UUID>{common::UUID(kUuid0), common::UUID(kUuid1)}); + filter.set_service_uuids(std::vector<UUID>{UUID(kUuid0), UUID(kUuid1)}); EXPECT_FALSE( filter.MatchLowEnergyResult(kEmptyData, false, hci::kRSSIInvalid)); EXPECT_FALSE( @@ -278,65 +274,65 @@ TEST(GAP_DiscoveryFilterTest, 128BitServiceUuids) { constexpr uint16_t kUuid0 = 0x180d; constexpr uint16_t kUuid1 = 0x1800; - const common::BufferView kEmptyData; + const BufferView kEmptyData; // Below, "Incomplete" refers to the "Incomplete Service UUIDs" field while // "Complete" refers to "Complete Service UUIDs". - const auto kIncompleteEmpty = common::CreateStaticByteBuffer(0x01, 0x06); - const auto kIncompleteNoMatch = common::CreateStaticByteBuffer( - 0x11, 0x06, - - // UUID - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, - 0x0C, 0x0D, 0x0E, 0x0F); - const auto kIncompleteMatch1 = common::CreateStaticByteBuffer( - 0x21, 0x06, - - // UUID 1 - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, - 0x0C, 0x0D, 0x0E, 0x0F, - - // UUID 2 - 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, - 0x0d, 0x18, 0x00, 0x00); - const auto kIncompleteMatch2 = common::CreateStaticByteBuffer( - 0x21, 0x06, - - // UUID 1 - 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, - 0x00, 0x18, 0x00, 0x00, - - // UUID 2 - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, - 0x0C, 0x0D, 0x0E, 0x0F); - const auto kCompleteEmpty = common::CreateStaticByteBuffer(0x01, 0x07); - const auto kCompleteNoMatch = common::CreateStaticByteBuffer( - 0x11, 0x07, - - // UUID - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, - 0x0C, 0x0D, 0x0E, 0x0F); - const auto kCompleteMatch1 = common::CreateStaticByteBuffer( - 0x21, 0x07, - - // UUID 1 - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, - 0x0C, 0x0D, 0x0E, 0x0F, - - // UUID 2 - 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, - 0x0d, 0x18, 0x00, 0x00); - const auto kCompleteMatch2 = common::CreateStaticByteBuffer( - 0x21, 0x07, - - // UUID 1 - 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, - 0x00, 0x18, 0x00, 0x00, - - // UUID 2 - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, - 0x0C, 0x0D, 0x0E, 0x0F); + const auto kIncompleteEmpty = CreateStaticByteBuffer(0x01, 0x06); + const auto kIncompleteNoMatch = + CreateStaticByteBuffer(0x11, 0x06, + + // UUID + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F); + const auto kIncompleteMatch1 = + CreateStaticByteBuffer(0x21, 0x06, + + // UUID 1 + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + + // UUID 2 + 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0x0d, 0x18, 0x00, 0x00); + const auto kIncompleteMatch2 = + CreateStaticByteBuffer(0x21, 0x06, + + // UUID 1 + 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, + + // UUID 2 + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F); + const auto kCompleteEmpty = CreateStaticByteBuffer(0x01, 0x07); + const auto kCompleteNoMatch = + CreateStaticByteBuffer(0x11, 0x07, + + // UUID + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F); + const auto kCompleteMatch1 = + CreateStaticByteBuffer(0x21, 0x07, + + // UUID 1 + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + + // UUID 2 + 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0x0d, 0x18, 0x00, 0x00); + const auto kCompleteMatch2 = + CreateStaticByteBuffer(0x21, 0x07, + + // UUID 1 + 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, + + // UUID 2 + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F); DiscoveryFilter filter; @@ -363,8 +359,7 @@ TEST(GAP_DiscoveryFilterTest, 128BitServiceUuids) { filter.MatchLowEnergyResult(kCompleteMatch2, false, hci::kRSSIInvalid)); // Filter for kUuid0 and kUuid1. - filter.set_service_uuids( - std::vector<common::UUID>{common::UUID(kUuid0), common::UUID(kUuid1)}); + filter.set_service_uuids(std::vector<UUID>{UUID(kUuid0), UUID(kUuid1)}); EXPECT_FALSE( filter.MatchLowEnergyResult(kEmptyData, false, hci::kRSSIInvalid)); EXPECT_FALSE( @@ -386,12 +381,12 @@ TEST(GAP_DiscoveryFilterTest, 128BitServiceUuids) { } TEST(GAP_DiscoveryFilterTest, NameSubstring) { - const common::BufferView kEmptyData; + const BufferView kEmptyData; const auto kShortenedName = - common::CreateStaticByteBuffer(0x05, 0x08, 'T', 'e', 's', 't'); + CreateStaticByteBuffer(0x05, 0x08, 'T', 'e', 's', 't'); const auto kCompleteName = - common::CreateStaticByteBuffer(0x0E, 0x09, 'T', 'e', 's', 't', ' ', 'C', - 'o', 'm', 'p', 'l', 'e', 't', 'e'); + CreateStaticByteBuffer(0x0E, 0x09, 'T', 'e', 's', 't', ' ', 'C', 'o', 'm', + 'p', 'l', 'e', 't', 'e'); DiscoveryFilter filter; @@ -440,7 +435,7 @@ TEST(GAP_DiscoveryFilterTest, NameSubstring) { TEST(GAP_DiscoveryFilterTest, RSSI) { constexpr int8_t kRSSIThreshold = 60; - const common::BufferView kEmptyData; + const BufferView kEmptyData; DiscoveryFilter filter; filter.set_rssi(hci::kRSSIInvalid); @@ -479,9 +474,8 @@ TEST(GAP_DiscoveryFilterTest, Pathloss) { constexpr int8_t kNotMatchingRSSI = -66; constexpr int8_t kTooLargeRSSI = 71; - const common::BufferView kEmptyData; - const auto kDataWithTxPower = - common::CreateStaticByteBuffer(0x02, 0x0A, kTxPower); + const BufferView kEmptyData; + const auto kDataWithTxPower = CreateStaticByteBuffer(0x02, 0x0A, kTxPower); DiscoveryFilter filter; filter.set_pathloss(kPathlossThreshold); @@ -524,14 +518,12 @@ TEST(GAP_DiscoveryFilterTest, Pathloss) { } TEST(GAP_DiscoveryFilterTest, ManufacturerCode) { - const common::BufferView kEmptyData; - const auto kValidData0 = - common::CreateStaticByteBuffer(0x03, 0xFF, 0xE0, 0x00); + const BufferView kEmptyData; + const auto kValidData0 = CreateStaticByteBuffer(0x03, 0xFF, 0xE0, 0x00); const auto kValidData1 = - common::CreateStaticByteBuffer(0x06, 0xFF, 0xE0, 0x00, 0x01, 0x02, 0x03); - const auto kInvalidData0 = common::CreateStaticByteBuffer(0x02, 0xFF, 0xE0); - const auto kInvalidData1 = - common::CreateStaticByteBuffer(0x03, 0xFF, 0x4C, 0x00); + CreateStaticByteBuffer(0x06, 0xFF, 0xE0, 0x00, 0x01, 0x02, 0x03); + const auto kInvalidData0 = CreateStaticByteBuffer(0x02, 0xFF, 0xE0); + const auto kInvalidData1 = CreateStaticByteBuffer(0x03, 0xFF, 0x4C, 0x00); DiscoveryFilter filter; @@ -572,7 +564,7 @@ TEST(GAP_DiscoveryFilterTest, Combined) { constexpr char kMatchingName[] = "test"; constexpr char kNotMatchingName[] = "foo"; - const auto kAdvertisingData = common::CreateStaticByteBuffer( + const auto kAdvertisingData = CreateStaticByteBuffer( // Flags 0x02, 0x01, 0x01, @@ -596,8 +588,7 @@ TEST(GAP_DiscoveryFilterTest, Combined) { // Assign all fields and make them match. filter.set_flags(0x01); filter.set_connectable(true); - filter.set_service_uuids( - std::vector<common::UUID>{common::UUID(kMatchingUuid)}); + filter.set_service_uuids(std::vector<UUID>{UUID(kMatchingUuid)}); filter.set_name_substring(kMatchingName); filter.set_pathloss(kMatchingPathlossThreshold); filter.set_manufacturer_code(0x00E0); @@ -613,11 +604,9 @@ TEST(GAP_DiscoveryFilterTest, Combined) { EXPECT_FALSE(filter.MatchLowEnergyResult(kAdvertisingData, true, kRSSI)); filter.set_connectable(true); - filter.set_service_uuids( - std::vector<common::UUID>{common::UUID(kNotMatchingUuid)}); + filter.set_service_uuids(std::vector<UUID>{UUID(kNotMatchingUuid)}); EXPECT_FALSE(filter.MatchLowEnergyResult(kAdvertisingData, true, kRSSI)); - filter.set_service_uuids( - std::vector<common::UUID>{common::UUID(kMatchingUuid)}); + filter.set_service_uuids(std::vector<UUID>{UUID(kMatchingUuid)}); filter.set_name_substring(kNotMatchingName); EXPECT_FALSE(filter.MatchLowEnergyResult(kAdvertisingData, true, kRSSI)); @@ -635,13 +624,13 @@ TEST(GAP_DiscoveryFilterTest, Combined) { } TEST(GAP_DiscoveryFilterTest, GeneralDiscoveryFlags) { - const auto kLimitedDiscoverableData = common::CreateStaticByteBuffer( + const auto kLimitedDiscoverableData = CreateStaticByteBuffer( // Flags 0x02, 0x01, 0x01); - const auto kGeneralDiscoverableData = common::CreateStaticByteBuffer( + const auto kGeneralDiscoverableData = CreateStaticByteBuffer( // Flags 0x02, 0x01, 0x02); - const auto kNonDiscoverableData = common::CreateStaticByteBuffer( + const auto kNonDiscoverableData = CreateStaticByteBuffer( // Flags (all flags are set except for discoverability). 0x02, 0x01, 0xFC); diff --git a/src/connectivity/bluetooth/core/bt-host/gap/gap.h b/src/connectivity/bluetooth/core/bt-host/gap/gap.h index b5822d4beff90cb0e692188f74d7c4e788da29ef..9b4304bb39d896a8c8716716b53999b8f235077c 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/gap.h +++ b/src/connectivity/bluetooth/core/bt-host/gap/gap.h @@ -31,10 +31,6 @@ enum class Mode { kExtended, }; -// Opaque identifier type. This is used by the GAP library to identify remote -// Bluetooth devices. -using PeerId = common::PeerId; - // EIR Data Type, Advertising Data Type (AD Type), OOB Data Type definitions. // clang-format off enum class DataType : uint8_t { diff --git a/src/connectivity/bluetooth/core/bt-host/gap/identity_resolving_list.cc b/src/connectivity/bluetooth/core/bt-host/gap/identity_resolving_list.cc index 2fd8aaa946560647214a31d49863cc3647e86a2b..375d181ee46811fafd06380016c6fb1afdeda973 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/identity_resolving_list.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/identity_resolving_list.cc @@ -10,9 +10,6 @@ namespace bt { namespace gap { -using common::DeviceAddress; -using common::UInt128; - void IdentityResolvingList::Add(DeviceAddress identity, const UInt128& irk) { registry_[identity] = irk; } diff --git a/src/connectivity/bluetooth/core/bt-host/gap/identity_resolving_list.h b/src/connectivity/bluetooth/core/bt-host/gap/identity_resolving_list.h index 249501686f4b8c7f74437a8fdc3b159b751e9437..2746b1191cdbd21c8478b8c63aa2b679151bcc73 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/identity_resolving_list.h +++ b/src/connectivity/bluetooth/core/bt-host/gap/identity_resolving_list.h @@ -5,11 +5,11 @@ #ifndef SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_GAP_IDENTITY_RESOLVING_LIST_H_ #define SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_GAP_IDENTITY_RESOLVING_LIST_H_ +#include <fbl/macros.h> + #include <optional> #include <unordered_map> -#include <fbl/macros.h> - #include "src/connectivity/bluetooth/core/bt-host/common/device_address.h" #include "src/connectivity/bluetooth/core/bt-host/common/uint128.h" @@ -28,19 +28,19 @@ class IdentityResolvingList final { // Associate the given |irk| with |identity|. If |identity| is already in the // list, the existing entry is updated with the new IRK. - void Add(common::DeviceAddress identity, const common::UInt128& irk); + void Add(DeviceAddress identity, const UInt128& irk); // Delete |identity| and associated IRK, if present. - void Remove(common::DeviceAddress identity); + void Remove(DeviceAddress identity); // Tries to resolve the given RPA against the identities in the registry. // Returns std::nullopt if the address is not a RPA or cannot be resolved. // Otherwise, returns a value containing the identity address. - std::optional<common::DeviceAddress> Resolve(common::DeviceAddress rpa) const; + std::optional<DeviceAddress> Resolve(DeviceAddress rpa) const; private: // Maps identity addresses to IRKs. - std::unordered_map<common::DeviceAddress, common::UInt128> registry_; + std::unordered_map<DeviceAddress, UInt128> registry_; DISALLOW_COPY_ASSIGN_AND_MOVE(IdentityResolvingList); }; diff --git a/src/connectivity/bluetooth/core/bt-host/gap/identity_resolving_list_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gap/identity_resolving_list_unittest.cc index 575c4fbcce26d5056ed535debc962f4252ad1c18..779cd330b3ed85e6be08a6baab50730327b71291 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/identity_resolving_list_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/identity_resolving_list_unittest.cc @@ -5,17 +5,12 @@ #include "identity_resolving_list.h" #include "gtest/gtest.h" - #include "src/connectivity/bluetooth/core/bt-host/sm/util.h" namespace bt { namespace gap { namespace { -using common::DeviceAddress; -using common::RandomUInt128; -using common::UInt128; - const DeviceAddress kAddress1(DeviceAddress::Type::kLERandom, "01:02:03:04:05:06"); const DeviceAddress kAddress2(DeviceAddress::Type::kLERandom, diff --git a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_address_manager.cc b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_address_manager.cc index 8162851a88e37fc02cb11a693f1b2d59ec134a62..e6dd2fa349cfde1ea4f148a8e3473cbb8fd57933 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_address_manager.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_address_manager.cc @@ -4,19 +4,14 @@ #include "low_energy_address_manager.h" +#include "gap.h" #include "src/connectivity/bluetooth/core/bt-host/common/log.h" #include "src/connectivity/bluetooth/core/bt-host/hci/transport.h" #include "src/connectivity/bluetooth/core/bt-host/sm/util.h" -#include "gap.h" - namespace bt { namespace gap { -using common::DeviceAddress; -using common::HostError; -using common::UInt128; - LowEnergyAddressManager::LowEnergyAddressManager( const DeviceAddress& public_address, StateQueryDelegate delegate, fxl::RefPtr<hci::Transport> hci) diff --git a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_address_manager.h b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_address_manager.h index 1c39df193416a56dd30c366171d01ace4e8b60f6..175e2b38862f03f690456cc0d51f6a1b095a394b 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_address_manager.h +++ b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_address_manager.h @@ -70,14 +70,14 @@ class LowEnergyAddressManager final : public hci::LocalAddressDelegate { // if scan, legacy advertising, and/or initiation procedures are in progress. using StateQueryDelegate = fit::function<bool()>; - LowEnergyAddressManager(const common::DeviceAddress& public_address, + LowEnergyAddressManager(const DeviceAddress& public_address, StateQueryDelegate delegate, fxl::RefPtr<hci::Transport> hci); ~LowEnergyAddressManager(); // Assigns the IRK to generate a RPA for the next address refresh when privacy // is enabled. - void set_irk(const std::optional<common::UInt128>& irk) { irk_ = irk; } + void set_irk(const std::optional<UInt128>& irk) { irk_ = irk; } // Enable or disable the privacy feature. When enabled, the controller will be // configured to use a new random address if it is currently allowed to do so. @@ -92,13 +92,13 @@ class LowEnergyAddressManager final : public hci::LocalAddressDelegate { void EnablePrivacy(bool enabled); // LocalAddressDelegate overrides: - std::optional<common::UInt128> irk() const override { return irk_; } - common::DeviceAddress identity_address() const override { return public_; } + std::optional<UInt128> irk() const override { return irk_; } + DeviceAddress identity_address() const override { return public_; } void EnsureLocalAddress(AddressCallback callback) override; private: // Return the current address. - const common::DeviceAddress& current_address() const { + const DeviceAddress& current_address() const { return (privacy_enabled_ && random_) ? *random_ : public_; } @@ -120,12 +120,12 @@ class LowEnergyAddressManager final : public hci::LocalAddressDelegate { // The public device address (i.e. BD_ADDR) that is assigned to the // controller. - const common::DeviceAddress public_; + const DeviceAddress public_; // The random device address assigned to the controller by the most recent // successful HCI_LE_Set_Random_Address command. std::nullopt if the command // was never run successfully. - std::optional<common::DeviceAddress> random_; + std::optional<DeviceAddress> random_; // True if the random address needs a refresh. This is the case when // a. Privacy is enabled and the random device address needs to get rotated; @@ -139,7 +139,7 @@ class LowEnergyAddressManager final : public hci::LocalAddressDelegate { // The local identity resolving key. If present, it is used to generate RPAs // when privacy is enabled. - std::optional<common::UInt128> irk_; + std::optional<UInt128> irk_; // Callbacks waiting to be notified of the local address. std::queue<AddressCallback> address_callbacks_; diff --git a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_address_manager_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_address_manager_unittest.cc index f2980967cc89b4752abef2ae15abd2ccdeacb5ed..5b5ee83385a48b545c9764c9a16e0f9c7ef9322a 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_address_manager_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_address_manager_unittest.cc @@ -6,20 +6,15 @@ #include <fbl/function.h> +#include "gap.h" #include "src/connectivity/bluetooth/core/bt-host/sm/util.h" #include "src/connectivity/bluetooth/core/bt-host/testing/fake_controller_test.h" #include "src/connectivity/bluetooth/core/bt-host/testing/test_controller.h" -#include "gap.h" - namespace bt { namespace gap { namespace { -using common::CreateStaticByteBuffer; -using common::DeviceAddress; -using common::DeviceAddressBytes; -using common::UInt128; using testing::CommandTransaction; using testing::TestController; diff --git a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_advertising_manager.cc b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_advertising_manager.cc index 25518bff1ce9aad92da2905b1dcbffd2cfd12584..81be76714c97e8a98357788158f5e5e3bd1f071f 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_advertising_manager.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_advertising_manager.cc @@ -23,7 +23,7 @@ constexpr size_t kFlagsSize = 3; constexpr uint8_t kDefaultFlags = 0; // Write the block for the flags to the |buffer|. -void WriteFlags(common::MutableByteBuffer* buffer, bool limited = false) { +void WriteFlags(MutableByteBuffer* buffer, bool limited = false) { ZX_DEBUG_ASSERT(buffer->size() >= kFlagsSize); (*buffer)[0] = 2; (*buffer)[1] = static_cast<uint8_t>(DataType::kFlags); @@ -41,16 +41,16 @@ class LowEnergyAdvertisingManager::ActiveAdvertisement final { // TODO(BT-270): Don't randomly generate the ID of an advertisement. // Instead use a counter like other internal IDs once this ID is not visible // outside of bt-host. - explicit ActiveAdvertisement(const common::DeviceAddress& address) - : address_(address), id_(common::RandomPeerId().value()) {} + explicit ActiveAdvertisement(const DeviceAddress& address) + : address_(address), id_(RandomPeerId().value()) {} ~ActiveAdvertisement() = default; - const common::DeviceAddress& address() const { return address_; } + const DeviceAddress& address() const { return address_; } AdvertisementId id() const { return id_; } private: - common::DeviceAddress address_; + DeviceAddress address_; AdvertisementId id_; DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(ActiveAdvertisement); @@ -81,18 +81,17 @@ void LowEnergyAdvertisingManager::StartAdvertising( if (anonymous && connect_callback) { bt_log(TRACE, "gap-le", "can't advertise anonymously and connectable!"); status_callback(kInvalidAdvertisementId, - hci::Status(common::HostError::kInvalidParameters)); + hci::Status(HostError::kInvalidParameters)); return; } // Serialize the data - auto data_bytes = - common::NewSlabBuffer(data.CalculateBlockSize() + kFlagsSize); + auto data_bytes = NewSlabBuffer(data.CalculateBlockSize() + kFlagsSize); WriteFlags(data_bytes.get()); auto data_view = data_bytes->mutable_view(kFlagsSize); data.WriteBlock(&data_view); - auto scan_rsp_bytes = common::NewSlabBuffer(scan_rsp.CalculateBlockSize()); + auto scan_rsp_bytes = NewSlabBuffer(scan_rsp.CalculateBlockSize()); scan_rsp.WriteBlock(scan_rsp_bytes.get()); auto self = weak_ptr_factory_.GetWeakPtr(); diff --git a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_advertising_manager.h b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_advertising_manager.h index 072da7637f730e868b7dfa45d68f244f2cecc14d..b1c5746ed3476ddd80843492df8696ea81f933ed 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_advertising_manager.h +++ b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_advertising_manager.h @@ -24,7 +24,7 @@ class Transport; namespace gap { -using AdvertisementId = common::Identifier<uint64_t>; +using AdvertisementId = Identifier<uint64_t>; constexpr AdvertisementId kInvalidAdvertisementId(0u); class LowEnergyAdvertisingManager { @@ -49,11 +49,11 @@ class LowEnergyAdvertisingManager { // - an |advertisement_id|, which can be used to stop advertising // or disambiguate calls to |callback|, and a success |status|. // - kInvalidAdvertisementId and an error indication in |status|: - // * common::HostError::kInvalidParameters if the advertising parameters + // * HostError::kInvalidParameters if the advertising parameters // are invalid (e.g. |data| is too large). - // * common::HostError::kNotSupported if another set cannot be advertised + // * HostError::kNotSupported if another set cannot be advertised // or if the requested parameters are not supported by the hardware. - // * common::HostError::kProtocolError with a HCI error reported from + // * HostError::kProtocolError with a HCI error reported from // the controller, otherwise. using ConnectionCallback = fit::function<void( AdvertisementId advertisement_id, std::unique_ptr<hci::Connection> link)>; diff --git a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_advertising_manager_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_advertising_manager_unittest.cc index 4a4d445812c0471b868633e788fa128e082a4ca6..ed3cc6486b6e798569468f79f1a010312987be09 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_advertising_manager_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_advertising_manager_unittest.cc @@ -20,8 +20,6 @@ namespace bt { namespace gap { namespace { -using common::DeviceAddress; - constexpr size_t kDefaultMaxAds = 1; constexpr size_t kDefaultMaxAdSize = 23; constexpr size_t kDefaultFakeAdSize = 20; @@ -46,7 +44,7 @@ class FakeLowEnergyAdvertiser final : public hci::LowEnergyAdvertiser { public: FakeLowEnergyAdvertiser( size_t max_ads, size_t max_ad_size, - std::map<common::DeviceAddress, AdvertisementStatus>* ad_store) + std::map<DeviceAddress, AdvertisementStatus>* ad_store) : max_ads_(max_ads), max_ad_size_(max_ad_size), ads_(ad_store) { ZX_ASSERT(ads_); } @@ -59,9 +57,8 @@ class FakeLowEnergyAdvertiser final : public hci::LowEnergyAdvertiser { bool AllowsRandomAddressChange() const override { return true; } - void StartAdvertising(const common::DeviceAddress& address, - const common::ByteBuffer& data, - const common::ByteBuffer& scan_rsp, + void StartAdvertising(const DeviceAddress& address, const ByteBuffer& data, + const ByteBuffer& scan_rsp, ConnectionCallback connect_callback, zx::duration interval, bool anonymous, AdvertisingStatusCallback callback) override { @@ -71,13 +68,11 @@ class FakeLowEnergyAdvertiser final : public hci::LowEnergyAdvertiser { return; } if (data.size() > max_ad_size_) { - callback(zx::duration(), - hci::Status(common::HostError::kInvalidParameters)); + callback(zx::duration(), hci::Status(HostError::kInvalidParameters)); return; } if (scan_rsp.size() > max_ad_size_) { - callback(zx::duration(), - hci::Status(common::HostError::kInvalidParameters)); + callback(zx::duration(), hci::Status(HostError::kInvalidParameters)); return; } AdvertisementStatus new_status; @@ -90,14 +85,14 @@ class FakeLowEnergyAdvertiser final : public hci::LowEnergyAdvertiser { callback(interval, hci::Status()); } - bool StopAdvertising(const common::DeviceAddress& address) override { + bool StopAdvertising(const DeviceAddress& address) override { ads_->erase(address); return true; } void OnIncomingConnection( hci::ConnectionHandle handle, hci::Connection::Role role, - const common::DeviceAddress& peer_address, + const DeviceAddress& peer_address, const hci::LEConnectionParameters& conn_params) override { // Right now, we call the first callback, because we can't call any other // ones. @@ -117,7 +112,7 @@ class FakeLowEnergyAdvertiser final : public hci::LowEnergyAdvertiser { private: size_t max_ads_, max_ad_size_; - std::map<common::DeviceAddress, AdvertisementStatus>* ads_; + std::map<DeviceAddress, AdvertisementStatus>* ads_; hci::Status pending_error_; DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(FakeLowEnergyAdvertiser); @@ -146,8 +141,8 @@ class GAP_LowEnergyAdvertisingManagerTest : public TestingBase { AdvertisingData CreateFakeAdvertisingData( size_t packed_size = kDefaultFakeAdSize) { AdvertisingData result; - auto buffer = common::CreateStaticByteBuffer(0x00, 0x01, 0x02, 0x03, 0x04, - 0x05, 0x06, 0x07, 0x08); + auto buffer = CreateStaticByteBuffer(0x00, 0x01, 0x02, 0x03, 0x04, 0x05, + 0x06, 0x07, 0x08); size_t bytes_left = packed_size; while (bytes_left > 0) { // Each field to take 10 bytes total, unless the next header (4 bytes) @@ -189,7 +184,7 @@ class GAP_LowEnergyAdvertisingManagerTest : public TestingBase { } LowEnergyAdvertisingManager* adv_mgr() const { return adv_mgr_.get(); } - const std::map<common::DeviceAddress, AdvertisementStatus>& ad_store() { + const std::map<DeviceAddress, AdvertisementStatus>& ad_store() { return ad_store_; } AdvertisementId last_ad_id() const { return last_ad_id_; } @@ -205,7 +200,7 @@ class GAP_LowEnergyAdvertisingManagerTest : public TestingBase { private: hci::FakeLocalAddressDelegate fake_address_delegate_; - std::map<common::DeviceAddress, AdvertisementStatus> ad_store_; + std::map<DeviceAddress, AdvertisementStatus> ad_store_; AdvertisementId last_ad_id_; std::optional<hci::Status> last_status_; std::unique_ptr<FakeLowEnergyAdvertiser> advertiser_; diff --git a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager.cc b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager.cc index 2d75892783223d9276668b2ea3d8cfbe8f89aacf..61bb183ec04e2ee1bd8ef67cdaa74a65ec8ad63b 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager.cc @@ -24,8 +24,6 @@ namespace bt { namespace gap { -using common::DeviceAddress; - namespace internal { // Represents the state of an active connection. Each instance is owned @@ -448,7 +446,7 @@ LowEnergyConnectionManager::~LowEnergyConnectionManager() { // Clear |pending_requests_| and notify failure. for (auto& iter : pending_requests_) { - iter.second.NotifyCallbacks(hci::Status(common::HostError::kFailed), + iter.second.NotifyCallbacks(hci::Status(HostError::kFailed), [] { return nullptr; }); } pending_requests_.clear(); @@ -508,7 +506,7 @@ bool LowEnergyConnectionManager::Connect(PeerId peer_id, // Disconnect() or other circumstances). if (!conn_ref->active()) { bt_log(TRACE, "gap-le", "link disconnected, ref is inactive"); - callback(hci::Status(common::HostError::kFailed), nullptr); + callback(hci::Status(HostError::kFailed), nullptr); } else { callback(hci::Status(), std::move(conn_ref)); } diff --git a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager.h b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager.h index 451c041181d7974c447e330fe853658c67f3739d..4b170b8edc58b42dd19bbe36debd1120c1e5a963 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager.h +++ b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager.h @@ -197,7 +197,7 @@ class LowEnergyConnectionManager final { class PendingRequestData { public: - PendingRequestData(const common::DeviceAddress& address, + PendingRequestData(const DeviceAddress& address, ConnectionResultCallback first_callback); PendingRequestData() = default; ~PendingRequestData() = default; @@ -214,10 +214,10 @@ class LowEnergyConnectionManager final { using RefFunc = fit::function<LowEnergyConnectionRefPtr()>; void NotifyCallbacks(hci::Status status, const RefFunc& func); - const common::DeviceAddress& address() const { return address_; } + const DeviceAddress& address() const { return address_; } private: - common::DeviceAddress address_; + DeviceAddress address_; std::list<ConnectionResultCallback> callbacks_; DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(PendingRequestData); diff --git a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager_unittest.cc index baa48e6624f4c03252b8bb576204aff8431561d1..7040bbf89c8f2395410dd9f068e45b3ffb5b4c62 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager_unittest.cc @@ -29,8 +29,6 @@ namespace { using bt::testing::FakeController; using bt::testing::FakePeer; -using common::DeviceAddress; - using TestingBase = bt::testing::FakeControllerTest<FakeController>; const DeviceAddress kAddress0(DeviceAddress::Type::kLEPublic, @@ -97,7 +95,7 @@ class LowEnergyConnectionManagerTest : public TestingBase { data::testing::FakeDomain* fake_l2cap() const { return l2cap_.get(); } // Addresses of currently connected fake peers. - using PeerList = std::unordered_set<common::DeviceAddress>; + using PeerList = std::unordered_set<DeviceAddress>; const PeerList& connected_peers() const { return connected_peers_; } // Addresses of peers with a canceled connection attempt. @@ -111,10 +109,10 @@ class LowEnergyConnectionManagerTest : public TestingBase { // Called by |connector_| when a new remote initiated connection is received. void OnIncomingConnection(hci::ConnectionHandle handle, hci::Connection::Role role, - const common::DeviceAddress& peer_address, + const DeviceAddress& peer_address, const hci::LEConnectionParameters& conn_params) { - common::DeviceAddress local_address(common::DeviceAddress::Type::kLEPublic, - "03:02:01:01:02:03"); + DeviceAddress local_address(DeviceAddress::Type::kLEPublic, + "03:02:01:01:02:03"); // Create a production connection object that can interact with the fake // controller. @@ -123,8 +121,8 @@ class LowEnergyConnectionManagerTest : public TestingBase { } // Called by FakeController on connection events. - void OnConnectionStateChanged(const common::DeviceAddress& address, - bool connected, bool canceled) { + void OnConnectionStateChanged(const DeviceAddress& address, bool connected, + bool canceled) { bt_log(SPEW, "gap-test", "OnConnectionStateChanged: %s connected: %s, canceled %s", address.ToString().c_str(), connected ? "true" : "false", @@ -254,7 +252,7 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, ConnectSinglePeerTimeout) { RunLoopFor(kTestRequestTimeout); EXPECT_FALSE(status); - EXPECT_EQ(common::HostError::kTimedOut, status.error()) << status.ToString(); + EXPECT_EQ(HostError::kTimedOut, status.error()) << status.ToString(); EXPECT_EQ(Peer::ConnectionState::kNotConnected, peer->le()->connection_state()); } @@ -285,7 +283,7 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, PeerDoesNotExpireDuringTimeout) { EXPECT_FALSE(peer->temporary()); RunLoopFor(kTestRequestTimeout); - EXPECT_EQ(common::HostError::kTimedOut, status.error()) << status.ToString(); + EXPECT_EQ(HostError::kTimedOut, status.error()) << status.ToString(); EXPECT_EQ(peer, peer_cache()->FindByAddress(kAddress1)); EXPECT_EQ(Peer::ConnectionState::kNotConnected, peer->le()->connection_state()); @@ -314,7 +312,7 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, conn_mgr()->set_request_timeout_for_testing(kConnectionDelay + zx::sec(1)); // Initialize as error to verify that |callback| assigns success. - hci::Status status(common::HostError::kFailed); + hci::Status status(HostError::kFailed); LowEnergyConnectionRefPtr conn_ref; auto callback = [&status, &conn_ref](auto cb_status, auto cb_conn_ref) { status = cb_status; @@ -350,7 +348,7 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, ConnectSinglePeer) { test_device()->AddPeer(std::move(fake_peer)); // Initialize as error to verify that |callback| assigns success. - hci::Status status(common::HostError::kFailed); + hci::Status status(HostError::kFailed); LowEnergyConnectionRefPtr conn_ref; auto callback = [&status, &conn_ref](auto cb_status, auto cb_conn_ref) { EXPECT_TRUE(cb_conn_ref); @@ -437,7 +435,7 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, ReleaseRef) { test_device()->AddPeer(std::move(fake_peer)); // Initialize as error to verify that |callback| assigns success. - hci::Status status(common::HostError::kFailed); + hci::Status status(HostError::kFailed); LowEnergyConnectionRefPtr conn_ref; auto callback = [&status, &conn_ref](auto cb_status, auto cb_conn_ref) { EXPECT_TRUE(cb_conn_ref); @@ -700,7 +698,7 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, Destructor) { bool error_cb_called = false; auto error_cb = [&error_cb_called](auto status, auto conn_ref) { EXPECT_FALSE(conn_ref); - EXPECT_EQ(common::HostError::kFailed, status.error()); + EXPECT_EQ(HostError::kFailed, status.error()); error_cb_called = true; }; @@ -811,7 +809,7 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, DisconnectWhileRefPending) { auto ref_cb = [](auto status, auto conn_ref) { EXPECT_FALSE(conn_ref); EXPECT_FALSE(status); - EXPECT_EQ(common::HostError::kFailed, status.error()); + EXPECT_EQ(HostError::kFailed, status.error()); }; EXPECT_TRUE(conn_mgr()->Connect(peer->identifier(), ref_cb)); @@ -847,7 +845,7 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, DisconnectEventWhileRefPending) { auto ref_cb = [](auto status, auto conn_ref) { EXPECT_FALSE(conn_ref); EXPECT_FALSE(status); - EXPECT_EQ(common::HostError::kFailed, status.error()); + EXPECT_EQ(HostError::kFailed, status.error()); }; auto disconn_cb = [this, ref_cb, peer](auto) { diff --git a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager.cc b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager.cc index 7880306a9478b4ad379001e6ce3c0bc2414c2894..d27b955683f1322ea4400fd1637ef02c6a318fc8 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager.cc @@ -177,7 +177,7 @@ void LowEnergyDiscoveryManager::RemoveSession( } void LowEnergyDiscoveryManager::OnPeerFound( - const hci::LowEnergyScanResult& result, const common::ByteBuffer& data) { + const hci::LowEnergyScanResult& result, const ByteBuffer& data) { ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); // Ignore regular scan results during a passive scan. diff --git a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager.h b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager.h index e827e91cbc092edfcf4f97cef56cf96e615bca35..56424dc990d9b183186df0eacac5f855569d5f24 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager.h +++ b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager.h @@ -85,10 +85,10 @@ class PeerCache; // // // Only scan for peers advertising the "Heart Rate" GATT Service. // uint16_t uuid = 0x180d; -// session->filter()->set_service_uuids({bt::common::UUID(uuid)}); +// session->filter()->set_service_uuids({bt::UUID(uuid)}); // session->SetResultCallback([](const // bt::hci::LowEnergyScanResult& result, -// const bt::common::ByteBuffer& +// const bt::ByteBuffer& // advertising_data) { // // Do stuff with |result| and |advertising_data|. (|advertising_data| // // contains any received Scan Response data as well). @@ -224,7 +224,7 @@ class LowEnergyDiscoveryManager final : public hci::LowEnergyScanner::Delegate { // hci::LowEnergyScanner::Delegate override: void OnPeerFound(const hci::LowEnergyScanResult& result, - const common::ByteBuffer& data) override; + const ByteBuffer& data) override; void OnDirectedAdvertisement(const hci::LowEnergyScanResult& result) override; // Called by hci::LowEnergyScanner diff --git a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager_unittest.cc index 1c44f7844a8e9107c74326a3cc1fa6be887e5f52..a2cb13284821712a97c1f3229137205202888761 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager_unittest.cc @@ -25,8 +25,6 @@ namespace { using bt::testing::FakeController; using bt::testing::FakePeer; -using common::DeviceAddress; - using TestingBase = bt::testing::FakeControllerTest<FakeController>; const DeviceAddress kAddress0(DeviceAddress::Type::kLEPublic, @@ -138,7 +136,7 @@ class LowEnergyDiscoveryManagerTest : public TestingBase { // - Not discoverable; void AddFakePeers() { // Peer 0 - const auto kAdvData0 = common::CreateStaticByteBuffer( + const auto kAdvData0 = CreateStaticByteBuffer( // Flags 0x02, 0x01, 0x02, @@ -152,7 +150,7 @@ class LowEnergyDiscoveryManagerTest : public TestingBase { test_device()->AddPeer(std::move(fake_peer)); // Peer 1 - const auto kAdvData1 = common::CreateStaticByteBuffer( + const auto kAdvData1 = CreateStaticByteBuffer( // Flags 0x02, 0x01, 0x01, @@ -163,7 +161,7 @@ class LowEnergyDiscoveryManagerTest : public TestingBase { test_device()->AddPeer(std::move(fake_peer)); // Peer 2 - const auto kAdvData2 = common::CreateStaticByteBuffer( + const auto kAdvData2 = CreateStaticByteBuffer( // Flags 0x02, 0x01, 0x02, @@ -174,7 +172,7 @@ class LowEnergyDiscoveryManagerTest : public TestingBase { test_device()->AddPeer(std::move(fake_peer)); // Peer 3 - const auto kAdvData3 = common::CreateStaticByteBuffer( + const auto kAdvData3 = CreateStaticByteBuffer( // Flags 0x02, 0x01, 0x00, @@ -621,7 +619,7 @@ TEST_F(GAP_LowEnergyDiscoveryManagerTest, StartDiscoveryWithFilters) { discovery_manager()->set_scan_period(zx::msec(200)); // Session 0 is interested in performing general discovery. - std::unordered_set<common::DeviceAddress> peers_session0; + std::unordered_set<DeviceAddress> peers_session0; LowEnergyDiscoverySession::PeerFoundCallback result_cb = [&peers_session0](const auto& peer) { peers_session0.insert(peer.address()); @@ -631,7 +629,7 @@ TEST_F(GAP_LowEnergyDiscoveryManagerTest, StartDiscoveryWithFilters) { sessions[0]->SetResultCallback(std::move(result_cb)); // Session 1 is interested in performing limited discovery. - std::unordered_set<common::DeviceAddress> peers_session1; + std::unordered_set<DeviceAddress> peers_session1; result_cb = [&peers_session1](const auto& peer) { peers_session1.insert(peer.address()); }; @@ -641,18 +639,18 @@ TEST_F(GAP_LowEnergyDiscoveryManagerTest, StartDiscoveryWithFilters) { sessions[1]->SetResultCallback(std::move(result_cb)); // Session 2 is interested in peers with UUID 0x180d. - std::unordered_set<common::DeviceAddress> peers_session2; + std::unordered_set<DeviceAddress> peers_session2; result_cb = [&peers_session2](const auto& peer) { peers_session2.insert(peer.address()); }; sessions.push_back(StartDiscoverySession()); uint16_t uuid = 0x180d; - sessions[2]->filter()->set_service_uuids({common::UUID(uuid)}); + sessions[2]->filter()->set_service_uuids({UUID(uuid)}); sessions[2]->SetResultCallback(std::move(result_cb)); // Session 3 is interested in peers whose names contain "Device". - std::unordered_set<common::DeviceAddress> peers_session3; + std::unordered_set<DeviceAddress> peers_session3; result_cb = [&peers_session3](const auto& peer) { peers_session3.insert(peer.address()); }; @@ -661,7 +659,7 @@ TEST_F(GAP_LowEnergyDiscoveryManagerTest, StartDiscoveryWithFilters) { sessions[3]->SetResultCallback(std::move(result_cb)); // Session 4 is interested in non-connectable peers. - std::unordered_set<common::DeviceAddress> peers_session4; + std::unordered_set<DeviceAddress> peers_session4; result_cb = [&peers_session4](const auto& peer) { peers_session4.insert(peer.address()); }; @@ -718,7 +716,7 @@ TEST_F(GAP_LowEnergyDiscoveryManagerTest, discovery_manager()->set_scan_period(zx::sec(20)); // Session 0 is interested in performing general discovery. - std::unordered_set<common::DeviceAddress> peers_session0; + std::unordered_set<DeviceAddress> peers_session0; LowEnergyDiscoverySession::PeerFoundCallback result_cb = [this, &peers_session0](const auto& peer) { peers_session0.insert(peer.address()); @@ -731,7 +729,7 @@ TEST_F(GAP_LowEnergyDiscoveryManagerTest, ASSERT_EQ(3u, peers_session0.size()); // Session 1 is interested in performing limited discovery. - std::unordered_set<common::DeviceAddress> peers_session1; + std::unordered_set<DeviceAddress> peers_session1; result_cb = [&peers_session1](const auto& peer) { peers_session1.insert(peer.address()); }; @@ -741,18 +739,18 @@ TEST_F(GAP_LowEnergyDiscoveryManagerTest, sessions[1]->SetResultCallback(std::move(result_cb)); // Session 2 is interested in peers with UUID 0x180d. - std::unordered_set<common::DeviceAddress> peers_session2; + std::unordered_set<DeviceAddress> peers_session2; result_cb = [&peers_session2](const auto& peer) { peers_session2.insert(peer.address()); }; sessions.push_back(StartDiscoverySession()); uint16_t uuid = 0x180d; - sessions[2]->filter()->set_service_uuids({common::UUID(uuid)}); + sessions[2]->filter()->set_service_uuids({UUID(uuid)}); sessions[2]->SetResultCallback(std::move(result_cb)); // Session 3 is interested in peers whose names contain "Device". - std::unordered_set<common::DeviceAddress> peers_session3; + std::unordered_set<DeviceAddress> peers_session3; result_cb = [&peers_session3](const auto& peer) { peers_session3.insert(peer.address()); }; @@ -761,7 +759,7 @@ TEST_F(GAP_LowEnergyDiscoveryManagerTest, sessions[3]->SetResultCallback(std::move(result_cb)); // Session 4 is interested in non-connectable peers. - std::unordered_set<common::DeviceAddress> peers_session4; + std::unordered_set<DeviceAddress> peers_session4; result_cb = [&peers_session4](const auto& peer) { peers_session4.insert(peer.address()); }; @@ -847,7 +845,7 @@ TEST_F(GAP_LowEnergyDiscoveryManagerTest, discovery_manager()->set_scan_period(kTestScanPeriod); - std::unordered_set<common::DeviceAddress> addresses_found; + std::unordered_set<DeviceAddress> addresses_found; LowEnergyDiscoverySession::PeerFoundCallback result_cb = [&addresses_found](const auto& peer) { addresses_found.insert(peer.address()); diff --git a/src/connectivity/bluetooth/core/bt-host/gap/peer.cc b/src/connectivity/bluetooth/core/bt-host/gap/peer.cc index bebcfd8c2f9a3ff3cf734f770a14427676c09c22..ba82d46f62bc031665df775e42bb789338346bae 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/peer.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/peer.cc @@ -13,11 +13,6 @@ namespace bt { -using common::BufferView; -using common::ByteBuffer; -using common::DeviceAddress; -using common::DynamicByteBuffer; - namespace gap { namespace { @@ -45,7 +40,7 @@ Peer::LowEnergyData::LowEnergyData(Peer* owner) } void Peer::LowEnergyData::SetAdvertisingData(int8_t rssi, - const common::ByteBuffer& adv) { + const ByteBuffer& adv) { // Prolong this peer's expiration in case it is temporary. peer_->UpdateExpiry(); @@ -216,9 +211,9 @@ void Peer::BrEdrData::SetConnectionState(ConnectionState state) { } void Peer::BrEdrData::SetInquiryData( - common::DeviceClass device_class, uint16_t clock_offset, + DeviceClass device_class, uint16_t clock_offset, hci::PageScanRepetitionMode page_scan_rep_mode, int8_t rssi, - const common::BufferView& eir_data) { + const BufferView& eir_data) { peer_->UpdateExpiry(); bool notify_listeners = false; @@ -245,7 +240,7 @@ void Peer::BrEdrData::SetInquiryData( } } -bool Peer::BrEdrData::SetEirData(const common::ByteBuffer& eir) { +bool Peer::BrEdrData::SetEirData(const ByteBuffer& eir) { ZX_DEBUG_ASSERT(eir.size()); // TODO(armansito): Validate that the EIR data is not malformed? @@ -258,7 +253,7 @@ bool Peer::BrEdrData::SetEirData(const common::ByteBuffer& eir) { // TODO(jamuraa): maybe rename this class? AdvertisingDataReader reader(eir); gap::DataType type; - common::BufferView data; + BufferView data; bool changed = false; while (reader.GetNextField(&type, &data)) { if (type == gap::DataType::kCompleteLocalName) { diff --git a/src/connectivity/bluetooth/core/bt-host/gap/peer.h b/src/connectivity/bluetooth/core/bt-host/gap/peer.h index 6af19bebbb0d9e62f0c9bf2fc42274e31c03f7b3..f5c7d19d5799ee1463945b2a1588c472f8a7bb3c 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/peer.h +++ b/src/connectivity/bluetooth/core/bt-host/gap/peer.h @@ -59,7 +59,7 @@ class Peer final { // Advertising (and optionally scan response) data obtained during // discovery. - const common::BufferView advertising_data() const { + const BufferView advertising_data() const { return adv_data_buffer_.view(0, adv_data_len_); } @@ -87,7 +87,7 @@ class Peer final { // |rssi| corresponds to the most recent advertisement RSSI. // |advertising_data| should include any scan response data if obtained // during an active scan. - void SetAdvertisingData(int8_t rssi, const common::ByteBuffer& data); + void SetAdvertisingData(int8_t rssi, const ByteBuffer& data); // Updates the connection state and notifies listeners if necessary. void SetConnectionState(ConnectionState state); @@ -115,7 +115,7 @@ class Peer final { ConnectionState conn_state_; size_t adv_data_len_; - common::DynamicByteBuffer adv_data_buffer_; + DynamicByteBuffer adv_data_buffer_; std::optional<hci::LEConnectionParameters> conn_params_; std::optional<hci::LEPreferredConnectionParameters> preferred_conn_params_; @@ -138,10 +138,10 @@ class Peer final { bool bonded() const { return link_key_.has_value(); } // Returns the peer's BD_ADDR. - const common::DeviceAddress& address() const { return address_; } + const DeviceAddress& address() const { return address_; } // Returns the device class reported by the peer, if it is known. - const std::optional<common::DeviceClass>& device_class() const { + const std::optional<DeviceClass>& device_class() const { return device_class_; } @@ -158,7 +158,7 @@ class Peer final { const std::optional<uint16_t>& clock_offset() const { return clock_offset_; } - const common::BufferView extended_inquiry_response() const { + const BufferView extended_inquiry_response() const { return eir_buffer_.view(0, eir_len_); } @@ -192,24 +192,23 @@ class Peer final { private: // All multi-byte fields must be in little-endian byte order as they were // received from the controller. - void SetInquiryData( - common::DeviceClass device_class, uint16_t clock_offset, - hci::PageScanRepetitionMode page_scan_rep_mode, - int8_t rssi = hci::kRSSIInvalid, - const common::BufferView& eir_data = common::BufferView()); + void SetInquiryData(DeviceClass device_class, uint16_t clock_offset, + hci::PageScanRepetitionMode page_scan_rep_mode, + int8_t rssi = hci::kRSSIInvalid, + const BufferView& eir_data = BufferView()); // Updates the EIR data field and returns true if any properties changed. - bool SetEirData(const common::ByteBuffer& data); + bool SetEirData(const ByteBuffer& data); Peer* peer_; // weak ConnectionState conn_state_; - common::DeviceAddress address_; - std::optional<common::DeviceClass> device_class_; + DeviceAddress address_; + std::optional<DeviceClass> device_class_; std::optional<hci::PageScanRepetitionMode> page_scan_rep_mode_; std::optional<uint16_t> clock_offset_; // TODO(jamuraa): Parse more of the Extended Inquiry Response fields size_t eir_len_; - common::DynamicByteBuffer eir_buffer_; + DynamicByteBuffer eir_buffer_; std::optional<sm::LTK> link_key_; // TODO(armansito): Store traditional service UUIDs. @@ -243,7 +242,7 @@ class Peer final { // If a BR/EDR/LE device uses an identity address that is different from // its BD_ADDR, then there will be two separate Peer entries for // it. - const common::DeviceAddress& address() const { return address_; } + const DeviceAddress& address() const { return address_; } bool identity_known() const { return identity_known_; } // The LMP version of this device obtained doing discovery. @@ -341,8 +340,7 @@ class Peer final { // (do the callbacks outlive |this|?). Peer(DeviceCallback notify_listeners_callback, DeviceCallback update_expiry_callback, DeviceCallback dual_mode_callback, - PeerId identifier, const common::DeviceAddress& address, - bool connectable); + PeerId identifier, const DeviceAddress& address, bool connectable); // Marks this device's identity as known. Called by PeerCache when // initializing a bonded device and by LowEnergyData when setting bond data @@ -351,7 +349,7 @@ class Peer final { // Assigns a new value for the address of this device. Called by LowEnergyData // when a new identity address is assigned. - void set_address(const common::DeviceAddress& address) { address_ = address; } + void set_address(const DeviceAddress& address) { address_ = address; } // Updates the RSSI and returns true if it changed. bool SetRssiInternal(int8_t rssi); @@ -388,7 +386,7 @@ class Peer final { PeerId identifier_; TechnologyType technology_; - common::DeviceAddress address_; + DeviceAddress address_; bool identity_known_; std::optional<std::string> name_; diff --git a/src/connectivity/bluetooth/core/bt-host/gap/peer_cache.cc b/src/connectivity/bluetooth/core/bt-host/gap/peer_cache.cc index 8dda2d72555614a77cb0bcdc1d1f5b2b24cba6e3..17478d55a8c2559ec3230c6f0f51a743ff786bce 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/peer_cache.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/peer_cache.cc @@ -16,8 +16,6 @@ namespace bt { namespace gap { -using common::DeviceAddress; - namespace { // Return an address with the same value as given, but with type kBREDR for @@ -35,8 +33,7 @@ DeviceAddress GetAliasAddress(const DeviceAddress& address) { Peer* PeerCache::NewPeer(const DeviceAddress& address, bool connectable) { ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); - auto* const peer = - InsertPeerRecord(common::RandomPeerId(), address, connectable); + auto* const peer = InsertPeerRecord(RandomPeerId(), address, connectable); if (peer) { UpdateExpiry(*peer); NotifyPeerUpdated(*peer); @@ -169,10 +166,10 @@ bool PeerCache::StoreLowEnergyBond(PeerId identifier, return true; } -bool PeerCache::StoreBrEdrBond(const common::DeviceAddress& address, +bool PeerCache::StoreBrEdrBond(const DeviceAddress& address, const sm::LTK& link_key) { ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); - ZX_DEBUG_ASSERT(address.type() == common::DeviceAddress::Type::kBREDR); + ZX_DEBUG_ASSERT(address.type() == DeviceAddress::Type::kBREDR); auto* peer = FindByAddress(address); if (!peer) { bt_log(TRACE, "gap-bredr", "failed to store bond for unknown peer: %s", @@ -263,7 +260,7 @@ Peer* PeerCache::FindByAddress(const DeviceAddress& in_address) const { // Private methods below. Peer* PeerCache::InsertPeerRecord(PeerId identifier, - const common::DeviceAddress& address, + const DeviceAddress& address, bool connectable) { if (FindIdByAddress(address)) { bt_log(WARN, "gap", "tried to insert peer with existing address: %s", @@ -367,7 +364,7 @@ void PeerCache::RemovePeer(Peer* peer) { } std::optional<PeerId> PeerCache::FindIdByAddress( - const common::DeviceAddress& address) const { + const DeviceAddress& address) const { auto iter = address_map_.find(address); if (iter == address_map_.end()) { // Search again using the other technology's address. This is necessary when diff --git a/src/connectivity/bluetooth/core/bt-host/gap/peer_cache.h b/src/connectivity/bluetooth/core/bt-host/gap/peer_cache.h index e81d15d2586de2796515975ae7bcf7ffddaadf50..76985754531f07a7d156adc6e323a456fc8e7ef3 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/peer_cache.h +++ b/src/connectivity/bluetooth/core/bt-host/gap/peer_cache.h @@ -20,9 +20,7 @@ namespace bt { -namespace common { class ByteBuffer; -} // namespace common namespace hci { struct LowEnergyScanResult; @@ -46,7 +44,7 @@ class PeerCache final { // // Returns nullptr if an entry matching |address| already exists in the cache, // including as a public identity of a peer with a different technology. - Peer* NewPeer(const common::DeviceAddress& address, bool connectable); + Peer* NewPeer(const DeviceAddress& address, bool connectable); // Iterates over all current peers in the map, running |f| on each entry // synchronously. This is intended for IPC methods that request a list of @@ -71,7 +69,7 @@ class PeerCache final { // should be instead updated with new bond information to create a dual-mode // peer. // - bool AddBondedPeer(PeerId identifier, const common::DeviceAddress& address, + bool AddBondedPeer(PeerId identifier, const DeviceAddress& address, const sm::PairingData& bond_data, const std::optional<sm::LTK>& link_key); @@ -92,8 +90,7 @@ class PeerCache final { // The peer will be considered "bonded" and the bonded callback notified. If // the peer is already bonded then the link key will be updated. Returns // false if the address does not match that of a known peer. - bool StoreBrEdrBond(const common::DeviceAddress& address, - const sm::LTK& link_key); + bool StoreBrEdrBond(const DeviceAddress& address, const sm::LTK& link_key); // Resets a peer |peer_id| to an unbonded state by removing secrets for its // transports. The peer will become temporary and may expire. This does not @@ -112,7 +109,7 @@ class PeerCache final { // returns nullptr otherwise. Tries to resolve |address| if it is resolvable. // If |address| is of type kBREDR or kLEPublic, then this searches for peers // that have either type of address. - Peer* FindByAddress(const common::DeviceAddress& address) const; + Peer* FindByAddress(const DeviceAddress& address) const; // When set, |callback| will be invoked whenever a peer is added or updated. void set_peer_updated_callback(PeerCallback callback) { @@ -165,8 +162,7 @@ class PeerCache final { // |address|, and connectability (|connectable|). Returns a pointer to the // inserted peer or nullptr if |identifier| or |address| already exists in // the cache. - Peer* InsertPeerRecord(PeerId identifier, - const common::DeviceAddress& address, + Peer* InsertPeerRecord(PeerId identifier, const DeviceAddress& address, bool connectable); // Notifies interested parties that |peer| has bonded @@ -195,8 +191,7 @@ class PeerCache final { // technologies if it is a public address. |address| should be already // resolved, if it is resolvable. If found, returns a valid peer ID; // otherwise returns std::nullopt. - std::optional<PeerId> FindIdByAddress( - const common::DeviceAddress& address) const; + std::optional<PeerId> FindIdByAddress(const DeviceAddress& address) const; // Mapping from unique peer IDs to PeerRecords. // Owns the corresponding Peers. @@ -209,7 +204,7 @@ class PeerCache final { // // Dual-mode peers shall have identity addresses of both technologies // mapped to the same ID, if the addresses have the same value. - std::unordered_map<common::DeviceAddress, PeerId> address_map_; + std::unordered_map<DeviceAddress, PeerId> address_map_; // The LE identity resolving list used to resolve RPAs. IdentityResolvingList le_resolving_list_; diff --git a/src/connectivity/bluetooth/core/bt-host/gap/peer_cache_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gap/peer_cache_unittest.cc index 403dc3753277acdb559bb8af8185e8b9a0eee2c7..a9524e3a6a58339a05541f2896797e52337abd10 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/peer_cache_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/peer_cache_unittest.cc @@ -18,11 +18,6 @@ namespace bt { namespace gap { namespace { -using common::CreateStaticByteBuffer; -using common::DeviceAddress; -using common::MutableBufferView; -using common::StaticByteBuffer; - // All fields are initialized to zero as they are unused in these tests. const hci::LEConnectionParameters kTestParams; @@ -60,7 +55,7 @@ const bt::sm::Key kKey{}; const bt::sm::LTK kBrEdrKey; // Phone (Networking) -const common::DeviceClass kTestDeviceClass({0x06, 0x02, 0x02}); +const DeviceClass kTestDeviceClass({0x06, 0x02, 0x02}); class GAP_PeerCacheTest : public ::gtest::TestLoopFixture { public: @@ -122,13 +117,11 @@ TEST_F(GAP_PeerCacheTest, LookUp) { EXPECT_FALSE(cache()->NewPeer(kAddrLePublic, true)); peer->MutLe().SetAdvertisingData(kTestRSSI, kAdvData1); - EXPECT_TRUE( - common::ContainersEqual(kAdvData1, peer->le()->advertising_data())); + EXPECT_TRUE(ContainersEqual(kAdvData1, peer->le()->advertising_data())); EXPECT_EQ(kTestRSSI, peer->rssi()); peer->MutLe().SetAdvertisingData(kTestRSSI, kAdvData0); - EXPECT_TRUE( - common::ContainersEqual(kAdvData0, peer->le()->advertising_data())); + EXPECT_TRUE(ContainersEqual(kAdvData0, peer->le()->advertising_data())); EXPECT_EQ(kTestRSSI, peer->rssi()); } @@ -470,7 +463,7 @@ TEST_F(GAP_PeerCacheTest_BondingTest, AddBondedPeerWithIrkIsAddedToResolvingList) { sm::PairingData data; data.ltk = kLTK; - data.irk = sm::Key(sm::SecurityProperties(), common::RandomUInt128()); + data.irk = sm::Key(sm::SecurityProperties(), RandomUInt128()); EXPECT_TRUE(cache()->AddBondedPeer(kId, kAddrLeRandom, data, {})); auto* peer = cache()->FindByAddress(kAddrLeRandom); @@ -604,7 +597,7 @@ TEST_F(GAP_PeerCacheTest_BondingTest, sm::PairingData data; data.ltk = kLTK; data.identity_address = kAddrLeRandom; - data.irk = sm::Key(sm::SecurityProperties(), common::RandomUInt128()); + data.irk = sm::Key(sm::SecurityProperties(), RandomUInt128()); EXPECT_TRUE(cache()->StoreLowEnergyBond(peer()->identifier(), data)); ASSERT_TRUE(peer()->le()->bonded()); @@ -709,7 +702,7 @@ TEST_F(GAP_PeerCacheTest_BondingTest, ForgetLowEnergyPeerWithIrk) { sm::PairingData data; data.ltk = kLTK; data.identity_address = kAddrLeAlias; - data.irk = sm::Key(sm::SecurityProperties(), common::RandomUInt128()); + data.irk = sm::Key(sm::SecurityProperties(), RandomUInt128()); DeviceAddress rpa = sm::util::GenerateRpa(data.irk->value()); ASSERT_TRUE(cache()->StoreLowEnergyBond(peer()->identifier(), data)); @@ -745,7 +738,7 @@ TEST_F(GAP_PeerCacheTest_BondingTest, sm::PairingData data; data.ltk = kLTK; data.identity_address = kAddrLeAlias; - data.irk = sm::Key(sm::SecurityProperties(), common::RandomUInt128()); + data.irk = sm::Key(sm::SecurityProperties(), RandomUInt128()); ASSERT_TRUE(cache()->StoreLowEnergyBond(peer()->identifier(), data)); peer()->MutLe().SetConnectionState(Peer::ConnectionState::kConnected); @@ -883,8 +876,8 @@ TEST_F(GAP_PeerCacheTest_LowEnergyUpdateCallbackTest, ASSERT_NE(peer()->rssi(), kTestRSSI); cache()->set_peer_updated_callback([&](const auto& updated_peer) { ASSERT_TRUE(updated_peer.le()); - EXPECT_TRUE(common::ContainersEqual(kAdvData, - updated_peer.le()->advertising_data())); + EXPECT_TRUE( + ContainersEqual(kAdvData, updated_peer.le()->advertising_data())); EXPECT_EQ(updated_peer.rssi(), kTestRSSI); }); peer()->MutLe().SetAdvertisingData(kTestRSSI, kAdvData); @@ -949,7 +942,7 @@ TEST_F(GAP_PeerCacheTest_BrEdrUpdateCallbackTest, cache()->set_peer_updated_callback([](const auto& updated_peer) { ASSERT_TRUE(updated_peer.bredr()); ASSERT_TRUE(updated_peer.bredr()->device_class()); - EXPECT_EQ(common::DeviceClass::MajorClass(0x02), + EXPECT_EQ(DeviceClass::MajorClass(0x02), updated_peer.bredr()->device_class()->major_class()); }); peer()->MutBrEdr().SetInquiryData(ir()); @@ -981,7 +974,7 @@ TEST_F( irr().class_of_device = kTestDeviceClass; cache()->set_peer_updated_callback([](const auto& updated_peer) { ASSERT_TRUE(updated_peer.bredr()->device_class()); - EXPECT_EQ(common::DeviceClass::MajorClass(0x02), + EXPECT_EQ(DeviceClass::MajorClass(0x02), updated_peer.bredr()->device_class()->major_class()); }); peer()->MutBrEdr().SetInquiryData(irr()); @@ -1053,7 +1046,7 @@ TEST_F( EXPECT_EQ(*data->clock_offset(), 0x8001); EXPECT_EQ(*data->page_scan_repetition_mode(), hci::PageScanRepetitionMode::kR1); - EXPECT_EQ(common::DeviceClass::MajorClass(0x02), + EXPECT_EQ(DeviceClass::MajorClass(0x02), updated_peer.bredr()->device_class()->major_class()); EXPECT_EQ(updated_peer.rssi(), kTestRSSI); EXPECT_EQ(*updated_peer.name(), "Test"); @@ -1177,15 +1170,15 @@ class GAP_PeerCacheExpirationTest : public ::gtest::TestLoopFixture { return cache_.FindByAddress(peer_addr_alias_); } bool IsDefaultPeerPresent() { return GetDefaultPeer(); } - Peer* NewPeer(const common::DeviceAddress& address, bool connectable) { + Peer* NewPeer(const DeviceAddress& address, bool connectable) { return cache_.NewPeer(address, connectable); } int peers_removed() const { return peers_removed_; } private: PeerCache cache_; - common::DeviceAddress peer_addr_; - common::DeviceAddress peer_addr_alias_; + DeviceAddress peer_addr_; + DeviceAddress peer_addr_alias_; PeerId peer_id_; int peers_removed_; }; diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/client.cc b/src/connectivity/bluetooth/core/bt-host/gatt/client.cc index a77f3bb732e37491288895b21bf3fc6efbbc6a72..ca503f150137919a1afa562d5f1e7e204b2b3b51 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/client.cc +++ b/src/connectivity/bluetooth/core/bt-host/gatt/client.cc @@ -10,19 +10,17 @@ #include "src/connectivity/bluetooth/core/bt-host/common/log.h" #include "src/connectivity/bluetooth/core/bt-host/common/slab_allocator.h" -using bt::common::HostError; +using bt::HostError; namespace bt { using att::StatusCallback; -using common::BufferView; -using common::HostError; namespace gatt { namespace { -common::MutableByteBufferPtr NewPDU(size_t param_size) { - auto pdu = common::NewSlabBuffer(sizeof(att::Header) + param_size); +MutableByteBufferPtr NewPDU(size_t param_size) { + auto pdu = NewSlabBuffer(sizeof(att::Header) + param_size); if (!pdu) { bt_log(TRACE, "att", "out of memory"); } @@ -65,7 +63,7 @@ bool ProcessDescriptorDiscoveryResponse( } last_handle = desc.handle; - desc.type = common::UUID(entry.uuid); + desc.type = UUID(entry.uuid); // Notify the handler. desc_callback(desc); @@ -279,7 +277,7 @@ class Impl final : public Client { BufferView value(entry.value, entry_length - (2 * sizeof(att::Handle))); // This must succeed as we have performed the appropriate checks above. - __UNUSED bool result = common::UUID::FromBytes(value, &service.type); + __UNUSED bool result = UUID::FromBytes(value, &service.type); ZX_DEBUG_ASSERT(result); // Notify the handler. @@ -431,8 +429,7 @@ class Impl final : public Client { // This must succeed as we have performed the necessary checks // above. - __UNUSED bool result = - common::UUID::FromBytes(value.view(3), &chrc.type); + __UNUSED bool result = UUID::FromBytes(value.view(3), &chrc.type); ZX_DEBUG_ASSERT(result); // Notify the handler. @@ -622,7 +619,7 @@ class Impl final : public Client { } } - void WriteRequest(att::Handle handle, const common::ByteBuffer& value, + void WriteRequest(att::Handle handle, const ByteBuffer& value, StatusCallback callback) override { const size_t payload_size = sizeof(att::WriteRequestParams) + value.size(); if (sizeof(att::OpCode) + payload_size > att_->mtu()) { @@ -673,7 +670,7 @@ class Impl final : public Client { } void WriteWithoutResponse(att::Handle handle, - const common::ByteBuffer& value) override { + const ByteBuffer& value) override { const size_t payload_size = sizeof(att::WriteRequestParams) + value.size(); if (sizeof(att::OpCode) + payload_size > att_->mtu()) { bt_log(SPEW, "gatt", "write request payload exceeds MTU"); diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/client.h b/src/connectivity/bluetooth/core/bt-host/gatt/client.h index 9f816983e7e478e544e8ab17343ca757afea2022..3be7a6e0b06451bb6a28812d23c4b22f831e3ce6 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/client.h +++ b/src/connectivity/bluetooth/core/bt-host/gatt/client.h @@ -89,8 +89,7 @@ class Client { // // Reports the status of the procedure and the resulting value in |callback|. // Returns an empty buffer if the status is an error. - using ReadCallback = - fit::function<void(att::Status, const common::ByteBuffer&)>; + using ReadCallback = fit::function<void(att::Status, const ByteBuffer&)>; virtual void ReadRequest(att::Handle handle, ReadCallback callback) = 0; // Sends an ATT Read Blob request with the requested attribute |handle| and @@ -107,19 +106,19 @@ class Client { // Reports the status of the procedure in |callback|. // HostError::kPacketMalformed is returned if |value| is too large to write in // a single ATT request. - virtual void WriteRequest(att::Handle handle, const common::ByteBuffer& value, + virtual void WriteRequest(att::Handle handle, const ByteBuffer& value, att::StatusCallback callback) = 0; // Sends an ATT Write Command with the requested |handle| and |value|. This // should only be used with characteristics that support the "Write Without // Response" property. virtual void WriteWithoutResponse(att::Handle handle, - const common::ByteBuffer& value) = 0; + const ByteBuffer& value) = 0; // Assigns a callback that will be called when a notification or indication // PDU is received. using NotificationCallback = fit::function<void( - bool indication, att::Handle handle, const common::ByteBuffer& value)>; + bool indication, att::Handle handle, const ByteBuffer& value)>; virtual void SetNotificationHandler(NotificationCallback handler) = 0; }; diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/client_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gatt/client_unittest.cc index e86893f3796c5e328ce28c280bf4e70fff2af21a..69fd36cfaee2839290a05468c2f7707d9888eb8f 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/client_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/gatt/client_unittest.cc @@ -11,20 +11,13 @@ namespace bt { namespace gatt { namespace { -using common::ByteBuffer; -using common::ContainersEqual; -using common::CreateStaticByteBuffer; -using common::HostError; -using common::LowerBits; -using common::UpperBits; - -constexpr common::UUID kTestUuid1((uint16_t)0xDEAD); -constexpr common::UUID kTestUuid2((uint16_t)0xBEEF); -constexpr common::UUID kTestUuid3({0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, - 14, 15}); +constexpr UUID kTestUuid1((uint16_t)0xDEAD); +constexpr UUID kTestUuid2((uint16_t)0xBEEF); +constexpr UUID kTestUuid3({0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15}); // clang-format off -const auto kDiscoverAllPrimaryRequest = common::CreateStaticByteBuffer( +const auto kDiscoverAllPrimaryRequest = CreateStaticByteBuffer( 0x10, // opcode: read by group type request 0x01, 0x00, // start handle: 0x0001 0xFF, 0xFF, // end handle: 0xFFFF @@ -71,7 +64,7 @@ class GATT_ClientTest : public l2cap::testing::FakeChannelTest { // given handles bool ExpectFindInformation(att::Handle range_start = 0x0001, att::Handle range_end = 0xFFFF) { - return Expect(common::CreateStaticByteBuffer( + return Expect(CreateStaticByteBuffer( 0x04, // opcode LowerBits(range_start), UpperBits(range_start), // start handle LowerBits(range_end), UpperBits(range_end) // end hanle @@ -92,7 +85,7 @@ class GATT_ClientTest : public l2cap::testing::FakeChannelTest { TEST_F(GATT_ClientTest, ExchangeMTUMalformedResponse) { constexpr uint16_t kPreferredMTU = 100; - const auto kExpectedRequest = common::CreateStaticByteBuffer( + const auto kExpectedRequest = CreateStaticByteBuffer( 0x02, // opcode: exchange MTU kPreferredMTU, 0x00 // client rx mtu: kPreferredMTU ); @@ -116,7 +109,7 @@ TEST_F(GATT_ClientTest, ExchangeMTUMalformedResponse) { // Respond back with a malformed PDU. This should cause a link error and the // MTU request should fail. - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x03, // opcode: exchange MTU response 30 // server rx mtu is one octet too short )); @@ -132,7 +125,7 @@ TEST_F(GATT_ClientTest, ExchangeMTUMalformedResponse) { TEST_F(GATT_ClientTest, ExchangeMTUErrorNotSupported) { constexpr uint16_t kPreferredMTU = 100; constexpr uint16_t kInitialMTU = 50; - const auto kExpectedRequest = common::CreateStaticByteBuffer( + const auto kExpectedRequest = CreateStaticByteBuffer( 0x02, // opcode: exchange MTU kPreferredMTU, 0x00 // client rx mtu: kPreferredMTU ); @@ -157,7 +150,7 @@ TEST_F(GATT_ClientTest, ExchangeMTUErrorNotSupported) { // Respond with "Request Not Supported". This will cause us to switch to the // default MTU. - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x01, // opcode: error response 0x02, // request: exchange MTU 0x00, 0x00, // handle: 0 @@ -174,7 +167,7 @@ TEST_F(GATT_ClientTest, ExchangeMTUErrorNotSupported) { TEST_F(GATT_ClientTest, ExchangeMTUErrorOther) { constexpr uint16_t kPreferredMTU = 100; - const auto kExpectedRequest = common::CreateStaticByteBuffer( + const auto kExpectedRequest = CreateStaticByteBuffer( 0x02, // opcode: exchange MTU kPreferredMTU, 0x00 // client rx mtu: kPreferredMTU ); @@ -196,12 +189,11 @@ TEST_F(GATT_ClientTest, ExchangeMTUErrorOther) { ASSERT_TRUE(Expect(kExpectedRequest)); // Respond with an error. The MTU should remain unchanged. - fake_chan()->Receive(common::CreateStaticByteBuffer( - 0x01, // opcode: error response - 0x02, // request: exchange MTU - 0x00, 0x00, // handle: 0 - 0x0E // error: Unlikely Error - )); + fake_chan()->Receive(CreateStaticByteBuffer(0x01, // opcode: error response + 0x02, // request: exchange MTU + 0x00, 0x00, // handle: 0 + 0x0E // error: Unlikely Error + )); RunLoopUntilIdle(); @@ -215,7 +207,7 @@ TEST_F(GATT_ClientTest, ExchangeMTUSelectLocal) { constexpr uint16_t kPreferredMTU = 100; constexpr uint16_t kServerRxMTU = kPreferredMTU + 1; - const auto kExpectedRequest = common::CreateStaticByteBuffer( + const auto kExpectedRequest = CreateStaticByteBuffer( 0x02, // opcode: exchange MTU kPreferredMTU, 0x00 // client rx mtu: kPreferredMTU ); @@ -237,7 +229,7 @@ TEST_F(GATT_ClientTest, ExchangeMTUSelectLocal) { ASSERT_EQ(att::kLEMinMTU, att()->mtu()); // Respond with an error. The MTU should remain unchanged. - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x03, // opcode: exchange MTU response kServerRxMTU, 0x00 // server rx mtu )); @@ -254,7 +246,7 @@ TEST_F(GATT_ClientTest, ExchangeMTUSelectRemote) { constexpr uint16_t kPreferredMTU = 100; constexpr uint16_t kServerRxMTU = kPreferredMTU - 1; - const auto kExpectedRequest = common::CreateStaticByteBuffer( + const auto kExpectedRequest = CreateStaticByteBuffer( 0x02, // opcode: exchange MTU kPreferredMTU, 0x00 // client rx mtu: kPreferredMTU ); @@ -276,7 +268,7 @@ TEST_F(GATT_ClientTest, ExchangeMTUSelectRemote) { ASSERT_EQ(att::kLEMinMTU, att()->mtu()); // Respond with an error. The MTU should remain unchanged. - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x03, // opcode: exchange MTU response kServerRxMTU, 0x00 // server rx mtu )); @@ -293,7 +285,7 @@ TEST_F(GATT_ClientTest, ExchangeMTUSelectDefault) { constexpr uint16_t kPreferredMTU = 100; constexpr uint16_t kServerRxMTU = 5; // Smaller than the LE default MTU - const auto kExpectedRequest = common::CreateStaticByteBuffer( + const auto kExpectedRequest = CreateStaticByteBuffer( 0x02, // opcode: exchange MTU kPreferredMTU, 0x00 // client rx mtu: kPreferredMTU ); @@ -315,7 +307,7 @@ TEST_F(GATT_ClientTest, ExchangeMTUSelectDefault) { ASSERT_EQ(att::kLEMinMTU, att()->mtu()); // Respond with an error. The MTU should remain unchanged. - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x03, // opcode: exchange MTU response kServerRxMTU, 0x00 // server rx mtu )); @@ -339,7 +331,7 @@ TEST_F(GATT_ClientTest, DiscoverAllPrimaryResponseTooShort) { ASSERT_TRUE(Expect(kDiscoverAllPrimaryRequest)); // Respond back with a malformed payload. - fake_chan()->Receive(common::CreateStaticByteBuffer(0x11)); + fake_chan()->Receive(CreateStaticByteBuffer(0x11)); RunLoopUntilIdle(); @@ -360,7 +352,7 @@ TEST_F(GATT_ClientTest, DiscoverAllPrimaryMalformedDataLength) { // Respond back with an unexpected data length. This is 6 for services with a // 16-bit UUID (start (2) + end (2) + uuid (2)) and 20 for 128-bit // (start (2) + end (2) + uuid (16)). - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x11, // opcode: read by group type response 7, // data length: 7 (not 6 or 20) 0, 1, 2, 3, 4, 5, 6 // one entry of length 7, which will be ignored @@ -382,7 +374,7 @@ TEST_F(GATT_ClientTest, DiscoverAllPrimaryMalformedAttrDataList) { ASSERT_TRUE(Expect(kDiscoverAllPrimaryRequest)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x11, // opcode: read by group type response 6, // data length: 6 (16-bit UUIDs) 0, 1, 2, 3, 4, 5, // entry 1: correct size @@ -408,7 +400,7 @@ TEST_F(GATT_ClientTest, DiscoverAllPrimaryEmptyDataList) { ASSERT_TRUE(Expect(kDiscoverAllPrimaryRequest)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x11, // opcode: read by group type response 6 // data length: 6 (16-bit UUIDs) // data list is empty @@ -430,7 +422,7 @@ TEST_F(GATT_ClientTest, DiscoverAllPrimaryAttributeNotFound) { ASSERT_TRUE(Expect(kDiscoverAllPrimaryRequest)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x01, // opcode: error response 0x10, // request: read by group type 0x01, 0x00, // handle: 0x0001 @@ -455,7 +447,7 @@ TEST_F(GATT_ClientTest, DiscoverAllPrimaryError) { ASSERT_TRUE(Expect(kDiscoverAllPrimaryRequest)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x01, // opcode: error response 0x10, // request: read by group type 0x01, 0x00, // handle: 0x0001 @@ -480,7 +472,7 @@ TEST_F(GATT_ClientTest, DiscoverAllPrimaryMalformedServiceRange) { ASSERT_TRUE(Expect(kDiscoverAllPrimaryRequest)); // Return a service where start > end. - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x11, // opcode: read by group type response 0x06, // data length: 6 (16-bit UUIDs) 0x02, 0x00, // svc 1 start: 0x0002 @@ -511,7 +503,7 @@ TEST_F(GATT_ClientTest, DiscoverAllPrimary16BitResultsSingleRequest) { ASSERT_TRUE(Expect(kDiscoverAllPrimaryRequest)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x11, // opcode: read by group type response 0x06, // data length: 6 (16-bit UUIDs) 0x01, 0x00, // svc 1 start: 0x0001 @@ -552,7 +544,7 @@ TEST_F(GATT_ClientTest, DiscoverAllPrimary128BitResultSingleRequest) { ASSERT_TRUE(Expect(kDiscoverAllPrimaryRequest)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x11, // opcode: read by group type response 0x14, // data length: 20 (128-bit UUIDs) 0x01, 0x00, // svc 1 start: 0x0008 @@ -573,24 +565,24 @@ TEST_F(GATT_ClientTest, DiscoverAllPrimary128BitResultSingleRequest) { } TEST_F(GATT_ClientTest, DiscoverAllPrimaryMultipleRequests) { - const auto kExpectedRequest1 = common::CreateStaticByteBuffer( - 0x10, // opcode: read by group type request - 0x01, 0x00, // start handle: 0x0001 - 0xFF, 0xFF, // end handle: 0xFFFF - 0x00, 0x28 // type: primary service (0x2800) - ); - const auto kExpectedRequest2 = common::CreateStaticByteBuffer( - 0x10, // opcode: read by group type request - 0x08, 0x00, // start handle: 0x0008 - 0xFF, 0xFF, // end handle: 0xFFFF - 0x00, 0x28 // type: primary service (0x2800) - ); - const auto kExpectedRequest3 = common::CreateStaticByteBuffer( - 0x10, // opcode: read by group type request - 0x0A, 0x00, // start handle: 0x000A - 0xFF, 0xFF, // end handle: 0xFFFF - 0x00, 0x28 // type: primary service (0x2800) - ); + const auto kExpectedRequest1 = + CreateStaticByteBuffer(0x10, // opcode: read by group type request + 0x01, 0x00, // start handle: 0x0001 + 0xFF, 0xFF, // end handle: 0xFFFF + 0x00, 0x28 // type: primary service (0x2800) + ); + const auto kExpectedRequest2 = + CreateStaticByteBuffer(0x10, // opcode: read by group type request + 0x08, 0x00, // start handle: 0x0008 + 0xFF, 0xFF, // end handle: 0xFFFF + 0x00, 0x28 // type: primary service (0x2800) + ); + const auto kExpectedRequest3 = + CreateStaticByteBuffer(0x10, // opcode: read by group type request + 0x0A, 0x00, // start handle: 0x000A + 0xFF, 0xFF, // end handle: 0xFFFF + 0x00, 0x28 // type: primary service (0x2800) + ); att::Status status(HostError::kFailed); auto res_cb = [this, &status](att::Status val) { status = val; }; @@ -607,7 +599,7 @@ TEST_F(GATT_ClientTest, DiscoverAllPrimaryMultipleRequests) { ASSERT_TRUE(Expect(kExpectedRequest1)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x11, // opcode: read by group type response 0x06, // data length: 6 (16-bit UUIDs) 0x01, 0x00, // svc 1 start: 0x0001 @@ -624,7 +616,7 @@ TEST_F(GATT_ClientTest, DiscoverAllPrimaryMultipleRequests) { // Respond with one 128-bit service UUID. - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x11, // opcode: read by group type response 0x14, // data length: 20 (128-bit UUIDs) 0x08, 0x00, // svc 1 start: 0x0008 @@ -638,7 +630,7 @@ TEST_F(GATT_ClientTest, DiscoverAllPrimaryMultipleRequests) { ASSERT_TRUE(Expect(kExpectedRequest3)); // Terminate the procedure with an error response. - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x01, // opcode: error response 0x10, // request: read by group type 0x0A, 0x00, // handle: 0x000A @@ -681,12 +673,12 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryResponseTooShort) { constexpr att::Handle kStart = 0x0001; constexpr att::Handle kEnd = 0xFFFF; - const auto kExpectedRequest = common::CreateStaticByteBuffer( - 0x08, // opcode: read by type request - 0x01, 0x00, // start handle: 0x0001 - 0xFF, 0xFF, // end handle: 0xFFFF - 0x03, 0x28 // type: characteristic decl. (0x2803) - ); + const auto kExpectedRequest = + CreateStaticByteBuffer(0x08, // opcode: read by type request + 0x01, 0x00, // start handle: 0x0001 + 0xFF, 0xFF, // end handle: 0xFFFF + 0x03, 0x28 // type: characteristic decl. (0x2803) + ); att::Status status; auto res_cb = [this, &status](att::Status val) { status = val; }; @@ -699,7 +691,7 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryResponseTooShort) { ASSERT_TRUE(Expect(kExpectedRequest)); // Respond back with a malformed payload. - fake_chan()->Receive(common::CreateStaticByteBuffer(0x09)); + fake_chan()->Receive(CreateStaticByteBuffer(0x09)); RunLoopUntilIdle(); @@ -710,12 +702,12 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryMalformedDataLength) { constexpr att::Handle kStart = 0x0001; constexpr att::Handle kEnd = 0xFFFF; - const auto kExpectedRequest = common::CreateStaticByteBuffer( - 0x08, // opcode: read by type request - 0x01, 0x00, // start handle: 0x0001 - 0xFF, 0xFF, // end handle: 0xFFFF - 0x03, 0x28 // type: characteristic decl. (0x2803) - ); + const auto kExpectedRequest = + CreateStaticByteBuffer(0x08, // opcode: read by type request + 0x01, 0x00, // start handle: 0x0001 + 0xFF, 0xFF, // end handle: 0xFFFF + 0x03, 0x28 // type: characteristic decl. (0x2803) + ); att::Status status; auto res_cb = [this, &status](att::Status val) { status = val; }; @@ -730,7 +722,7 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryMalformedDataLength) { // Respond back with an unexpected data length. This is 7 for characteristics // with a 16-bit UUID (handle (2) + props (1) + value handle (2) + uuid (2)) // and 21 for 128-bit (handle (2) + props (1) + value handle (2) + uuid (16)). - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x09, // opcode: read by type response 8, // data length: 8 (not 7 or 21) 0, 1, 2, 3, 4, 5, 6, 7 // one entry of length 8, which will be ignored @@ -745,12 +737,12 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryMalformedAttrDataList) { constexpr att::Handle kStart = 0x0001; constexpr att::Handle kEnd = 0xFFFF; - const auto kExpectedRequest = common::CreateStaticByteBuffer( - 0x08, // opcode: read by type request - 0x01, 0x00, // start handle: 0x0001 - 0xFF, 0xFF, // end handle: 0xFFFF - 0x03, 0x28 // type: characteristic decl. (0x2803) - ); + const auto kExpectedRequest = + CreateStaticByteBuffer(0x08, // opcode: read by type request + 0x01, 0x00, // start handle: 0x0001 + 0xFF, 0xFF, // end handle: 0xFFFF + 0x03, 0x28 // type: characteristic decl. (0x2803) + ); att::Status status; auto res_cb = [this, &status](att::Status val) { status = val; }; @@ -765,7 +757,7 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryMalformedAttrDataList) { // Respond back with an unexpected data length. This is 7 for characteristics // with a 16-bit UUID (handle (2) + props (1) + value handle (2) + uuid (2)) // and 21 for 128-bit (handle (2) + props (1) + value handle (2) + uuid (16)). - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x09, // opcode: read by type response 7, // data length: 7 (16-bit UUIDs) 0, 1, 2, 3, 4, 5, 6, // entry 1: correct size @@ -781,12 +773,12 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryEmptyDataList) { constexpr att::Handle kStart = 0x0001; constexpr att::Handle kEnd = 0xFFFF; - const auto kExpectedRequest = common::CreateStaticByteBuffer( - 0x08, // opcode: read by type request - 0x01, 0x00, // start handle: 0x0001 - 0xFF, 0xFF, // end handle: 0xFFFF - 0x03, 0x28 // type: characteristic decl. (0x2803) - ); + const auto kExpectedRequest = + CreateStaticByteBuffer(0x08, // opcode: read by type request + 0x01, 0x00, // start handle: 0x0001 + 0xFF, 0xFF, // end handle: 0xFFFF + 0x03, 0x28 // type: characteristic decl. (0x2803) + ); att::Status status; auto res_cb = [this, &status](att::Status val) { status = val; }; @@ -798,7 +790,7 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryEmptyDataList) { ASSERT_TRUE(Expect(kExpectedRequest)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x09, // opcode: read by type response 7 // data length: 7 (16-bit UUIDs) // data list empty @@ -813,12 +805,12 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryAttributeNotFound) { constexpr att::Handle kStart = 0x0001; constexpr att::Handle kEnd = 0xFFFF; - const auto kExpectedRequest = common::CreateStaticByteBuffer( - 0x08, // opcode: read by type request - 0x01, 0x00, // start handle: 0x0001 - 0xFF, 0xFF, // end handle: 0xFFFF - 0x03, 0x28 // type: characteristic decl. (0x2803) - ); + const auto kExpectedRequest = + CreateStaticByteBuffer(0x08, // opcode: read by type request + 0x01, 0x00, // start handle: 0x0001 + 0xFF, 0xFF, // end handle: 0xFFFF + 0x03, 0x28 // type: characteristic decl. (0x2803) + ); att::Status status; auto res_cb = [this, &status](att::Status val) { status = val; }; @@ -830,7 +822,7 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryAttributeNotFound) { ASSERT_TRUE(Expect(kExpectedRequest)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x01, // opcode: error response 0x08, // request: read by type 0x01, 0x00, // handle: 0x0001 @@ -847,12 +839,12 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryError) { constexpr att::Handle kStart = 0x0001; constexpr att::Handle kEnd = 0xFFFF; - const auto kExpectedRequest = common::CreateStaticByteBuffer( - 0x08, // opcode: read by type request - 0x01, 0x00, // start handle: 0x0001 - 0xFF, 0xFF, // end handle: 0xFFFF - 0x03, 0x28 // type: characteristic decl. (0x2803) - ); + const auto kExpectedRequest = + CreateStaticByteBuffer(0x08, // opcode: read by type request + 0x01, 0x00, // start handle: 0x0001 + 0xFF, 0xFF, // end handle: 0xFFFF + 0x03, 0x28 // type: characteristic decl. (0x2803) + ); att::Status status; auto res_cb = [this, &status](att::Status val) { status = val; }; @@ -864,7 +856,7 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryError) { ASSERT_TRUE(Expect(kExpectedRequest)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x01, // opcode: error response 0x08, // request: read by type 0x01, 0x00, // handle: 0x0001 @@ -881,12 +873,12 @@ TEST_F(GATT_ClientTest, CharacteristicDiscovery16BitResultsSingleRequest) { constexpr att::Handle kStart = 0x0001; constexpr att::Handle kEnd = 0x0005; - const auto kExpectedRequest = common::CreateStaticByteBuffer( - 0x08, // opcode: read by type request - 0x01, 0x00, // start handle: 0x0001 - 0x05, 0x00, // end handle: 0x0005 - 0x03, 0x28 // type: characteristic decl. (0x2803) - ); + const auto kExpectedRequest = + CreateStaticByteBuffer(0x08, // opcode: read by type request + 0x01, 0x00, // start handle: 0x0001 + 0x05, 0x00, // end handle: 0x0005 + 0x03, 0x28 // type: characteristic decl. (0x2803) + ); att::Status status; auto res_cb = [this, &status](att::Status val) { status = val; }; @@ -903,7 +895,7 @@ TEST_F(GATT_ClientTest, CharacteristicDiscovery16BitResultsSingleRequest) { ASSERT_TRUE(Expect(kExpectedRequest)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x09, // opcode: read by type response 0x07, // data length: 7 (16-bit UUIDs) 0x03, 0x00, // chrc 1 handle @@ -934,12 +926,12 @@ TEST_F(GATT_ClientTest, CharacteristicDiscovery128BitResultsSingleRequest) { constexpr att::Handle kStart = 0x0001; constexpr att::Handle kEnd = 0x0005; - const auto kExpectedRequest = common::CreateStaticByteBuffer( - 0x08, // opcode: read by type request - 0x01, 0x00, // start handle: 0x0001 - 0x05, 0x00, // end handle: 0x0005 - 0x03, 0x28 // type: characteristic decl. (0x2803) - ); + const auto kExpectedRequest = + CreateStaticByteBuffer(0x08, // opcode: read by type request + 0x01, 0x00, // start handle: 0x0001 + 0x05, 0x00, // end handle: 0x0005 + 0x03, 0x28 // type: characteristic decl. (0x2803) + ); att::Status status; auto res_cb = [this, &status](att::Status val) { status = val; }; @@ -956,7 +948,7 @@ TEST_F(GATT_ClientTest, CharacteristicDiscovery128BitResultsSingleRequest) { ASSERT_TRUE(Expect(kExpectedRequest)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x09, // opcode: read by type response 0x15, // data length: 21 (128-bit UUIDs) 0x05, 0x00, // chrc handle @@ -980,24 +972,24 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryMultipleRequests) { constexpr att::Handle kStart = 0x0001; constexpr att::Handle kEnd = 0xFFFF; - const auto kExpectedRequest1 = common::CreateStaticByteBuffer( - 0x08, // opcode: read by type request - 0x01, 0x00, // start handle: 0x0001 - 0xFF, 0xFF, // end handle: 0xFFFF - 0x03, 0x28 // type: characteristic decl. (0x2803) - ); - const auto kExpectedRequest2 = common::CreateStaticByteBuffer( - 0x08, // opcode: read by type request - 0x06, 0x00, // start handle: 0x0006 - 0xFF, 0xFF, // end handle: 0xFFFF - 0x03, 0x28 // type: characteristic decl. (0x2803) - ); - const auto kExpectedRequest3 = common::CreateStaticByteBuffer( - 0x08, // opcode: read by type request - 0x08, 0x00, // start handle: 0x0008 - 0xFF, 0xFF, // end handle: 0xFFFF - 0x03, 0x28 // type: characteristic decl. (0x2803) - ); + const auto kExpectedRequest1 = + CreateStaticByteBuffer(0x08, // opcode: read by type request + 0x01, 0x00, // start handle: 0x0001 + 0xFF, 0xFF, // end handle: 0xFFFF + 0x03, 0x28 // type: characteristic decl. (0x2803) + ); + const auto kExpectedRequest2 = + CreateStaticByteBuffer(0x08, // opcode: read by type request + 0x06, 0x00, // start handle: 0x0006 + 0xFF, 0xFF, // end handle: 0xFFFF + 0x03, 0x28 // type: characteristic decl. (0x2803) + ); + const auto kExpectedRequest3 = + CreateStaticByteBuffer(0x08, // opcode: read by type request + 0x08, 0x00, // start handle: 0x0008 + 0xFF, 0xFF, // end handle: 0xFFFF + 0x03, 0x28 // type: characteristic decl. (0x2803) + ); att::Status status; auto res_cb = [this, &status](att::Status val) { status = val; }; @@ -1014,7 +1006,7 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryMultipleRequests) { ASSERT_TRUE(Expect(kExpectedRequest1)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x09, // opcode: read by type response 0x07, // data length: 7 (16-bit UUIDs) 0x03, 0x00, // chrc 1 handle @@ -1033,7 +1025,7 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryMultipleRequests) { // Respond with one characteristic with a 128-bit UUID - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x09, // opcode: read by type response 0x15, // data length: 21 (128-bit UUIDs) 0x07, 0x00, // chrc handle @@ -1048,7 +1040,7 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryMultipleRequests) { ASSERT_TRUE(Expect(kExpectedRequest3)); // Terminate the procedure with an error response. - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x01, // opcode: error response 0x08, // request: read by type 0x0A, 0x00, // handle: 0x000A @@ -1082,12 +1074,12 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryResultsBeforeRange) { constexpr att::Handle kStart = 0x0002; constexpr att::Handle kEnd = 0x0005; - const auto kExpectedRequest = common::CreateStaticByteBuffer( - 0x08, // opcode: read by type request - 0x02, 0x00, // start handle: 0x0002 - 0x05, 0x00, // end handle: 0x0005 - 0x03, 0x28 // type: characteristic decl. (0x2803) - ); + const auto kExpectedRequest = + CreateStaticByteBuffer(0x08, // opcode: read by type request + 0x02, 0x00, // start handle: 0x0002 + 0x05, 0x00, // end handle: 0x0005 + 0x03, 0x28 // type: characteristic decl. (0x2803) + ); att::Status status; auto res_cb = [this, &status](att::Status val) { status = val; }; @@ -1104,7 +1096,7 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryResultsBeforeRange) { ASSERT_TRUE(Expect(kExpectedRequest)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x09, // opcode: read by type response 0x07, // data length: 7 (16-bit UUIDs) 0x01, 0x00, // chrc 1 handle (handle is before the range) @@ -1125,12 +1117,12 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryResultsBeyondRange) { constexpr att::Handle kStart = 0x0002; constexpr att::Handle kEnd = 0x0005; - const auto kExpectedRequest = common::CreateStaticByteBuffer( - 0x08, // opcode: read by type request - 0x02, 0x00, // start handle: 0x0002 - 0x05, 0x00, // end handle: 0x0005 - 0x03, 0x28 // type: characteristic decl. (0x2803) - ); + const auto kExpectedRequest = + CreateStaticByteBuffer(0x08, // opcode: read by type request + 0x02, 0x00, // start handle: 0x0002 + 0x05, 0x00, // end handle: 0x0005 + 0x03, 0x28 // type: characteristic decl. (0x2803) + ); att::Status status; auto res_cb = [this, &status](att::Status val) { status = val; }; @@ -1147,7 +1139,7 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryResultsBeyondRange) { ASSERT_TRUE(Expect(kExpectedRequest)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x09, // opcode: read by type response 0x07, // data length: 7 (16-bit UUIDs) 0x06, 0x00, // chrc 1 handle (handle is beyond the range) @@ -1168,12 +1160,12 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryValueNotContiguous) { constexpr att::Handle kStart = 0x0002; constexpr att::Handle kEnd = 0x0005; - const auto kExpectedRequest = common::CreateStaticByteBuffer( - 0x08, // opcode: read by type request - 0x02, 0x00, // start handle: 0x0002 - 0x05, 0x00, // end handle: 0x0005 - 0x03, 0x28 // type: characteristic decl. (0x2803) - ); + const auto kExpectedRequest = + CreateStaticByteBuffer(0x08, // opcode: read by type request + 0x02, 0x00, // start handle: 0x0002 + 0x05, 0x00, // end handle: 0x0005 + 0x03, 0x28 // type: characteristic decl. (0x2803) + ); att::Status status; auto res_cb = [this, &status](att::Status val) { status = val; }; @@ -1190,7 +1182,7 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryValueNotContiguous) { ASSERT_TRUE(Expect(kExpectedRequest)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x09, // opcode: read by type response 0x07, // data length: 7 (16-bit UUIDs) 0x02, 0x00, // chrc 1 handle @@ -1209,12 +1201,12 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryHandlesNotIncreasing) { constexpr att::Handle kStart = 0x0002; constexpr att::Handle kEnd = 0x0005; - const auto kExpectedRequest = common::CreateStaticByteBuffer( - 0x08, // opcode: read by type request - 0x02, 0x00, // start handle: 0x0002 - 0x05, 0x00, // end handle: 0x0005 - 0x03, 0x28 // type: characteristic decl. (0x2803) - ); + const auto kExpectedRequest = + CreateStaticByteBuffer(0x08, // opcode: read by type request + 0x02, 0x00, // start handle: 0x0002 + 0x05, 0x00, // end handle: 0x0005 + 0x03, 0x28 // type: characteristic decl. (0x2803) + ); att::Status status; auto res_cb = [this, &status](att::Status val) { status = val; }; @@ -1231,7 +1223,7 @@ TEST_F(GATT_ClientTest, CharacteristicDiscoveryHandlesNotIncreasing) { ASSERT_TRUE(Expect(kExpectedRequest)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x09, // opcode: read by type response 0x07, // data length: 7 (16-bit UUIDs) 0x02, 0x00, // chrc 1 handle @@ -1268,7 +1260,7 @@ TEST_F(GATT_ClientTest, DescriptorDiscoveryResponseTooShort) { ASSERT_TRUE(ExpectFindInformation()); // Respond back with a malformed payload. - fake_chan()->Receive(common::CreateStaticByteBuffer(0x05)); + fake_chan()->Receive(CreateStaticByteBuffer(0x05)); RunLoopUntilIdle(); @@ -1280,7 +1272,7 @@ TEST_F(GATT_ClientTest, DescriptorDiscoveryMalformedDataLength) { SendDiscoverDescriptors(&status, NopDescCallback); ASSERT_TRUE(ExpectFindInformation()); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x05, // opcode: find information response 0x03 // format (must be 1 or 2) )); @@ -1295,10 +1287,10 @@ TEST_F(GATT_ClientTest, DescriptorDiscoveryMalformedAttrDataList16) { SendDiscoverDescriptors(&status, NopDescCallback); ASSERT_TRUE(ExpectFindInformation()); - fake_chan()->Receive(common::CreateStaticByteBuffer( - 0x05, // opcode: find information response - 0x01, // format: 16-bit. Data length must be 4 - 1, 2, 3, 4, 5)); + fake_chan()->Receive( + CreateStaticByteBuffer(0x05, // opcode: find information response + 0x01, // format: 16-bit. Data length must be 4 + 1, 2, 3, 4, 5)); RunLoopUntilIdle(); @@ -1310,7 +1302,7 @@ TEST_F(GATT_ClientTest, DescriptorDiscoveryMalformedAttrDataList128) { SendDiscoverDescriptors(&status, NopDescCallback); ASSERT_TRUE(ExpectFindInformation()); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x05, // opcode: find information response 0x02, // format: 128-bit. Data length must be 18 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17)); @@ -1325,7 +1317,7 @@ TEST_F(GATT_ClientTest, DescriptorDiscoveryEmptyDataList) { SendDiscoverDescriptors(&status, NopDescCallback); ASSERT_TRUE(ExpectFindInformation()); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x05, // opcode: find information response 0x01 // format: 16-bit. // data list empty @@ -1341,7 +1333,7 @@ TEST_F(GATT_ClientTest, DescriptorDiscoveryAttributeNotFound) { SendDiscoverDescriptors(&status, NopDescCallback); ASSERT_TRUE(ExpectFindInformation()); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x01, // opcode: error response 0x04, // request: find information 0x01, 0x00, // handle: 0x0001 @@ -1358,7 +1350,7 @@ TEST_F(GATT_ClientTest, DescriptorDiscoveryError) { SendDiscoverDescriptors(&status, NopDescCallback); ASSERT_TRUE(ExpectFindInformation()); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x01, // opcode: error response 0x04, // request: find information 0x01, 0x00, // handle: 0x0001 @@ -1384,7 +1376,7 @@ TEST_F(GATT_ClientTest, DescriptorDiscovery16BitResultsSingleRequest) { SendDiscoverDescriptors(&status, std::move(desc_cb), kStart, kEnd); ASSERT_TRUE(ExpectFindInformation(kStart, kEnd)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x05, // opcode: find information response 0x01, // format: 16-bit. Data length must be 4 0x01, 0x00, // desc 1 handle @@ -1421,7 +1413,7 @@ TEST_F(GATT_ClientTest, DescriptorDiscovery128BitResultsSingleRequest) { ASSERT_TRUE(ExpectFindInformation(kStart, kEnd)); att()->set_mtu(512); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x05, // opcode: find information response 0x02, // format: 128-bit. Data length must be 18 0x01, 0x00, // desc 1 handle @@ -1459,7 +1451,7 @@ TEST_F(GATT_ClientTest, DescriptorDiscoveryMultipleRequests) { // Batch 1 ASSERT_TRUE(ExpectFindInformation(kStart1, kEnd)); return; - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x05, // opcode: find information response 0x01, // format: 16-bit. Data length must be 4 0x01, 0x00, // desc 1 handle @@ -1471,7 +1463,7 @@ TEST_F(GATT_ClientTest, DescriptorDiscoveryMultipleRequests) { // Batch 2 ASSERT_TRUE(ExpectFindInformation(kStart2, kEnd)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x05, // opcode: find information response 0x02, // format: 128-bit. Data length must be 18 0x03, 0x00, // desc 3 handle @@ -1482,7 +1474,7 @@ TEST_F(GATT_ClientTest, DescriptorDiscoveryMultipleRequests) { // Batch 3 ASSERT_TRUE(ExpectFindInformation(kStart3, kEnd)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x01, // opcode: error response 0x08, // request: read by type 0x04, 0x00, // handle: kStart3 (0x0004) @@ -1507,7 +1499,7 @@ TEST_F(GATT_ClientTest, DescriptorDiscoveryResultsBeforeRange) { SendDiscoverDescriptors(&status, NopDescCallback, kStart); ASSERT_TRUE(ExpectFindInformation(kStart)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x05, // opcode: find information response 0x01, // format: 16-bit. 0x01, 0x00, // handle is before the range @@ -1527,7 +1519,7 @@ TEST_F(GATT_ClientTest, DescriptorDiscoveryResultsBeyondRange) { SendDiscoverDescriptors(&status, NopDescCallback, kStart, kEnd); ASSERT_TRUE(ExpectFindInformation(kStart, kEnd)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x05, // opcode: find information response 0x01, // format: 16-bit. 0x03, 0x00, // handle is beyond the range @@ -1544,7 +1536,7 @@ TEST_F(GATT_ClientTest, DescriptorDiscoveryHandlesNotIncreasing) { SendDiscoverDescriptors(&status, NopDescCallback); ASSERT_TRUE(ExpectFindInformation()); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x05, // opcode: find information response 0x01, // format: 16-bit. 0x01, 0x00, // handle: 0x0001 @@ -1559,12 +1551,12 @@ TEST_F(GATT_ClientTest, DescriptorDiscoveryHandlesNotIncreasing) { } TEST_F(GATT_ClientTest, WriteRequestMalformedResponse) { - const auto kValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kValue = CreateStaticByteBuffer('f', 'o', 'o'); const auto kHandle = 0x0001; const auto kExpectedRequest = - common::CreateStaticByteBuffer(0x12, // opcode: write request - 0x01, 0x00, // handle: 0x0001 - 'f', 'o', 'o' // value: "foo" + CreateStaticByteBuffer(0x12, // opcode: write request + 0x01, 0x00, // handle: 0x0001 + 'f', 'o', 'o' // value: "foo" ); att::Status status; @@ -1579,7 +1571,7 @@ TEST_F(GATT_ClientTest, WriteRequestMalformedResponse) { ASSERT_FALSE(fake_chan()->link_error()); // Respond back with a malformed PDU. This should result in a link error. - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x013, // opcode: write response 0 // One byte payload. The write request has no parameters. )); @@ -1591,13 +1583,13 @@ TEST_F(GATT_ClientTest, WriteRequestMalformedResponse) { } TEST_F(GATT_ClientTest, WriteRequestExceedsMtu) { - const auto kValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kValue = CreateStaticByteBuffer('f', 'o', 'o'); constexpr att::Handle kHandle = 0x0001; constexpr size_t kMtu = 5; const auto kExpectedRequest = - common::CreateStaticByteBuffer(0x12, // opcode: write request - 0x01, 0x00, // handle: 0x0001 - 'f', 'o', 'o' // value: "foo" + CreateStaticByteBuffer(0x12, // opcode: write request + 0x01, 0x00, // handle: 0x0001 + 'f', 'o', 'o' // value: "foo" ); ASSERT_EQ(kMtu + 1, kExpectedRequest.size()); @@ -1614,12 +1606,12 @@ TEST_F(GATT_ClientTest, WriteRequestExceedsMtu) { } TEST_F(GATT_ClientTest, WriteRequestError) { - const auto kValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kValue = CreateStaticByteBuffer('f', 'o', 'o'); const auto kHandle = 0x0001; const auto kExpectedRequest = - common::CreateStaticByteBuffer(0x12, // opcode: write request - 0x01, 0x00, // handle: 0x0001 - 'f', 'o', 'o' // value: "foo" + CreateStaticByteBuffer(0x12, // opcode: write request + 0x01, 0x00, // handle: 0x0001 + 'f', 'o', 'o' // value: "foo" ); att::Status status; @@ -1631,7 +1623,7 @@ TEST_F(GATT_ClientTest, WriteRequestError) { ASSERT_TRUE(Expect(kExpectedRequest)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x01, // opcode: error response 0x12, // request: write request 0x01, 0x00, // handle: 0x0001 @@ -1645,12 +1637,12 @@ TEST_F(GATT_ClientTest, WriteRequestError) { } TEST_F(GATT_ClientTest, WriteRequestSuccess) { - const auto kValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kValue = CreateStaticByteBuffer('f', 'o', 'o'); const auto kHandle = 0x0001; const auto kExpectedRequest = - common::CreateStaticByteBuffer(0x12, // opcode: write request - 0x01, 0x00, // handle: 0x0001 - 'f', 'o', 'o' // value: "foo" + CreateStaticByteBuffer(0x12, // opcode: write request + 0x01, 0x00, // handle: 0x0001 + 'f', 'o', 'o' // value: "foo" ); att::Status status; @@ -1662,9 +1654,8 @@ TEST_F(GATT_ClientTest, WriteRequestSuccess) { ASSERT_TRUE(Expect(kExpectedRequest)); - fake_chan()->Receive( - common::CreateStaticByteBuffer(0x13 // opcode: write response - )); + fake_chan()->Receive(CreateStaticByteBuffer(0x13 // opcode: write response + )); RunLoopUntilIdle(); EXPECT_TRUE(status); @@ -1672,13 +1663,13 @@ TEST_F(GATT_ClientTest, WriteRequestSuccess) { } TEST_F(GATT_ClientTest, WriteWithoutResponseExceedsMtu) { - const auto kValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kValue = CreateStaticByteBuffer('f', 'o', 'o'); constexpr att::Handle kHandle = 0x0001; constexpr size_t kMtu = 5; const auto kExpectedRequest = - common::CreateStaticByteBuffer(0x52, // opcode: write command - 0x01, 0x00, // handle: 0x0001 - 'f', 'o', 'o' // value: "foo" + CreateStaticByteBuffer(0x52, // opcode: write command + 0x01, 0x00, // handle: 0x0001 + 'f', 'o', 'o' // value: "foo" ); ASSERT_EQ(kMtu + 1, kExpectedRequest.size()); @@ -1695,12 +1686,12 @@ TEST_F(GATT_ClientTest, WriteWithoutResponseExceedsMtu) { } TEST_F(GATT_ClientTest, WriteWithoutResponseSuccess) { - const auto kValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kValue = CreateStaticByteBuffer('f', 'o', 'o'); const auto kHandle = 0x0001; const auto kExpectedRequest = - common::CreateStaticByteBuffer(0x52, // opcode: write request - 0x01, 0x00, // handle: 0x0001 - 'f', 'o', 'o' // value: "foo" + CreateStaticByteBuffer(0x52, // opcode: write request + 0x01, 0x00, // handle: 0x0001 + 'f', 'o', 'o' // value: "foo" ); // Initiate the request in a loop task, as Expect() below blocks @@ -1713,8 +1704,8 @@ TEST_F(GATT_ClientTest, WriteWithoutResponseSuccess) { TEST_F(GATT_ClientTest, ReadRequestEmptyResponse) { constexpr att::Handle kHandle = 0x0001; const auto kExpectedRequest = - common::CreateStaticByteBuffer(0x0A, // opcode: read request - 0x01, 0x00 // handle: 0x0001 + CreateStaticByteBuffer(0x0A, // opcode: read request + 0x01, 0x00 // handle: 0x0001 ); att::Status status(HostError::kFailed); @@ -1732,7 +1723,7 @@ TEST_F(GATT_ClientTest, ReadRequestEmptyResponse) { ASSERT_TRUE(Expect(kExpectedRequest)); // ATT Read Response with no payload. - fake_chan()->Receive(common::CreateStaticByteBuffer(0x0B)); + fake_chan()->Receive(CreateStaticByteBuffer(0x0B)); RunLoopUntilIdle(); @@ -1743,19 +1734,19 @@ TEST_F(GATT_ClientTest, ReadRequestEmptyResponse) { TEST_F(GATT_ClientTest, ReadRequestSuccess) { constexpr att::Handle kHandle = 0x0001; const auto kExpectedRequest = - common::CreateStaticByteBuffer(0x0A, // opcode: read request - 0x01, 0x00 // handle: 0x0001 + CreateStaticByteBuffer(0x0A, // opcode: read request + 0x01, 0x00 // handle: 0x0001 ); const auto kExpectedResponse = - common::CreateStaticByteBuffer(0x0B, // opcode: read response - 't', 'e', 's', 't' // value: "test" + CreateStaticByteBuffer(0x0B, // opcode: read response + 't', 'e', 's', 't' // value: "test" ); att::Status status(HostError::kFailed); auto cb = [&](att::Status cb_status, const ByteBuffer& value) { status = cb_status; - EXPECT_TRUE(common::ContainersEqual(kExpectedResponse.view(1), value)); + EXPECT_TRUE(ContainersEqual(kExpectedResponse.view(1), value)); }; // Initiate the request in a loop task, as Expect() below blocks @@ -1775,8 +1766,8 @@ TEST_F(GATT_ClientTest, ReadRequestSuccess) { TEST_F(GATT_ClientTest, ReadRequestError) { constexpr att::Handle kHandle = 0x0001; const auto kExpectedRequest = - common::CreateStaticByteBuffer(0x0A, // opcode: read request - 0x01, 0x00 // handle: 0x0001 + CreateStaticByteBuffer(0x0A, // opcode: read request + 0x01, 0x00 // handle: 0x0001 ); att::Status status; @@ -1793,7 +1784,7 @@ TEST_F(GATT_ClientTest, ReadRequestError) { ASSERT_TRUE(Expect(kExpectedRequest)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x01, // opcode: error response 0x0A, // request: read request 0x01, 0x00, // handle: 0x0001 @@ -1832,7 +1823,7 @@ TEST_F(GATT_ClientTest, ReadBlobRequestEmptyResponse) { ASSERT_TRUE(Expect(kExpectedRequest)); // ATT Read Blob Response with no payload. - fake_chan()->Receive(common::CreateStaticByteBuffer(0x0D)); + fake_chan()->Receive(CreateStaticByteBuffer(0x0D)); RunLoopUntilIdle(); @@ -1898,7 +1889,7 @@ TEST_F(GATT_ClientTest, ReadBlobRequestError) { ASSERT_TRUE(Expect(kExpectedRequest)); - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x01, // opcode: error response 0x0C, // request: read blob request 0x01, 0x00, // handle: 0x0001 @@ -1924,10 +1915,12 @@ TEST_F(GATT_ClientTest, EmptyNotification) { EXPECT_EQ(0u, value.size()); }); - fake_chan()->Receive(common::CreateStaticByteBuffer( + // clang-format off + fake_chan()->Receive(CreateStaticByteBuffer( 0x1B, // opcode: notification 0x01, 0x00 // handle: 1 )); + // clang-format on RunLoopUntilIdle(); EXPECT_TRUE(called); @@ -1945,11 +1938,13 @@ TEST_F(GATT_ClientTest, Notification) { EXPECT_EQ("test", value.AsString()); }); - fake_chan()->Receive(common::CreateStaticByteBuffer( + // clang-format off + fake_chan()->Receive(CreateStaticByteBuffer( 0x1B, // opcode: notification 0x01, 0x00, // handle: 1 't', 'e', 's', 't' // value: "test" - )); + )); + // clang-format on RunLoopUntilIdle(); EXPECT_TRUE(called); @@ -1967,14 +1962,16 @@ TEST_F(GATT_ClientTest, Indication) { EXPECT_EQ("test", value.AsString()); }); - fake_chan()->Receive(common::CreateStaticByteBuffer( + // clang-format off + fake_chan()->Receive(CreateStaticByteBuffer( 0x1D, // opcode: indication 0x01, 0x00, // handle: 1 't', 'e', 's', 't' // value: "test" - )); + )); + // clang-format on // Wait until a confirmation gets sent. - EXPECT_TRUE(Expect(common::CreateStaticByteBuffer(0x1E))); + EXPECT_TRUE(Expect(CreateStaticByteBuffer(0x1E))); EXPECT_TRUE(called); } diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/fake_client.cc b/src/connectivity/bluetooth/core/bt-host/gatt/fake_client.cc index 293cdbd77936089d7306df1d5a43adb88eca5b00..08b4b94bb0f03c9e95bd9914a5b75a1850acc41f 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/fake_client.cc +++ b/src/connectivity/bluetooth/core/bt-host/gatt/fake_client.cc @@ -104,8 +104,7 @@ void FakeClient::ReadBlobRequest(att::Handle handle, uint16_t offset, } } -void FakeClient::WriteRequest(att::Handle handle, - const common::ByteBuffer& value, +void FakeClient::WriteRequest(att::Handle handle, const ByteBuffer& value, StatusCallback callback) { if (write_request_callback_) { write_request_callback_(handle, value, std::move(callback)); @@ -113,14 +112,14 @@ void FakeClient::WriteRequest(att::Handle handle, } void FakeClient::WriteWithoutResponse(att::Handle handle, - const common::ByteBuffer& value) { + const ByteBuffer& value) { if (write_without_rsp_callback_) { write_without_rsp_callback_(handle, value); } } void FakeClient::SendNotification(bool indicate, att::Handle handle, - const common::ByteBuffer& value) { + const ByteBuffer& value) { if (notification_callback_) { notification_callback_(indicate, handle, value); } diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/fake_client.h b/src/connectivity/bluetooth/core/bt-host/gatt/fake_client.h index e1213634cb76a6f8b9552b49c78f4a9b3bc8b001..2cd47a459598fb8e2fa7d11beabb620dd3661669 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/fake_client.h +++ b/src/connectivity/bluetooth/core/bt-host/gatt/fake_client.h @@ -82,22 +82,22 @@ class FakeClient final : public Client { } // Sets a callback which will run when WriteRequest gets called. - using WriteRequestCallback = fit::function<void( - att::Handle, const common::ByteBuffer&, att::StatusCallback)>; + using WriteRequestCallback = + fit::function<void(att::Handle, const ByteBuffer&, att::StatusCallback)>; void set_write_request_callback(WriteRequestCallback callback) { write_request_callback_ = std::move(callback); } // Sets a callback which will run when WriteWithoutResponse gets called. using WriteWithoutResponseCallback = - fit::function<void(att::Handle, const common::ByteBuffer&)>; + fit::function<void(att::Handle, const ByteBuffer&)>; void set_write_without_rsp_callback(WriteWithoutResponseCallback callback) { write_without_rsp_callback_ = std::move(callback); } // Emulates the receipt of a notification or indication PDU. void SendNotification(bool indicate, att::Handle handle, - const common::ByteBuffer& value); + const ByteBuffer& value); private: // Client overrides: @@ -115,10 +115,10 @@ class FakeClient final : public Client { void ReadRequest(att::Handle handle, ReadCallback callback) override; void ReadBlobRequest(att::Handle handle, uint16_t offset, ReadCallback callback) override; - void WriteRequest(att::Handle handle, const common::ByteBuffer& value, + void WriteRequest(att::Handle handle, const ByteBuffer& value, att::StatusCallback callback) override; void WriteWithoutResponse(att::Handle handle, - const common::ByteBuffer& value) override; + const ByteBuffer& value) override; void SetNotificationHandler(NotificationCallback callback) override; // All callbacks will be posted on this dispatcher to emulate asynchronous diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/fake_layer.cc b/src/connectivity/bluetooth/core/bt-host/gatt/fake_layer.cc index 9e9a591f40d4bf7025a9b105402465c13686033c..1609706abd6d043640259f4ce3f14ac37aa27b1d 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/fake_layer.cc +++ b/src/connectivity/bluetooth/core/bt-host/gatt/fake_layer.cc @@ -51,7 +51,7 @@ void FakeLayer::RegisterRemoteServiceWatcher(RemoteServiceWatcher callback, // TODO: implement } -void FakeLayer::ListServices(PeerId peer_id, std::vector<common::UUID> uuids, +void FakeLayer::ListServices(PeerId peer_id, std::vector<UUID> uuids, ServiceListCallback callback) { // TODO: implement } diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/fake_layer.h b/src/connectivity/bluetooth/core/bt-host/gatt/fake_layer.h index 4a88784aba6c6ea6c05664d9a88aab63567aac98..b01b266ae68c9c6348f27f4878b758dee3d8141d 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/fake_layer.h +++ b/src/connectivity/bluetooth/core/bt-host/gatt/fake_layer.h @@ -34,7 +34,7 @@ class FakeLayer final : public GATT { void DiscoverServices(PeerId peer_id) override; void RegisterRemoteServiceWatcher(RemoteServiceWatcher callback, async_dispatcher_t* dispatcher) override; - void ListServices(PeerId peer_id, std::vector<common::UUID> uuids, + void ListServices(PeerId peer_id, std::vector<UUID> uuids, ServiceListCallback callback) override; void FindService(PeerId peer_id, IdType service_id, RemoteServiceCallback callback) override; diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/gatt.cc b/src/connectivity/bluetooth/core/bt-host/gatt/gatt.cc index 958015f32393a258280a5fb8bf47b456f7d14a34..860eea5582ddcefa0b2cc12cd29ff1c251d9d144 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/gatt.cc +++ b/src/connectivity/bluetooth/core/bt-host/gatt/gatt.cc @@ -22,8 +22,8 @@ namespace bt { namespace gatt { namespace { -class Impl final : public GATT, common::TaskDomain<Impl, GATT> { - using TaskDomainBase = common::TaskDomain<Impl, GATT>; +class Impl final : public GATT, TaskDomain<Impl, GATT> { + using TaskDomainBase = TaskDomain<Impl, GATT>; public: explicit Impl(async_dispatcher_t* gatt_dispatcher) @@ -42,7 +42,7 @@ class Impl final : public GATT, common::TaskDomain<Impl, GATT> { // Forwards Service Changed payloads to clients. auto send_indication_callback = [this](PeerId peer_id, att::Handle handle, - const common::ByteBuffer& value) { + const ByteBuffer& value) { auto iter = connections_.find(peer_id); if (iter == connections_.end()) { bt_log(WARN, "gatt", "peer not registered: %s", bt_str(peer_id)); @@ -176,8 +176,7 @@ class Impl final : public GATT, common::TaskDomain<Impl, GATT> { } iter->second.server()->SendNotification( - config.handle, common::BufferView(value.data(), value.size()), - indicate); + config.handle, BufferView(value.data(), value.size()), indicate); }); } @@ -207,7 +206,7 @@ class Impl final : public GATT, common::TaskDomain<Impl, GATT> { }); } - void ListServices(PeerId peer_id, std::vector<common::UUID> uuids, + void ListServices(PeerId peer_id, std::vector<UUID> uuids, ServiceListCallback callback) override { ZX_DEBUG_ASSERT(callback); PostMessage([this, peer_id, callback = std::move(callback), @@ -215,7 +214,7 @@ class Impl final : public GATT, common::TaskDomain<Impl, GATT> { auto iter = connections_.find(peer_id); if (iter == connections_.end()) { // Connection not found. - callback(att::Status(common::HostError::kNotFound), ServiceList()); + callback(att::Status(HostError::kNotFound), ServiceList()); return; } iter->second.remote_service_manager()->ListServices(uuids, diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/gatt.h b/src/connectivity/bluetooth/core/bt-host/gatt/gatt.h index 2dd7699c84152a861da69721fe989f32ecc31535..f53a452639fe68836a578a7739aa1d33be24afee 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/gatt.h +++ b/src/connectivity/bluetooth/core/bt-host/gatt/gatt.h @@ -148,7 +148,7 @@ class GATT : public fbl::RefCounted<GATT> { // discovered. If the connection is removed without discovery services, // |callback| will be called with an error status. |callback| will always run // on the GATT loop. - virtual void ListServices(PeerId peer_id, std::vector<common::UUID> uuids, + virtual void ListServices(PeerId peer_id, std::vector<UUID> uuids, ServiceListCallback callback) = 0; // Connects the RemoteService with the given identifier found on the diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/gatt_defs.cc b/src/connectivity/bluetooth/core/bt-host/gatt/gatt_defs.cc index cf29eeaeb28fe3dbde3924e95c59aa4c65cffee9..c2a1fa0359e398b2ec76c692c3f0c564406d4834 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/gatt_defs.cc +++ b/src/connectivity/bluetooth/core/bt-host/gatt/gatt_defs.cc @@ -7,21 +7,18 @@ namespace bt { namespace gatt { -ServiceData::ServiceData(att::Handle start, - att::Handle end, - const common::UUID& type) +ServiceData::ServiceData(att::Handle start, att::Handle end, const UUID& type) : range_start(start), range_end(end), type(type) {} -CharacteristicData::CharacteristicData(Properties props, - att::Handle handle, +CharacteristicData::CharacteristicData(Properties props, att::Handle handle, att::Handle value_handle, - const common::UUID& type) + const UUID& type) : properties(props), handle(handle), value_handle(value_handle), type(type) {} -DescriptorData::DescriptorData(att::Handle handle, const common::UUID& type) +DescriptorData::DescriptorData(att::Handle handle, const UUID& type) : handle(handle), type(type) {} } // namespace gatt diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/gatt_defs.h b/src/connectivity/bluetooth/core/bt-host/gatt/gatt_defs.h index bfbf1aa9c2888b9e0a3db723b124c82e38216ac7..505116edf7f2193daf39b7f01b19e9433172cf91 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/gatt_defs.h +++ b/src/connectivity/bluetooth/core/bt-host/gatt/gatt_defs.h @@ -28,25 +28,20 @@ constexpr uint16_t kCharacteristicAggregateFormat16 = 0x2905; constexpr uint16_t kGenericAttributeService16 = 0x1801; constexpr uint16_t kServiceChangedCharacteristic16 = 0x2a05; -constexpr common::UUID kPrimaryService(kPrimaryService16); -constexpr common::UUID kSecondaryService(kSecondaryService16); -constexpr common::UUID kIncludeDeclaration(kIncludeDeclaration16); -constexpr common::UUID kCharacteristicDeclaration(kCharacteristicDeclaration16); -constexpr common::UUID kCharacteristicExtProperties( - kCharacteristicExtProperties16); -constexpr common::UUID kCharacteristicUserDescription( - kCharacteristicUserDescription16); -constexpr common::UUID kClientCharacteristicConfig( - kClientCharacteristicConfig16); -constexpr common::UUID kServerCharacteristicConfig( - kServerCharacteristicConfig16); -constexpr common::UUID kCharacteristicFormat(kCharacteristicFormat16); -constexpr common::UUID kCharacteristicAggregateFormat( - kCharacteristicAggregateFormat16); +constexpr UUID kPrimaryService(kPrimaryService16); +constexpr UUID kSecondaryService(kSecondaryService16); +constexpr UUID kIncludeDeclaration(kIncludeDeclaration16); +constexpr UUID kCharacteristicDeclaration(kCharacteristicDeclaration16); +constexpr UUID kCharacteristicExtProperties(kCharacteristicExtProperties16); +constexpr UUID kCharacteristicUserDescription(kCharacteristicUserDescription16); +constexpr UUID kClientCharacteristicConfig(kClientCharacteristicConfig16); +constexpr UUID kServerCharacteristicConfig(kServerCharacteristicConfig16); +constexpr UUID kCharacteristicFormat(kCharacteristicFormat16); +constexpr UUID kCharacteristicAggregateFormat(kCharacteristicAggregateFormat16); // Defined Generic Attribute Profile Service (Vol 3, Part G, 7) -constexpr bt::common::UUID kGenericAttributeService(kGenericAttributeService16); -constexpr bt::common::UUID kServiceChangedCharacteristic( +constexpr bt::UUID kGenericAttributeService(kGenericAttributeService16); +constexpr bt::UUID kServiceChangedCharacteristic( kServiceChangedCharacteristic16); } // namespace types @@ -77,7 +72,7 @@ using ExtendedProperties = uint16_t; constexpr uint16_t kCCCNotificationBit = 0x0001; constexpr uint16_t kCCCIndicationBit = 0x0002; -using PeerId = common::PeerId; +using PeerId = PeerId; // An identifier uniquely identifies a service, characteristic, or descriptor. using IdType = uint64_t; @@ -89,30 +84,30 @@ constexpr IdType kInvalidId = 0u; struct ServiceData { ServiceData() = default; - ServiceData(att::Handle start, att::Handle end, const common::UUID& type); + ServiceData(att::Handle start, att::Handle end, const UUID& type); att::Handle range_start; att::Handle range_end; - common::UUID type; + UUID type; }; struct CharacteristicData { CharacteristicData() = default; CharacteristicData(Properties props, att::Handle handle, - att::Handle value_handle, const common::UUID& type); + att::Handle value_handle, const UUID& type); Properties properties; att::Handle handle; att::Handle value_handle; - common::UUID type; + UUID type; }; struct DescriptorData { DescriptorData() = default; - DescriptorData(att::Handle handle, const common::UUID& type); + DescriptorData(att::Handle handle, const UUID& type); att::Handle handle; - common::UUID type; + UUID type; }; } // namespace gatt diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/generic_attribute_service.cc b/src/connectivity/bluetooth/core/bt-host/gatt/generic_attribute_service.cc index 42b50cb58bb65d28921ff3bfdfce67772238feaa..b74b88a86c43b387e3e785f83b30bf856a79615b 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/generic_attribute_service.cc +++ b/src/connectivity/bluetooth/core/bt-host/gatt/generic_attribute_service.cc @@ -17,7 +17,7 @@ namespace { void NopReadHandler(IdType, IdType, uint16_t, const ReadResponder&) {} -void NopWriteHandler(IdType, IdType, uint16_t, const common::ByteBuffer&, +void NopWriteHandler(IdType, IdType, uint16_t, const ByteBuffer&, const WriteResponder&) {} } // namespace @@ -103,7 +103,7 @@ void GenericAttributeService::OnServiceChanged(IdType service_id, return; } - common::StaticByteBuffer<2 * sizeof(uint16_t)> value; + StaticByteBuffer<2 * sizeof(uint16_t)> value; value[0] = static_cast<uint8_t>(start); value[1] = static_cast<uint8_t>(start >> 8); diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/generic_attribute_service.h b/src/connectivity/bluetooth/core/bt-host/gatt/generic_attribute_service.h index 3bedb6733ca2e0db2192d76f48d43bba08df7a1c..07779f0a1c983af257468e64a96895d9703a8c52 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/generic_attribute_service.h +++ b/src/connectivity/bluetooth/core/bt-host/gatt/generic_attribute_service.h @@ -20,7 +20,7 @@ namespace gatt { // inject the GATT object's notification sending functionality (avoiding this // service from carrying a reference to GATT or Server). using SendIndicationCallback = fit::function<void( - PeerId peer_id, att::Handle handle, const common::ByteBuffer& value)>; + PeerId peer_id, att::Handle handle, const ByteBuffer& value)>; // Implements the "Generic Attribute Profile Service" containing the "Service // Changed" characteristic that is "...used to indicate to connected devices diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/generic_attribute_service_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gatt/generic_attribute_service_unittest.cc index b6eb21d87c3a16c09e39626351bd2c9763093421..294d2e4ebea1939430b7387b3b112ab0201819ad 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/generic_attribute_service_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/gatt/generic_attribute_service_unittest.cc @@ -14,10 +14,10 @@ namespace gatt { namespace { void NopReadHandler(IdType, IdType, uint16_t, const ReadResponder&) {} -void NopWriteHandler(IdType, IdType, uint16_t, const common::ByteBuffer&, +void NopWriteHandler(IdType, IdType, uint16_t, const ByteBuffer&, const WriteResponder&) {} void NopCCCallback(IdType, IdType, PeerId, bool notify, bool indicate) {} -void NopSendIndication(PeerId, att::Handle, const common::ByteBuffer&) {} +void NopSendIndication(PeerId, att::Handle, const ByteBuffer&) {} // Handles for the third attribute (Service Changed characteristic) and fourth // attribute (corresponding client config). @@ -36,8 +36,8 @@ class GATT_GenericAttributeServiceTest : public ::testing::Test { ZX_DEBUG_ASSERT(attr); auto result_cb = [&out_ecode](auto cb_code) { *out_ecode = cb_code; }; uint16_t value = htole16(ccc_value); - return attr->WriteAsync( - peer_id, 0u, common::BufferView(&value, sizeof(value)), result_cb); + return attr->WriteAsync(peer_id, 0u, BufferView(&value, sizeof(value)), + result_cb); } LocalServiceManager mgr; @@ -75,7 +75,7 @@ TEST_F(GATT_GenericAttributeServiceTest, RegisterUnregister) { TEST_F(GATT_GenericAttributeServiceTest, IndicateOnRegister) { int callback_count = 0; auto send_indication = [&](PeerId peer_id, att::Handle handle, - const common::ByteBuffer& value) { + const ByteBuffer& value) { EXPECT_EQ(kTestPeerId, peer_id); EXPECT_EQ(kChrcHandle, handle); ASSERT_EQ(4u, value.size()); @@ -97,10 +97,10 @@ TEST_F(GATT_GenericAttributeServiceTest, IndicateOnRegister) { WriteServiceChangedCCC(kTestPeerId, kEnableInd, &ecode); EXPECT_EQ(0, callback_count); - constexpr common::UUID kTestSvcType((uint32_t)0xdeadbeef); + constexpr UUID kTestSvcType((uint32_t)0xdeadbeef); constexpr IdType kChrcId = 0; constexpr uint8_t kChrcProps = Property::kRead; - constexpr common::UUID kTestChrcType((uint32_t)0xdeadbeef); + constexpr UUID kTestChrcType((uint32_t)0xdeadbeef); const att::AccessRequirements kReadReqs(true, true, true); const att::AccessRequirements kWriteReqs, kUpdateReqs; auto service = std::make_unique<Service>(false /* primary */, kTestSvcType); @@ -118,7 +118,7 @@ TEST_F(GATT_GenericAttributeServiceTest, IndicateOnRegister) { TEST_F(GATT_GenericAttributeServiceTest, IndicateOnUnregister) { int callback_count = 0; auto send_indication = [&](PeerId peer_id, att::Handle handle, - const common::ByteBuffer& value) { + const ByteBuffer& value) { EXPECT_EQ(kTestPeerId, peer_id); EXPECT_EQ(kChrcHandle, handle); ASSERT_EQ(4u, value.size()); @@ -135,10 +135,10 @@ TEST_F(GATT_GenericAttributeServiceTest, IndicateOnUnregister) { // Register the GATT service. GenericAttributeService gatt_service(&mgr, std::move(send_indication)); - constexpr common::UUID kTestSvcType((uint32_t)0xdeadbeef); + constexpr UUID kTestSvcType((uint32_t)0xdeadbeef); constexpr IdType kChrcId = 0; constexpr uint8_t kChrcProps = Property::kNotify; - constexpr common::UUID kTestChrcType((uint32_t)0xdeadbeef); + constexpr UUID kTestChrcType((uint32_t)0xdeadbeef); const att::AccessRequirements kReadReqs, kWriteReqs; const att::AccessRequirements kUpdateReqs(true, true, true); auto service = std::make_unique<Service>(false /* primary */, kTestSvcType); diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/local_service_manager.cc b/src/connectivity/bluetooth/core/bt-host/gatt/local_service_manager.cc index ab1ce005c7b9cae70a691807e795abedb98d2b20..a5dca1fd9cc24cef4ef4ff06495052d2cd25a788 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/local_service_manager.cc +++ b/src/connectivity/bluetooth/core/bt-host/gatt/local_service_manager.cc @@ -48,7 +48,7 @@ att::Handle InsertCharacteristicAttributes( // 1 octet: properties // 2 octets: value handle // 2 or 16 octets: UUID - common::DynamicByteBuffer decl_value(3 + uuid_size); + DynamicByteBuffer decl_value(3 + uuid_size); decl_value[0] = chrc.properties(); decl_value[1] = static_cast<uint8_t>(value_attr->handle()); decl_value[2] = static_cast<uint8_t>(value_attr->handle() >> 8); @@ -62,7 +62,7 @@ att::Handle InsertCharacteristicAttributes( // Adds a characteristic descriptor declaration to |grouping| for |desc|. void InsertDescriptorAttribute(att::AttributeGrouping* grouping, - const common::UUID& type, + const UUID& type, const att::AccessRequirements& read_reqs, const att::AccessRequirements& write_reqs, att::Attribute::ReadHandler read_handler, @@ -247,16 +247,15 @@ class LocalServiceManager::ServiceData final { } value = htole16(value); - result_cb(att::ErrorCode::kNoError, - common::BufferView(reinterpret_cast<const uint8_t*>(&value), - sizeof(value))); + result_cb( + att::ErrorCode::kNoError, + BufferView(reinterpret_cast<const uint8_t*>(&value), sizeof(value))); } // Called when a write request is performed on a CCC descriptor belonging to // the characteristic identified by |chrc_id|. void OnWriteCCC(IdType chrc_id, uint8_t chrc_props, PeerId peer_id, - att::Handle handle, uint16_t offset, - const common::ByteBuffer& value, + att::Handle handle, uint16_t offset, const ByteBuffer& value, const WriteResponder& result_cb) { if (offset != 0u) { result_cb(att::ErrorCode::kInvalidOffset); @@ -314,7 +313,7 @@ class LocalServiceManager::ServiceData final { att::Handle handle, uint16_t offset, auto result_cb) { if (!self) { - result_cb(att::ErrorCode::kUnlikelyError, common::BufferView()); + result_cb(att::ErrorCode::kUnlikelyError, BufferView()); return; } @@ -322,7 +321,7 @@ class LocalServiceManager::ServiceData final { // characteristic property. if (!(props & Property::kRead)) { // TODO(armansito): Return kRequestNotSupported? - result_cb(att::ErrorCode::kReadNotPermitted, common::BufferView()); + result_cb(att::ErrorCode::kReadNotPermitted, BufferView()); return; } @@ -365,7 +364,7 @@ class LocalServiceManager::ServiceData final { att::AccessRequirements(false, false, false), // read (no security) att::AccessRequirements()); // write (not allowed) ZX_DEBUG_ASSERT(decl_attr); - decl_attr->SetValue(common::CreateStaticByteBuffer( + decl_attr->SetValue(CreateStaticByteBuffer( (uint8_t)(ext_props & 0x00FF), (uint8_t)((ext_props & 0xFF00) >> 8))); } @@ -392,7 +391,7 @@ class LocalServiceManager::ServiceData final { const auto& peer_id, att::Handle handle, uint16_t offset, auto result_cb) { if (!self) { - result_cb(att::ErrorCode::kUnlikelyError, common::BufferView()); + result_cb(att::ErrorCode::kUnlikelyError, BufferView()); return; } @@ -438,7 +437,7 @@ class LocalServiceManager::ServiceData final { const auto& peer_id, att::Handle handle, uint16_t offset, auto result_cb) { if (!self) { - result_cb(att::ErrorCode::kUnlikelyError, common::BufferView()); + result_cb(att::ErrorCode::kUnlikelyError, BufferView()); return; } @@ -508,7 +507,7 @@ IdType LocalServiceManager::RegisterService(ServicePtr service, return kInvalidId; // GATT does not support 32-bit UUIDs. - const common::BufferView service_decl_value = + const BufferView service_decl_value = service->type().CompactView(false /* allow_32bit */); // TODO(armansito): Cluster services with 16-bit and 128-bit together inside diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/local_service_manager.h b/src/connectivity/bluetooth/core/bt-host/gatt/local_service_manager.h index 4caf86759413dad6612c18ae37ce0c1dc5abaf8a..06bab87fc033113d48097cd9c2fd03e7eb31d1cb 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/local_service_manager.h +++ b/src/connectivity/bluetooth/core/bt-host/gatt/local_service_manager.h @@ -40,9 +40,9 @@ using ReadHandler = fit::function<void( // if the client has initiated a "Write Without Response" // procedure, in which case a response is not required. using WriteResponder = att::Attribute::WriteResultCallback; -using WriteHandler = fit::function<void( - IdType service_id, IdType id, uint16_t offset, - const common::ByteBuffer& value, WriteResponder responder)>; +using WriteHandler = + fit::function<void(IdType service_id, IdType id, uint16_t offset, + const ByteBuffer& value, WriteResponder responder)>; // Called when the peer device with the given |peer_id| has enabled or disabled // notifications/indications on the characteristic with id |chrc_id|. diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/local_service_manager_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gatt/local_service_manager_unittest.cc index 5d7d084d510a7f2503cbfb6019d0d2e6d64b72e7..0a784ef485b7d45a2d86462f98a42a5f8c7e360b 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/local_service_manager_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/gatt/local_service_manager_unittest.cc @@ -16,8 +16,8 @@ namespace { constexpr PeerId kTestPeerId(1); constexpr PeerId kTestPeerId2(2); -constexpr common::UUID kTestType16((uint16_t)0xdead); -constexpr common::UUID kTestType32((uint32_t)0xdeadbeef); +constexpr UUID kTestType16((uint16_t)0xdead); +constexpr UUID kTestType32((uint32_t)0xdeadbeef); // The first characteristic value attribute of the first service has handle // number 3. @@ -32,7 +32,7 @@ inline att::AccessRequirements AllowedNoSecurity() { } void NopReadHandler(IdType, IdType, uint16_t, const ReadResponder&) {} -void NopWriteHandler(IdType, IdType, uint16_t, const common::ByteBuffer&, +void NopWriteHandler(IdType, IdType, uint16_t, const ByteBuffer&, const WriteResponder&) {} void NopCCCallback(IdType service_id, IdType chrc_id, PeerId peer_id, bool notify, bool indicate) {} @@ -69,8 +69,8 @@ TEST(GATT_LocalServiceManagerTest, EmptyService) { EXPECT_EQ(0x0001, iter->start_handle()); EXPECT_EQ(0x0001, iter->end_handle()); EXPECT_EQ(types::kPrimaryService, iter->group_type()); - EXPECT_TRUE(common::ContainersEqual( - common::CreateStaticByteBuffer(0xad, 0xde), iter->decl_value())); + EXPECT_TRUE( + ContainersEqual(CreateStaticByteBuffer(0xad, 0xde), iter->decl_value())); iter++; @@ -80,10 +80,9 @@ TEST(GATT_LocalServiceManagerTest, EmptyService) { EXPECT_EQ(0x0002, iter->start_handle()); EXPECT_EQ(0x0002, iter->end_handle()); EXPECT_EQ(types::kSecondaryService, iter->group_type()); - EXPECT_TRUE(common::ContainersEqual( - common::CreateStaticByteBuffer(0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, - 0x80, 0x00, 0x10, 0x00, 0x00, 0xef, 0xbe, - 0xad, 0xde), + EXPECT_TRUE(ContainersEqual( + CreateStaticByteBuffer(0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0xef, 0xbe, 0xad, 0xde), iter->decl_value())); } @@ -111,7 +110,7 @@ TEST(GATT_LocalServiceManagerTest, RegisterCharacteristic) { constexpr IdType kChrcId = 0; constexpr uint8_t kChrcProps = Property::kRead; - constexpr common::UUID kTestChrcType((uint16_t)0xabcd); + constexpr UUID kTestChrcType((uint16_t)0xabcd); const att::AccessRequirements kReadReqs(true, true, true); const att::AccessRequirements kWriteReqs, kUpdateReqs; @@ -140,13 +139,13 @@ TEST(GATT_LocalServiceManagerTest, RegisterCharacteristic) { EXPECT_TRUE(attrs[1].value()); // clang-format off - const auto kDeclValue = common::CreateStaticByteBuffer( + const auto kDeclValue = CreateStaticByteBuffer( 0x02, // properties 0x03, 0x00, // value handle 0xcd, 0xab // UUID ); // clang-format on - EXPECT_TRUE(common::ContainersEqual(kDeclValue, *attrs[1].value())); + EXPECT_TRUE(ContainersEqual(kDeclValue, *attrs[1].value())); // Characteristic value EXPECT_EQ(srvc_handle + 2, attrs[2].handle()); @@ -163,7 +162,7 @@ TEST(GATT_LocalServiceManagerTest, RegisterCharacteristic32) { constexpr IdType kChrcId = 0; constexpr uint8_t kChrcProps = Property::kRead; - constexpr common::UUID kTestChrcType((uint32_t)0xdeadbeef); + constexpr UUID kTestChrcType((uint32_t)0xdeadbeef); const att::AccessRequirements kReadReqs(true, true, true); const att::AccessRequirements kWriteReqs, kUpdateReqs; @@ -191,14 +190,14 @@ TEST(GATT_LocalServiceManagerTest, RegisterCharacteristic32) { EXPECT_EQ(att::AccessRequirements(), attrs[1].write_reqs()); EXPECT_TRUE(attrs[1].value()); - const auto kDeclValue = common::CreateStaticByteBuffer( - 0x02, // properties - 0x03, 0x00, // value handle + const auto kDeclValue = + CreateStaticByteBuffer(0x02, // properties + 0x03, 0x00, // value handle - // The 32-bit UUID will be stored as 128-bit - 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, - 0xef, 0xbe, 0xad, 0xde); - EXPECT_TRUE(common::ContainersEqual(kDeclValue, *attrs[1].value())); + // The 32-bit UUID will be stored as 128-bit + 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0xef, 0xbe, 0xad, 0xde); + EXPECT_TRUE(ContainersEqual(kDeclValue, *attrs[1].value())); // Characteristic value EXPECT_EQ(srvc_handle + 2, attrs[2].handle()); @@ -215,9 +214,9 @@ TEST(GATT_LocalServiceManagerTest, RegisterCharacteristic128) { constexpr IdType kChrcId = 0; constexpr uint8_t kChrcProps = Property::kRead; - common::UUID kTestChrcType; - EXPECT_TRUE(common::StringToUuid("00112233-4455-6677-8899-AABBCCDDEEFF", - &kTestChrcType)); + UUID kTestChrcType; + EXPECT_TRUE( + StringToUuid("00112233-4455-6677-8899-AABBCCDDEEFF", &kTestChrcType)); const att::AccessRequirements kReadReqs(true, true, true); const att::AccessRequirements kWriteReqs, kUpdateReqs; @@ -245,14 +244,14 @@ TEST(GATT_LocalServiceManagerTest, RegisterCharacteristic128) { EXPECT_EQ(att::AccessRequirements(), attrs[1].write_reqs()); EXPECT_TRUE(attrs[1].value()); - const auto kDeclValue = common::CreateStaticByteBuffer( - 0x02, // properties - 0x03, 0x00, // value handle + const auto kDeclValue = + CreateStaticByteBuffer(0x02, // properties + 0x03, 0x00, // value handle - // 128-bit UUID - 0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, - 0x33, 0x22, 0x11, 0x00); - EXPECT_TRUE(common::ContainersEqual(kDeclValue, *attrs[1].value())); + // 128-bit UUID + 0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, 0x99, 0x88, + 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00); + EXPECT_TRUE(ContainersEqual(kDeclValue, *attrs[1].value())); // Characteristic value EXPECT_EQ(srvc_handle + 2, attrs[2].handle()); @@ -267,7 +266,7 @@ TEST(GATT_LocalServiceManagerTest, RegisterCharacteristic128) { TEST(GATT_LocalServiceManagerTest, ExtPropSetSuccess) { LocalServiceManager mgr; const att::AccessRequirements kReadReqs, kWriteReqs, kUpdateReqs; - constexpr common::UUID kChrcType16((uint16_t)0x1234); + constexpr UUID kChrcType16((uint16_t)0x1234); constexpr IdType kChrcId = 5; auto service = std::make_unique<Service>(true /* primary */, kTestType16); @@ -285,8 +284,8 @@ TEST(GATT_LocalServiceManagerTest, ExtPropSetSuccess) { const auto& attrs = grouping.attributes(); ASSERT_EQ(4u, attrs.size()); EXPECT_EQ(types::kCharacteristicExtProperties, attrs[3].type()); - EXPECT_TRUE(common::ContainersEqual( // Reliable Write property - common::CreateStaticByteBuffer(0x01, 0x00), *attrs[3].value())); + EXPECT_TRUE(ContainersEqual( // Reliable Write property + CreateStaticByteBuffer(0x01, 0x00), *attrs[3].value())); } // tests that the extended properties descriptor cannot be set externally @@ -294,8 +293,8 @@ TEST(GATT_LocalServiceManagerTest, ExtPropSetFailure) { LocalServiceManager mgr; const att::AccessRequirements kReadReqs, kWriteReqs, kUpdateReqs; - constexpr common::UUID kChrcType16((uint16_t)0x1234); - constexpr common::UUID kDescType16((uint16_t)0x2900); // UUID for Ext Prop + constexpr UUID kChrcType16((uint16_t)0x1234); + constexpr UUID kDescType16((uint16_t)0x2900); // UUID for Ext Prop auto service = std::make_unique<Service>(true /* primary */, kTestType16); auto chrc = std::make_unique<Characteristic>(0, kChrcType16, 0, 0, kReadReqs, @@ -311,8 +310,8 @@ TEST(GATT_LocalServiceManagerTest, RegisterCharacteristicSorted) { LocalServiceManager mgr; const att::AccessRequirements kReadReqs, kWriteReqs, kUpdateReqs; - constexpr common::UUID kType16((uint16_t)0xbeef); - constexpr common::UUID kType128((uint32_t)0xdeadbeef); + constexpr UUID kType16((uint16_t)0xbeef); + constexpr UUID kType128((uint32_t)0xdeadbeef); constexpr IdType kChrcId0 = 0; constexpr uint8_t kChrcProps0 = 0; @@ -358,8 +357,8 @@ TEST(GATT_LocalServiceManagerTest, RegisterDescriptor) { LocalServiceManager mgr; const att::AccessRequirements kReadReqs, kWriteReqs, kUpdateReqs; - constexpr common::UUID kChrcType16((uint16_t)0x1234); - constexpr common::UUID kDescType16((uint16_t)0x5678); + constexpr UUID kChrcType16((uint16_t)0x1234); + constexpr UUID kDescType16((uint16_t)0x5678); auto service = std::make_unique<Service>(true /* primary */, kTestType16); auto chrc = std::make_unique<Characteristic>(0, kChrcType16, 0, 0, kReadReqs, @@ -385,7 +384,7 @@ TEST(GATT_LocalServiceManagerTest, DuplicateChrcIds) { LocalServiceManager mgr; const att::AccessRequirements kReadReqs, kWriteReqs, kUpdateReqs; - constexpr common::UUID kChrcType16((uint16_t)0x1234); + constexpr UUID kChrcType16((uint16_t)0x1234); auto service = std::make_unique<Service>(true /* primary */, kTestType16); @@ -402,8 +401,8 @@ TEST(GATT_LocalServiceManagerTest, DuplicateDescIds) { LocalServiceManager mgr; const att::AccessRequirements kReadReqs, kWriteReqs, kUpdateReqs; - constexpr common::UUID kChrcType16((uint16_t)0x1234); - constexpr common::UUID kDescType16((uint16_t)0x5678); + constexpr UUID kChrcType16((uint16_t)0x1234); + constexpr UUID kDescType16((uint16_t)0x5678); auto service = std::make_unique<Service>(true /* primary */, kTestType16); @@ -423,8 +422,8 @@ TEST(GATT_LocalServiceManagerTest, DuplicateChrcAndDescIds) { LocalServiceManager mgr; const att::AccessRequirements kReadReqs, kWriteReqs, kUpdateReqs; - constexpr common::UUID kChrcType16((uint16_t)0x1234); - constexpr common::UUID kDescType16((uint16_t)0x5678); + constexpr UUID kChrcType16((uint16_t)0x1234); + constexpr UUID kDescType16((uint16_t)0x5678); auto service = std::make_unique<Service>(true /* primary */, kTestType16); @@ -441,7 +440,7 @@ TEST(GATT_LocalServiceManagerTest, DuplicateChrcAndDescIds) { TEST(GATT_LocalServiceManagerTest, ReadCharacteristicNoReadPermission) { LocalServiceManager mgr; const att::AccessRequirements kReadReqs, kWriteReqs, kUpdateReqs; - constexpr common::UUID kChrcType16((uint16_t)0x1234); + constexpr UUID kChrcType16((uint16_t)0x1234); constexpr IdType kChrcId = 5; auto service = std::make_unique<Service>(true /* primary */, kTestType16); @@ -470,7 +469,7 @@ TEST(GATT_LocalServiceManagerTest, ReadCharacteristicNoReadPermission) { TEST(GATT_LocalServiceManagerTest, ReadCharacteristicNoReadProperty) { LocalServiceManager mgr; - constexpr common::UUID kChrcType16((uint16_t)0x1234); + constexpr UUID kChrcType16((uint16_t)0x1234); constexpr IdType kChrcId = 5; // Characteristic is readable but doesn't have the "read" property. @@ -502,11 +501,11 @@ TEST(GATT_LocalServiceManagerTest, ReadCharacteristicNoReadProperty) { TEST(GATT_LocalServiceManagerTest, ReadCharacteristic) { LocalServiceManager mgr; - constexpr common::UUID kChrcType16((uint16_t)0x1234); + constexpr UUID kChrcType16((uint16_t)0x1234); constexpr IdType kChrcId = 5; constexpr uint16_t kOffset = 10; - const auto kTestValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kTestValue = CreateStaticByteBuffer('f', 'o', 'o'); auto kReadReqs = AllowedNoSecurity(); const att::AccessRequirements kWriteReqs, kUpdateReqs; @@ -536,7 +535,7 @@ TEST(GATT_LocalServiceManagerTest, ReadCharacteristic) { att::ErrorCode ecode = att::ErrorCode::kUnlikelyError; auto result_cb = [&ecode, &kTestValue](auto code, const auto& value) { ecode = code; - EXPECT_TRUE(common::ContainersEqual(kTestValue, value)); + EXPECT_TRUE(ContainersEqual(kTestValue, value)); }; EXPECT_TRUE(attr->ReadAsync(kTestPeerId, kOffset, std::move(result_cb))); @@ -548,9 +547,9 @@ TEST(GATT_LocalServiceManagerTest, ReadCharacteristic) { TEST(GATT_LocalServiceManagerTest, WriteCharacteristicNoWritePermission) { LocalServiceManager mgr; const att::AccessRequirements kReadReqs, kWriteReqs, kUpdateReqs; - constexpr common::UUID kChrcType16((uint16_t)0x1234); + constexpr UUID kChrcType16((uint16_t)0x1234); constexpr IdType kChrcId = 5; - const common::BufferView kTestValue; + const BufferView kTestValue; auto service = std::make_unique<Service>(true /* primary */, kTestType16); service->AddCharacteristic( @@ -578,9 +577,9 @@ TEST(GATT_LocalServiceManagerTest, WriteCharacteristicNoWritePermission) { TEST(GATT_LocalServiceManagerTest, WriteCharacteristicNoWriteProperty) { LocalServiceManager mgr; - constexpr common::UUID kChrcType16((uint16_t)0x1234); + constexpr UUID kChrcType16((uint16_t)0x1234); constexpr IdType kChrcId = 5; - const common::BufferView kTestValue; + const BufferView kTestValue; const att::AccessRequirements kReadReqs, kUpdateReqs; auto kWriteReqs = AllowedNoSecurity(); @@ -612,11 +611,11 @@ TEST(GATT_LocalServiceManagerTest, WriteCharacteristicNoWriteProperty) { TEST(GATT_LocalServiceManagerTest, WriteCharacteristic) { LocalServiceManager mgr; - constexpr common::UUID kChrcType16((uint16_t)0x1234); + constexpr UUID kChrcType16((uint16_t)0x1234); constexpr IdType kChrcId = 5; constexpr uint16_t kOffset = 10; - const auto kTestValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kTestValue = CreateStaticByteBuffer('f', 'o', 'o'); const att::AccessRequirements kReadReqs, kUpdateReqs; auto kWriteReqs = AllowedNoSecurity(); @@ -634,7 +633,7 @@ TEST(GATT_LocalServiceManagerTest, WriteCharacteristic) { EXPECT_EQ(svc_id, cb_svc_id); EXPECT_EQ(kChrcId, id); EXPECT_EQ(kOffset, offset); - EXPECT_TRUE(common::ContainersEqual(kTestValue, value)); + EXPECT_TRUE(ContainersEqual(kTestValue, value)); responder(att::ErrorCode::kNoError); }; @@ -659,8 +658,8 @@ TEST(GATT_LocalServiceManagerTest, WriteCharacteristic) { TEST(GATT_LocalServiceManagerTest, ReadDescriptorNoReadPermission) { LocalServiceManager mgr; const att::AccessRequirements kReadReqs, kWriteReqs, kUpdateReqs; - constexpr common::UUID kChrcType16((uint16_t)0x1234); - constexpr common::UUID kDescType16((uint16_t)0x5678); + constexpr UUID kChrcType16((uint16_t)0x1234); + constexpr UUID kDescType16((uint16_t)0x5678); constexpr IdType kChrcId = 0; constexpr IdType kDescId = 1; @@ -692,13 +691,13 @@ TEST(GATT_LocalServiceManagerTest, ReadDescriptorNoReadPermission) { TEST(GATT_LocalServiceManagerTest, ReadDescriptor) { LocalServiceManager mgr; - constexpr common::UUID kChrcType16((uint16_t)0x1234); - constexpr common::UUID kDescType16((uint16_t)0x5678); + constexpr UUID kChrcType16((uint16_t)0x1234); + constexpr UUID kDescType16((uint16_t)0x5678); constexpr IdType kChrcId = 0; constexpr IdType kDescId = 1; constexpr uint16_t kOffset = 10; - const auto kTestValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kTestValue = CreateStaticByteBuffer('f', 'o', 'o'); auto kReadReqs = AllowedNoSecurity(); const att::AccessRequirements kWriteReqs, kUpdateReqs; @@ -731,7 +730,7 @@ TEST(GATT_LocalServiceManagerTest, ReadDescriptor) { att::ErrorCode ecode = att::ErrorCode::kUnlikelyError; auto result_cb = [&ecode, &kTestValue](auto code, const auto& value) { ecode = code; - EXPECT_TRUE(common::ContainersEqual(kTestValue, value)); + EXPECT_TRUE(ContainersEqual(kTestValue, value)); }; EXPECT_TRUE(attr->ReadAsync(kTestPeerId, kOffset, std::move(result_cb))); @@ -743,11 +742,11 @@ TEST(GATT_LocalServiceManagerTest, ReadDescriptor) { TEST(GATT_LocalServiceManagerTest, WriteDescriptorNoWritePermission) { LocalServiceManager mgr; const att::AccessRequirements kReadReqs, kWriteReqs, kUpdateReqs; - constexpr common::UUID kChrcType16((uint16_t)0x1234); - constexpr common::UUID kDescType16((uint16_t)0x5678); + constexpr UUID kChrcType16((uint16_t)0x1234); + constexpr UUID kDescType16((uint16_t)0x5678); constexpr IdType kChrcId = 0; constexpr IdType kDescId = 1; - const common::BufferView kTestValue; + const BufferView kTestValue; auto service = std::make_unique<Service>(true /* primary */, kTestType16); auto chrc = std::make_unique<Characteristic>( @@ -776,13 +775,13 @@ TEST(GATT_LocalServiceManagerTest, WriteDescriptorNoWritePermission) { TEST(GATT_LocalServiceManagerTest, WriteDescriptor) { LocalServiceManager mgr; - constexpr common::UUID kChrcType16((uint16_t)0x1234); - constexpr common::UUID kDescType16((uint16_t)0x5678); + constexpr UUID kChrcType16((uint16_t)0x1234); + constexpr UUID kDescType16((uint16_t)0x5678); constexpr IdType kChrcId = 0; constexpr IdType kDescId = 1; constexpr uint16_t kOffset = 10; - const auto kTestValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kTestValue = CreateStaticByteBuffer('f', 'o', 'o'); const att::AccessRequirements kReadReqs, kUpdateReqs; auto kWriteReqs = AllowedNoSecurity(); @@ -802,7 +801,7 @@ TEST(GATT_LocalServiceManagerTest, WriteDescriptor) { EXPECT_EQ(svc_id, cb_svc_id); EXPECT_EQ(kDescId, id); EXPECT_EQ(kOffset, offset); - EXPECT_TRUE(common::ContainersEqual(kTestValue, value)); + EXPECT_TRUE(ContainersEqual(kTestValue, value)); responder(att::ErrorCode::kNoError); }; @@ -854,7 +853,7 @@ TEST(GATT_LocalServiceManagerTest, ServiceChanged) { constexpr IdType kChrcId = 0; constexpr uint8_t kChrcProps = Property::kRead; - constexpr common::UUID kTestChrcType((uint32_t)0xdeadbeef); + constexpr UUID kTestChrcType((uint32_t)0xdeadbeef); const att::AccessRequirements kReadReqs(true, true, true); const att::AccessRequirements kWriteReqs, kUpdateReqs; service->AddCharacteristic( @@ -955,8 +954,8 @@ class GATT_LocalClientCharacteristicConfigurationTest : public ::testing::Test { auto result_cb = [&out_ecode](auto cb_code) { *out_ecode = cb_code; }; uint16_t value = htole16(ccc_value); - return attr->WriteAsync( - peer_id, 0u, common::BufferView(&value, sizeof(value)), result_cb); + return attr->WriteAsync(peer_id, 0u, BufferView(&value, sizeof(value)), + result_cb); } }; diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/remote_characteristic.cc b/src/connectivity/bluetooth/core/bt-host/gatt/remote_characteristic.cc index 973a337bc67a94a77c7273140883513b6c1f1a40..86a651c52efc88cc47e8b6d0aa39682460654f3c 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/remote_characteristic.cc +++ b/src/connectivity/bluetooth/core/bt-host/gatt/remote_characteristic.cc @@ -6,18 +6,14 @@ #include <zircon/assert.h> +#include "client.h" #include "src/connectivity/bluetooth/core/bt-host/common/log.h" #include "src/connectivity/bluetooth/core/bt-host/common/run_or_post.h" #include "src/connectivity/bluetooth/core/bt-host/common/slab_allocator.h" -#include "client.h" - namespace bt { namespace gatt { -using common::HostError; -using common::RunOrPost; - namespace { void ReportNotifyStatus(att::Status status, IdType id, @@ -27,7 +23,7 @@ void ReportNotifyStatus(att::Status status, IdType id, dispatcher); } -void NotifyValue(const common::ByteBuffer& value, +void NotifyValue(const ByteBuffer& value, RemoteCharacteristic::ValueCallback callback, async_dispatcher_t* dispatcher) { if (!dispatcher) { @@ -35,11 +31,11 @@ void NotifyValue(const common::ByteBuffer& value, return; } - auto buffer = common::NewSlabBuffer(value.size()); + auto buffer = NewSlabBuffer(value.size()); if (buffer) { value.Copy(buffer.get()); - async::PostTask(dispatcher, - [callback = std::move(callback), val = std::move(buffer)] { callback(*val); }); + async::PostTask(dispatcher, [callback = std::move(callback), + val = std::move(buffer)] { callback(*val); }); } else { bt_log(TRACE, "gatt", "out of memory!"); } @@ -48,7 +44,8 @@ void NotifyValue(const common::ByteBuffer& value, } // namespace RemoteCharacteristic::PendingNotifyRequest::PendingNotifyRequest( - async_dispatcher_t* d, ValueCallback value_cb, NotifyStatusCallback status_cb) + async_dispatcher_t* d, ValueCallback value_cb, + NotifyStatusCallback status_cb) : dispatcher(d), value_callback(std::move(value_cb)), status_callback(std::move(status_cb)) { @@ -56,7 +53,8 @@ RemoteCharacteristic::PendingNotifyRequest::PendingNotifyRequest( ZX_DEBUG_ASSERT(status_callback); } -RemoteCharacteristic::NotifyHandler::NotifyHandler(async_dispatcher_t* d, ValueCallback cb) +RemoteCharacteristic::NotifyHandler::NotifyHandler(async_dispatcher_t* d, + ValueCallback cb) : dispatcher(d), callback(std::move(cb)) { ZX_DEBUG_ASSERT(callback); } @@ -213,7 +211,7 @@ void RemoteCharacteristic::EnableNotifications( if (pending_notify_reqs_.size() > 1u) return; - common::StaticByteBuffer<2> ccc_value; + StaticByteBuffer<2> ccc_value; ccc_value.SetToZeros(); // Enable indications if supported. Otherwise enable notifications. @@ -261,7 +259,7 @@ void RemoteCharacteristic::DisableNotificationsInternal() { } // Disable notifications. - common::StaticByteBuffer<2> ccc_value; + StaticByteBuffer<2> ccc_value; ccc_value.SetToZeros(); auto ccc_write_cb = [](att::Status status) { @@ -296,7 +294,7 @@ void RemoteCharacteristic::ResolvePendingNotifyRequests(att::Status status) { } } -void RemoteCharacteristic::HandleNotification(const common::ByteBuffer& value) { +void RemoteCharacteristic::HandleNotification(const ByteBuffer& value) { ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); ZX_DEBUG_ASSERT(client_); ZX_DEBUG_ASSERT(!shut_down_); diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/remote_characteristic.h b/src/connectivity/bluetooth/core/bt-host/gatt/remote_characteristic.h index 83753e9ca0cb4f077a292c3afeb5d7985597e3c0..ea68065b1346df1ff16c0e0e1a94e358989fd7d6 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/remote_characteristic.h +++ b/src/connectivity/bluetooth/core/bt-host/gatt/remote_characteristic.h @@ -53,7 +53,7 @@ class Client; // MUST call ShutDown() on the GATT thread to ensure safe clean up. class RemoteCharacteristic final { public: - using ValueCallback = fit::function<void(const common::ByteBuffer&)>; + using ValueCallback = fit::function<void(const ByteBuffer&)>; using NotifyStatusCallback = fit::function<void(att::Status, IdType handler_id)>; @@ -128,7 +128,7 @@ class RemoteCharacteristic final { void ResolvePendingNotifyRequests(att::Status status); // Called when a notification is received for this characteristic. - void HandleNotification(const common::ByteBuffer& value); + void HandleNotification(const ByteBuffer& value); fxl::ThreadChecker thread_checker_; IdType id_; diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/remote_service.cc b/src/connectivity/bluetooth/core/bt-host/gatt/remote_service.cc index 1947c008420a464bcf40fff1fe0bcf9bea6bbb20..005dc50abdaf14e99bc990fe2cf92df73e66eff6 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/remote_service.cc +++ b/src/connectivity/bluetooth/core/bt-host/gatt/remote_service.cc @@ -15,23 +15,15 @@ namespace gatt { using att::Status; using att::StatusCallback; -using common::BufferView; -using common::ByteBuffer; -using common::HostError; -using common::MutableByteBufferPtr; -using common::NewSlabBuffer; -using common::RunOrPost; namespace { -void ReportStatus(Status status, - StatusCallback callback, +void ReportStatus(Status status, StatusCallback callback, async_dispatcher_t* dispatcher) { RunOrPost([status, cb = std::move(callback)] { cb(status); }, dispatcher); } -void ReportValue(att::Status status, - const common::ByteBuffer& value, +void ReportValue(att::Status status, const ByteBuffer& value, RemoteService::ReadValueCallback callback, async_dispatcher_t* dispatcher) { if (!dispatcher) { @@ -42,7 +34,7 @@ void ReportValue(att::Status status, // TODO(armansito): Consider making att::Bearer return the ATT PDU buffer // directly which would remove the need for a copy. - auto buffer = common::NewSlabBuffer(value.size()); + auto buffer = NewSlabBuffer(value.size()); value.Copy(buffer.get()); async::PostTask(dispatcher, @@ -175,8 +167,7 @@ bool RemoteService::IsDiscovered() const { return HasCharacteristics(); } -void RemoteService::ReadCharacteristic(IdType id, - ReadValueCallback cb, +void RemoteService::ReadCharacteristic(IdType id, ReadValueCallback cb, async_dispatcher_t* dispatcher) { RunGattTask([this, id, cb = std::move(cb), dispatcher]() mutable { RemoteCharacteristic* chrc; @@ -189,7 +180,8 @@ void RemoteService::ReadCharacteristic(IdType id, if (!(chrc->info().properties & Property::kRead)) { bt_log(TRACE, "gatt", "characteristic does not support \"read\""); - ReportValue(att::Status(HostError::kNotSupported), BufferView(), std::move(cb), dispatcher); + ReportValue(att::Status(HostError::kNotSupported), BufferView(), + std::move(cb), dispatcher); return; } @@ -239,8 +231,7 @@ void RemoteService::ReadLongCharacteristic(IdType id, uint16_t offset, }); } -void RemoteService::WriteCharacteristic(IdType id, - std::vector<uint8_t> value, +void RemoteService::WriteCharacteristic(IdType id, std::vector<uint8_t> value, StatusCallback cb, async_dispatcher_t* dispatcher) { RunGattTask([this, id, value = std::move(value), cb = std::move(cb), @@ -462,7 +453,8 @@ bool RemoteService::IsOnGattThread() const { return async_get_default_dispatcher() == gatt_dispatcher_; } -HostError RemoteService::GetCharacteristic(IdType id, RemoteCharacteristic** out_char) { +HostError RemoteService::GetCharacteristic(IdType id, + RemoteCharacteristic** out_char) { ZX_DEBUG_ASSERT(IsOnGattThread()); ZX_DEBUG_ASSERT(out_char); @@ -616,7 +608,7 @@ void RemoteService::ReadLongHelper(att::Handle value_handle, uint16_t offset, } void RemoteService::HandleNotification(att::Handle value_handle, - const common::ByteBuffer& value) { + const ByteBuffer& value) { ZX_DEBUG_ASSERT(IsOnGattThread()); if (shut_down_) diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/remote_service.h b/src/connectivity/bluetooth/core/bt-host/gatt/remote_service.h index 7495fed4871440c97d3498f98aa4d88630bf94f7..fa6ca004eef598086c3f95855a9f341b943a20c5 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/remote_service.h +++ b/src/connectivity/bluetooth/core/bt-host/gatt/remote_service.h @@ -56,7 +56,7 @@ class RemoteService : public fbl::RefCounted<RemoteService> { att::Handle handle() const { return service_data_.range_start; } // Returns the service UUID. - const common::UUID& uuid() const { return service_data_.type; } + const UUID& uuid() const { return service_data_.type; } // Adds a handler which will be called when this service gets removed. // Returns false if the service was already shut down. |callback| will be @@ -82,8 +82,7 @@ class RemoteService : public fbl::RefCounted<RemoteService> { // if characteristics have not been discovered. // // NOTE: Providing a |dispatcher| results in a copy of the resulting value. - using ReadValueCallback = - fit::function<void(att::Status, const common::ByteBuffer&)>; + using ReadValueCallback = fit::function<void(att::Status, const ByteBuffer&)>; void ReadCharacteristic(IdType id, ReadValueCallback callback, async_dispatcher_t* dispatcher = nullptr); @@ -196,13 +195,12 @@ class RemoteService : public fbl::RefCounted<RemoteService> { // Returns a pointer to the characteristic with |id|. Returns nullptr if not // found. - common::HostError GetCharacteristic(IdType id, - RemoteCharacteristic** out_char); + HostError GetCharacteristic(IdType id, RemoteCharacteristic** out_char); // Returns a pointer to the characteristic descriptor with |id|. Returns // nullptr if not found. - common::HostError GetDescriptor( - IdType id, const RemoteCharacteristic::Descriptor** out_desc); + HostError GetDescriptor(IdType id, + const RemoteCharacteristic::Descriptor** out_desc); // Called immediately after characteristic discovery to initiate descriptor // discovery. @@ -231,13 +229,13 @@ class RemoteService : public fbl::RefCounted<RemoteService> { // Sends an ATT_Write_Request and reports the result via |cb| on |dispatcher|. // |cb| executes on the GATT dispatcher if the provided |dispatcher| is // nullptr. - void SendWriteRequest(att::Handle handle, const common::ByteBuffer& value, + void SendWriteRequest(att::Handle handle, const ByteBuffer& value, att::StatusCallback cb, async_dispatcher_t* dispatcher); // Helper function that drives the recursive "Read Long Characteristic Values" // procedure. Called by ReadLongCharacteristic(). void ReadLongHelper(att::Handle value_handle, uint16_t offset, - common::MutableByteBufferPtr buffer, size_t bytes_read, + MutableByteBufferPtr buffer, size_t bytes_read, ReadValueCallback callback, async_dispatcher_t* dispatcher); @@ -250,8 +248,7 @@ class RemoteService : public fbl::RefCounted<RemoteService> { // Called by RemoteServiceManager when a notification is received for one of // this service's characteristics. - void HandleNotification(att::Handle value_handle, - const common::ByteBuffer& value); + void HandleNotification(att::Handle value_handle, const ByteBuffer& value); ServiceData service_data_; diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/remote_service_manager.cc b/src/connectivity/bluetooth/core/bt-host/gatt/remote_service_manager.cc index acac6c65e2feb91f031b76673af2756e15bab3a6..6c107d0fb4639410a211028d8a204a1b0557545e 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/remote_service_manager.cc +++ b/src/connectivity/bluetooth/core/bt-host/gatt/remote_service_manager.cc @@ -9,21 +9,17 @@ namespace bt { -using common::HostError; - namespace gatt { namespace internal { RemoteServiceManager::ServiceListRequest::ServiceListRequest( - ServiceListCallback callback, - const std::vector<common::UUID>& uuids) + ServiceListCallback callback, const std::vector<UUID>& uuids) : callback_(std::move(callback)), uuids_(uuids) { ZX_DEBUG_ASSERT(callback_); } void RemoteServiceManager::ServiceListRequest::Complete( - att::Status status, - const ServiceMap& services) { + att::Status status, const ServiceMap& services) { ServiceList result; if (!status || services.empty()) { @@ -33,9 +29,7 @@ void RemoteServiceManager::ServiceListRequest::Complete( for (const auto& iter : services) { auto& svc = iter.second; - auto pred = [&svc](const common::UUID& uuid) { - return svc->uuid() == uuid; - }; + auto pred = [&svc](const UUID& uuid) { return svc->uuid() == uuid; }; if (uuids_.empty() || std::find_if(uuids_.begin(), uuids_.end(), pred) != uuids_.end()) { result.push_back(iter.second); @@ -65,7 +59,7 @@ RemoteServiceManager::~RemoteServiceManager() { ClearServices(); // Resolve all pending requests with an error. - att::Status status(common::HostError::kFailed); + att::Status status(HostError::kFailed); auto pending = std::move(pending_); while (!pending.empty()) { @@ -149,7 +143,7 @@ void RemoteServiceManager::Initialize(att::StatusCallback cb) { }); } -void RemoteServiceManager::ListServices(const std::vector<common::UUID>& uuids, +void RemoteServiceManager::ListServices(const std::vector<UUID>& uuids, ServiceListCallback callback) { ServiceListRequest request(std::move(callback), uuids); if (initialized_) { @@ -173,7 +167,7 @@ void RemoteServiceManager::ClearServices() { } void RemoteServiceManager::OnNotification(bool, att::Handle value_handle, - const common::ByteBuffer& value) { + const ByteBuffer& value) { ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); if (services_.empty()) { @@ -183,7 +177,8 @@ void RemoteServiceManager::OnNotification(bool, att::Handle value_handle, // Find the service that |value_handle| belongs to. auto iter = services_.upper_bound(value_handle); - if (iter != services_.begin()) --iter; + if (iter != services_.begin()) + --iter; // If |value_handle| is within the previous service then we found it. auto& svc = iter->second; diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/remote_service_manager.h b/src/connectivity/bluetooth/core/bt-host/gatt/remote_service_manager.h index cd1aa15bdf0c3e3928005ec8db1b074c1e4b2270..89edc7ab8dbdbd34c4edbe78149b1d4fcc79feed 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/remote_service_manager.h +++ b/src/connectivity/bluetooth/core/bt-host/gatt/remote_service_manager.h @@ -54,7 +54,7 @@ class RemoteServiceManager final { // |uuids| via |callback|. All services will be returned if |uuids| is empty. // // If called while uninitialized, |callback| will be run after initialization. - void ListServices(const std::vector<common::UUID>& uuids, + void ListServices(const std::vector<UUID>& uuids, ServiceListCallback callback); // Returns the RemoteService with the requested range start |handle| or @@ -69,7 +69,7 @@ class RemoteServiceManager final { class ServiceListRequest { public: ServiceListRequest(ServiceListCallback callback, - const std::vector<common::UUID>& uuids); + const std::vector<UUID>& uuids); ServiceListRequest() = default; ServiceListRequest(ServiceListRequest&&) = default; @@ -80,7 +80,7 @@ class RemoteServiceManager final { private: ServiceListCallback callback_; - std::vector<common::UUID> uuids_; + std::vector<UUID> uuids_; DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(ServiceListRequest); }; @@ -90,7 +90,7 @@ class RemoteServiceManager final { // Called by |client_| when a notification or indication is received. void OnNotification(bool ind, att::Handle value_handle, - const common::ByteBuffer& value); + const ByteBuffer& value); async_dispatcher_t* gatt_dispatcher_; std::unique_ptr<Client> client_; diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/remote_service_manager_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gatt/remote_service_manager_unittest.cc index 81709c24802b0299ad389eb825db520102ba58a2..9a92e38e6dcd542e7f985f3c3c55fef81a14eab8 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/remote_service_manager_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/gatt/remote_service_manager_unittest.cc @@ -31,22 +31,14 @@ static bool operator==(const DescriptorData& desc1, namespace internal { namespace { -using common::BufferView; -using common::ByteBuffer; -using common::CreateStaticByteBuffer; -using common::HostError; -using common::StaticByteBuffer; - -constexpr common::UUID kTestServiceUuid1((uint16_t)0xbeef); -constexpr common::UUID kTestServiceUuid2((uint16_t)0xcafe); -constexpr common::UUID kTestUuid3((uint16_t)0xfefe); -constexpr common::UUID kTestUuid4((uint16_t)0xefef); +constexpr UUID kTestServiceUuid1((uint16_t)0xbeef); +constexpr UUID kTestServiceUuid2((uint16_t)0xcafe); +constexpr UUID kTestUuid3((uint16_t)0xfefe); +constexpr UUID kTestUuid4((uint16_t)0xefef); const auto kCCCNotifyValue = CreateStaticByteBuffer(0x01, 0x00); const auto kCCCIndicateValue = CreateStaticByteBuffer(0x02, 0x00); -using common::HostError; - void NopStatusCallback(att::Status) {} void NopValueCallback(const ByteBuffer&) {} @@ -79,7 +71,7 @@ class GATT_RemoteServiceManagerTest : public ::gtest::TestLoopFixture { mgr()->Initialize(NopStatusCallback); ServiceList services; - mgr()->ListServices(std::vector<common::UUID>(), + mgr()->ListServices(std::vector<UUID>(), [&services](auto status, ServiceList cb_services) { services = std::move(cb_services); }); @@ -163,7 +155,7 @@ TEST_F(GATT_RemoteServiceManagerTest, InitializeNoServices) { EXPECT_TRUE(status); EXPECT_TRUE(services.empty()); - mgr()->ListServices(std::vector<common::UUID>(), + mgr()->ListServices(std::vector<UUID>(), [&services](auto status, ServiceList cb_services) { services = std::move(cb_services); }); @@ -202,7 +194,7 @@ TEST_F(GATT_RemoteServiceManagerTest, InitializeFailure) { [&watcher_services](auto svc) { watcher_services.push_back(svc); }); ServiceList services; - mgr()->ListServices(std::vector<common::UUID>(), + mgr()->ListServices(std::vector<UUID>(), [&services](auto status, ServiceList cb_services) { services = std::move(cb_services); }); @@ -226,7 +218,7 @@ TEST_F(GATT_RemoteServiceManagerTest, ListServicesBeforeInit) { fake_client()->set_primary_services(std::move(fake_services)); ServiceList services; - mgr()->ListServices(std::vector<common::UUID>(), + mgr()->ListServices(std::vector<UUID>(), [&services](auto status, ServiceList cb_services) { services = std::move(cb_services); }); @@ -256,7 +248,7 @@ TEST_F(GATT_RemoteServiceManagerTest, ListServicesAfterInit) { ASSERT_TRUE(status); ServiceList services; - mgr()->ListServices(std::vector<common::UUID>(), + mgr()->ListServices(std::vector<UUID>(), [&services](auto status, ServiceList cb_services) { services = std::move(cb_services); }); @@ -266,7 +258,7 @@ TEST_F(GATT_RemoteServiceManagerTest, ListServicesAfterInit) { } TEST_F(GATT_RemoteServiceManagerTest, ListServicesByUuid) { - std::vector<common::UUID> uuids{kTestServiceUuid1}; + std::vector<UUID> uuids{kTestServiceUuid1}; ServiceData svc1(1, 1, kTestServiceUuid1); ServiceData svc2(2, 2, kTestServiceUuid2); @@ -722,7 +714,7 @@ TEST_F(GATT_RemoteServiceManagerTest, ReadCharSendsReadRequest) { att::Status status(HostError::kFailed); service->ReadCharacteristic(0, [&](att::Status cb_status, const auto& value) { status = cb_status; - EXPECT_TRUE(common::ContainersEqual(kValue, value)); + EXPECT_TRUE(ContainersEqual(kValue, value)); }); RunLoopUntilIdle(); @@ -752,7 +744,7 @@ TEST_F(GATT_RemoteServiceManagerTest, ReadCharSendsReadRequestWithDispatcher) { 0, [&](att::Status cb_status, const auto& value) { status = cb_status; - EXPECT_TRUE(common::ContainersEqual(kValue, value)); + EXPECT_TRUE(ContainersEqual(kValue, value)); }, dispatcher()); @@ -1396,7 +1388,7 @@ TEST_F(GATT_RemoteServiceManagerTest, ReadDescSendsReadRequest) { service->ReadDescriptor(kDescrId, [&](att::Status cb_status, const auto& value) { status = cb_status; - EXPECT_TRUE(common::ContainersEqual(kValue, value)); + EXPECT_TRUE(ContainersEqual(kValue, value)); }); RunLoopUntilIdle(); @@ -1428,7 +1420,7 @@ TEST_F(GATT_RemoteServiceManagerTest, ReadDescSendsReadRequestWithDispatcher) { 0, [&](att::Status cb_status, const auto& value) { status = cb_status; - EXPECT_TRUE(common::ContainersEqual(kValue, value)); + EXPECT_TRUE(ContainersEqual(kValue, value)); }, dispatcher()); @@ -1946,7 +1938,7 @@ TEST_F(GATT_RemoteServiceManagerTest, EnableNotificationsRequestManyError) { TEST_F(GATT_RemoteServiceManagerTest, NotificationWithoutServices) { for (att::Handle i = 0; i < 10; ++i) { fake_client()->SendNotification( - false, i, common::CreateStaticByteBuffer('n', 'o', 't', 'i', 'f', 'y')); + false, i, CreateStaticByteBuffer('n', 'o', 't', 'i', 'f', 'y')); } RunLoopUntilIdle(); } @@ -1989,10 +1981,9 @@ TEST_F(GATT_RemoteServiceManagerTest, NotificationCallback) { // Notify both characteristics which should get dropped. fake_client()->SendNotification( - false, 3, common::CreateStaticByteBuffer('n', 'o', 't', 'i', 'f', 'y')); + false, 3, CreateStaticByteBuffer('n', 'o', 't', 'i', 'f', 'y')); fake_client()->SendNotification( - true, 6, - common::CreateStaticByteBuffer('i', 'n', 'd', 'i', 'c', 'a', 't', 'e')); + true, 6, CreateStaticByteBuffer('i', 'n', 'd', 'i', 'c', 'a', 't', 'e')); EnableNotifications(service, kId1, &status, &handler_id, std::move(chr1_cb)); ASSERT_TRUE(status); @@ -2001,14 +1992,13 @@ TEST_F(GATT_RemoteServiceManagerTest, NotificationCallback) { // Notify characteristic 1. fake_client()->SendNotification( - false, 3, common::CreateStaticByteBuffer('n', 'o', 't', 'i', 'f', 'y')); + false, 3, CreateStaticByteBuffer('n', 'o', 't', 'i', 'f', 'y')); EXPECT_EQ(1, chr1_count); EXPECT_EQ(0, chr2_count); // Notify characteristic 2. fake_client()->SendNotification( - true, 6, - common::CreateStaticByteBuffer('i', 'n', 'd', 'i', 'c', 'a', 't', 'e')); + true, 6, CreateStaticByteBuffer('i', 'n', 'd', 'i', 'c', 'a', 't', 'e')); EXPECT_EQ(1, chr1_count); EXPECT_EQ(1, chr2_count); @@ -2022,10 +2012,9 @@ TEST_F(GATT_RemoteServiceManagerTest, NotificationCallback) { // Notifications for characteristic 1 should get dropped. fake_client()->SendNotification( - false, 3, common::CreateStaticByteBuffer('n', 'o', 't', 'i', 'f', 'y')); + false, 3, CreateStaticByteBuffer('n', 'o', 't', 'i', 'f', 'y')); fake_client()->SendNotification( - true, 6, - common::CreateStaticByteBuffer('i', 'n', 'd', 'i', 'c', 'a', 't', 'e')); + true, 6, CreateStaticByteBuffer('i', 'n', 'd', 'i', 'c', 'a', 't', 'e')); EXPECT_EQ(1, chr1_count); EXPECT_EQ(2, chr2_count); } diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/server.cc b/src/connectivity/bluetooth/core/bt-host/gatt/server.cc index 1699152bde7535f8182e75b8c617b2e432c9198b..dd19257ea063bce6ee320c692d0dd5d4264c92c4 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/server.cc +++ b/src/connectivity/bluetooth/core/bt-host/gatt/server.cc @@ -17,8 +17,6 @@ namespace bt { namespace gatt { -using common::DynamicByteBuffer; - Server::Server(PeerId peer_id, fxl::RefPtr<att::Database> database, fxl::RefPtr<att::Bearer> bearer) : peer_id_(peer_id), db_(database), att_(bearer), weak_ptr_factory_(this) { @@ -69,10 +67,10 @@ Server::~Server() { att_->UnregisterHandler(exchange_mtu_id_); } -void Server::SendNotification(att::Handle handle, - const common::ByteBuffer& value, bool indicate) { - auto buffer = common::NewSlabBuffer(sizeof(att::Header) + sizeof(handle) + - value.size()); +void Server::SendNotification(att::Handle handle, const ByteBuffer& value, + bool indicate) { + auto buffer = + NewSlabBuffer(sizeof(att::Header) + sizeof(handle) + value.size()); ZX_ASSERT(buffer); att::PacketWriter writer(indicate ? att::kIndication : att::kNotification, @@ -108,8 +106,8 @@ void Server::OnExchangeMTU(att::Bearer::TransactionId tid, uint16_t client_mtu = le16toh(params.client_rx_mtu); uint16_t server_mtu = att_->preferred_mtu(); - auto buffer = common::NewSlabBuffer(sizeof(att::Header) + - sizeof(att::ExchangeMTUResponseParams)); + auto buffer = NewSlabBuffer(sizeof(att::Header) + + sizeof(att::ExchangeMTUResponseParams)); ZX_ASSERT(buffer); att::PacketWriter writer(att::kExchangeMTUResponse, buffer.get()); @@ -180,7 +178,7 @@ void Server::OnFindInformation(att::Bearer::TransactionId tid, size_t pdu_size = kHeaderSize + entry_size * results.size(); - auto buffer = common::NewSlabBuffer(pdu_size); + auto buffer = NewSlabBuffer(pdu_size); ZX_ASSERT(buffer); att::PacketWriter writer(att::kFindInformationResponse, buffer.get()); @@ -217,10 +215,10 @@ void Server::OnFindByTypeValueRequest(att::Bearer::TransactionId tid, const auto& params = packet.payload<att::FindByTypeValueRequestParams>(); att::Handle start = le16toh(params.start_handle); att::Handle end = le16toh(params.end_handle); - common::UUID type = common::UUID(params.type); + UUID type(params.type); constexpr size_t kParamsSize = sizeof(att::FindByTypeValueRequestParams); - common::BufferView value = packet.payload_data().view( + BufferView value = packet.payload_data().view( kParamsSize, packet.payload_size() - kParamsSize); if (start == att::kInvalidHandle || start > end) { @@ -260,7 +258,7 @@ void Server::OnFindByTypeValueRequest(att::Bearer::TransactionId tid, constexpr size_t kRspStructSize = sizeof(att::HandlesInformationList); size_t pdu_size = sizeof(att::Header) + kRspStructSize * results.size(); - auto buffer = common::NewSlabBuffer(pdu_size); + auto buffer = NewSlabBuffer(pdu_size); ZX_ASSERT(buffer); att::PacketWriter writer(att::kFindByTypeValueResponse, buffer.get()); @@ -287,19 +285,19 @@ void Server::OnReadByGroupType(att::Bearer::TransactionId tid, ZX_DEBUG_ASSERT(packet.opcode() == att::kReadByGroupTypeRequest); att::Handle start, end; - common::UUID group_type; + UUID group_type; // The group type is represented as either a 16-bit or 128-bit UUID. if (packet.payload_size() == sizeof(att::ReadByTypeRequestParams16)) { const auto& params = packet.payload<att::ReadByTypeRequestParams16>(); start = le16toh(params.start_handle); end = le16toh(params.end_handle); - group_type = common::UUID(le16toh(params.type)); + group_type = UUID(le16toh(params.type)); } else if (packet.payload_size() == sizeof(att::ReadByTypeRequestParams128)) { const auto& params = packet.payload<att::ReadByTypeRequestParams128>(); start = le16toh(params.start_handle); end = le16toh(params.end_handle); - group_type = common::UUID(params.type); + group_type = UUID(params.type); } else { att_->ReplyWithError(tid, att::kInvalidHandle, att::ErrorCode::kInvalidPDU); return; @@ -332,7 +330,7 @@ void Server::OnReadByGroupType(att::Bearer::TransactionId tid, size_t pdu_size = kHeaderSize + entry_size * results.size(); ZX_DEBUG_ASSERT(pdu_size <= att_->mtu()); - auto buffer = common::NewSlabBuffer(pdu_size); + auto buffer = NewSlabBuffer(pdu_size); ZX_ASSERT(buffer); att::PacketWriter writer(att::kReadByGroupTypeResponse, buffer.get()); @@ -362,19 +360,19 @@ void Server::OnReadByType(att::Bearer::TransactionId tid, ZX_DEBUG_ASSERT(packet.opcode() == att::kReadByTypeRequest); att::Handle start, end; - common::UUID type; + UUID type; // The attribute type is represented as either a 16-bit or 128-bit UUID. if (packet.payload_size() == sizeof(att::ReadByTypeRequestParams16)) { const auto& params = packet.payload<att::ReadByTypeRequestParams16>(); start = le16toh(params.start_handle); end = le16toh(params.end_handle); - type = common::UUID(le16toh(params.type)); + type = UUID(le16toh(params.type)); } else if (packet.payload_size() == sizeof(att::ReadByTypeRequestParams128)) { const auto& params = packet.payload<att::ReadByTypeRequestParams128>(); start = le16toh(params.start_handle); end = le16toh(params.end_handle); - type = common::UUID(params.type); + type = UUID(params.type); } else { att_->ReplyWithError(tid, att::kInvalidHandle, att::ErrorCode::kInvalidPDU); return; @@ -420,7 +418,7 @@ void Server::OnReadByType(att::Bearer::TransactionId tid, // Respond with just a single entry. size_t value_size = std::min(value.size(), kMaxValueSize); size_t entry_size = value_size + sizeof(att::AttributeData); - auto buffer = common::NewSlabBuffer(entry_size + kHeaderSize); + auto buffer = NewSlabBuffer(entry_size + kHeaderSize); att::PacketWriter writer(att::kReadByTypeResponse, buffer.get()); auto params = writer.mutable_payload<att::ReadByTypeResponseParams>(); @@ -445,7 +443,7 @@ void Server::OnReadByType(att::Bearer::TransactionId tid, size_t pdu_size = kHeaderSize + entry_size * results.size(); ZX_DEBUG_ASSERT(pdu_size <= att_->mtu()); - auto buffer = common::NewSlabBuffer(pdu_size); + auto buffer = NewSlabBuffer(pdu_size); ZX_ASSERT(buffer); att::PacketWriter writer(att::kReadByTypeResponse, buffer.get()); @@ -506,7 +504,7 @@ void Server::OnReadBlobRequest(att::Bearer::TransactionId tid, } size_t value_size = std::min(value.size(), self->att_->mtu() - kHeaderSize); - auto buffer = common::NewSlabBuffer(value_size + kHeaderSize); + auto buffer = NewSlabBuffer(value_size + kHeaderSize); ZX_ASSERT(buffer); att::PacketWriter writer(att::kReadBlobResponse, buffer.get()); @@ -571,7 +569,7 @@ void Server::OnReadRequest(att::Bearer::TransactionId tid, } size_t value_size = std::min(value.size(), self->att_->mtu() - kHeaderSize); - auto buffer = common::NewSlabBuffer(value_size + kHeaderSize); + auto buffer = NewSlabBuffer(value_size + kHeaderSize); ZX_ASSERT(buffer); att::PacketWriter writer(att::kReadResponse, buffer.get()); @@ -677,7 +675,7 @@ void Server::OnWriteRequest(att::Bearer::TransactionId tid, return; } - auto buffer = common::NewSlabBuffer(1); + auto buffer = NewSlabBuffer(1); (*buffer)[0] = att::kWriteResponse; self->att_->Reply(tid, std::move(buffer)); }; @@ -688,10 +686,9 @@ void Server::OnWriteRequest(att::Bearer::TransactionId tid, } att::ErrorCode Server::ReadByTypeHelper( - att::Handle start, att::Handle end, const common::UUID& type, - bool group_type, size_t max_data_list_size, size_t max_value_size, - size_t entry_prefix_size, size_t* out_value_size, - std::list<const att::Attribute*>* out_results) { + att::Handle start, att::Handle end, const UUID& type, bool group_type, + size_t max_data_list_size, size_t max_value_size, size_t entry_prefix_size, + size_t* out_value_size, std::list<const att::Attribute*>* out_results) { ZX_DEBUG_ASSERT(out_results); ZX_DEBUG_ASSERT(out_value_size); diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/server.h b/src/connectivity/bluetooth/core/bt-host/gatt/server.h index 576790fec65c77e7b3b28ec16eca203d2e7b146c..174612925567fa0f65cfbdc5a0b53c61fb27cbf1 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/server.h +++ b/src/connectivity/bluetooth/core/bt-host/gatt/server.h @@ -41,7 +41,7 @@ class Server final { // attribute handle. If |indicate| is true, then an indication will be sent. // The underlying att::Bearer will disconnect the link if a confirmation is // not received in a timely manner. - void SendNotification(att::Handle handle, const common::ByteBuffer& value, + void SendNotification(att::Handle handle, const ByteBuffer& value, bool indicate); private: @@ -81,8 +81,8 @@ class Server final { // Returns att::ErrorCode::kNoError on success. On error, returns an error // code that can be used in a ATT Error Response. att::ErrorCode ReadByTypeHelper( - att::Handle start, att::Handle end, const common::UUID& type, - bool group_type, size_t max_data_list_size, size_t max_value_size, + att::Handle start, att::Handle end, const UUID& type, bool group_type, + size_t max_data_list_size, size_t max_value_size, size_t entry_prefix_size, size_t* out_value_size, std::list<const att::Attribute*>* out_results); diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/server_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gatt/server_unittest.cc index d4fe7415617acef182cb9feb7e0931ebfd0efd49..784a8a9299ff308ac655254e940e7bde55ea3178 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/server_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/gatt/server_unittest.cc @@ -17,20 +17,17 @@ namespace bt { namespace gatt { namespace { -using common::LowerBits; -using common::UpperBits; - constexpr PeerId kTestPeerId(1); -constexpr common::UUID kTestType16((uint16_t)0xBEEF); -constexpr common::UUID kTestType128({0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, - 13, 14, 15}); +constexpr UUID kTestType16((uint16_t)0xBEEF); +constexpr UUID kTestType128({0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15}); -const auto kTestValue1 = common::CreateStaticByteBuffer('f', 'o', 'o'); -const auto kTestValue2 = common::CreateStaticByteBuffer('b', 'a', 'r'); -const auto kTestValue3 = common::CreateStaticByteBuffer('b', 'a', 'z'); -const auto kTestValue4 = common::CreateStaticByteBuffer('l', 'o', 'l'); +const auto kTestValue1 = CreateStaticByteBuffer('f', 'o', 'o'); +const auto kTestValue2 = CreateStaticByteBuffer('b', 'a', 'r'); +const auto kTestValue3 = CreateStaticByteBuffer('b', 'a', 'z'); +const auto kTestValue4 = CreateStaticByteBuffer('l', 'o', 'l'); -const auto kTestValueLong = common::CreateStaticByteBuffer('l', 'o', 'n', 'g'); +const auto kTestValueLong = CreateStaticByteBuffer('l', 'o', 'n', 'g'); inline att::AccessRequirements AllowedNoSecurity() { return att::AccessRequirements(false, false, false); @@ -75,8 +72,8 @@ class GATT_ServerTest : public l2cap::testing::FakeChannelTest { TEST_F(GATT_ServerTest, ExchangeMTURequestInvalidPDU) { // Just opcode // clang-format off - const auto kInvalidPDU = common::CreateStaticByteBuffer(0x02); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kInvalidPDU = CreateStaticByteBuffer(0x02); + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x02, // request: exchange MTU 0x00, 0x00, // handle: 0 @@ -92,12 +89,12 @@ TEST_F(GATT_ServerTest, ExchangeMTURequestValueTooSmall) { constexpr uint16_t kClientMTU = 1; // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x02, // opcode: exchange MTU kClientMTU, 0x00 // client rx mtu: |kClientMTU| ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x03, // opcode: exchange MTU response 0xF7, 0x00 // server rx mtu: |kServerMTU| ); @@ -116,12 +113,12 @@ TEST_F(GATT_ServerTest, ExchangeMTURequest) { constexpr uint16_t kClientMTU = 0x64; // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x02, // opcode: exchange MTU kClientMTU, 0x00 // client rx mtu: |kClientMTU| ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x03, // opcode: exchange MTU response 0xF7, 0x00 // server rx mtu: |kServerMTU| ); @@ -137,8 +134,8 @@ TEST_F(GATT_ServerTest, ExchangeMTURequest) { TEST_F(GATT_ServerTest, FindInformationInvalidPDU) { // Just opcode // clang-format off - const auto kInvalidPDU = common::CreateStaticByteBuffer(0x04); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kInvalidPDU = CreateStaticByteBuffer(0x04); + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x04, // request: find information 0x00, 0x00, // handle: 0 @@ -152,13 +149,13 @@ TEST_F(GATT_ServerTest, FindInformationInvalidPDU) { TEST_F(GATT_ServerTest, FindInformationInvalidHandle) { // Start handle is 0 // clang-format off - const auto kInvalidStartHandle = common::CreateStaticByteBuffer( + const auto kInvalidStartHandle = CreateStaticByteBuffer( 0x04, // opcode: find information 0x00, 0x00, // start: 0x0000 0xFF, 0xFF // end: 0xFFFF ); - const auto kExpected1 = common::CreateStaticByteBuffer( + const auto kExpected1 = CreateStaticByteBuffer( 0x01, // opcode: error response 0x04, // request: find information 0x00, 0x00, // handle: 0x0000 (start handle in request) @@ -166,13 +163,13 @@ TEST_F(GATT_ServerTest, FindInformationInvalidHandle) { ); // End handle is smaller than start handle - const auto kInvalidEndHandle = common::CreateStaticByteBuffer( + const auto kInvalidEndHandle = CreateStaticByteBuffer( 0x04, // opcode: find information 0x02, 0x00, // start: 0x0002 0x01, 0x00 // end: 0x0001 ); - const auto kExpected2 = common::CreateStaticByteBuffer( + const auto kExpected2 = CreateStaticByteBuffer( 0x01, // opcode: error response 0x04, // request: find information 0x02, 0x00, // handle: 0x0002 (start handle in request) @@ -186,13 +183,13 @@ TEST_F(GATT_ServerTest, FindInformationInvalidHandle) { TEST_F(GATT_ServerTest, FindInformationAttributeNotFound) { // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x04, // opcode: find information request 0x01, 0x00, // start: 0x0001 0xFF, 0xFF // end: 0xFFFF ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x04, // request: find information 0x01, 0x00, // handle: 0x0001 (start handle in request) @@ -210,13 +207,13 @@ TEST_F(GATT_ServerTest, FindInformation16) { grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x04, // opcode: find information request 0x01, 0x00, // start: 0x0001 0xFF, 0xFF // end: 0xFFFF ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x05, // opcode: find information response 0x01, // format: 16-bit 0x01, 0x00, // handle: 0x0001 @@ -236,13 +233,13 @@ TEST_F(GATT_ServerTest, FindInformation128) { grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x04, // opcode: find information request 0x01, 0x00, // start: 0x0001 0xFF, 0xFF // end: 0xFFFF ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x05, // opcode: find information response 0x02, // format: 128-bit 0x01, 0x00, // handle: 0x0001 @@ -266,7 +263,7 @@ TEST_F(GATT_ServerTest, FindByTypeValueSuccess) { db()->NewGrouping(types::kPrimaryService, 0, kTestValue1)->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x06, // opcode: find by type value request 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF @@ -274,7 +271,7 @@ TEST_F(GATT_ServerTest, FindByTypeValueSuccess) { 'f', 'o', 'o' // value: foo ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x07, // opcode: find by type value response 0x01, 0x00, // handle: 0x0001 0x01, 0x00, // group handle: 0x0001 @@ -291,7 +288,7 @@ TEST_F(GATT_ServerTest, FindByTypeValueFail) { db()->NewGrouping(types::kPrimaryService, 0, kTestValue1)->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x06, // opcode: find by type value request 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF @@ -299,7 +296,7 @@ TEST_F(GATT_ServerTest, FindByTypeValueFail) { 'n', 'o' // value: no ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // Error 0x06, // opcode: find by type value 0x00, 0x00, // group handle: 0x0000 @@ -312,7 +309,7 @@ TEST_F(GATT_ServerTest, FindByTypeValueFail) { TEST_F(GATT_ServerTest, FindByTypeValueEmptyDB) { // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x06, // opcode: find by type value request 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF @@ -320,7 +317,7 @@ TEST_F(GATT_ServerTest, FindByTypeValueEmptyDB) { 'n', 'o' // value: no ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // Error 0x06, // opcode: find by type value 0x00, 0x00, // group handle: 0x0000 @@ -333,7 +330,7 @@ TEST_F(GATT_ServerTest, FindByTypeValueEmptyDB) { TEST_F(GATT_ServerTest, FindByTypeValueInvalidHandle) { // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x06, // opcode: find by type value request 0x02, 0x00, // start: 0x0002 0x01, 0x00, // end: 0x0001 @@ -341,7 +338,7 @@ TEST_F(GATT_ServerTest, FindByTypeValueInvalidHandle) { 'n', 'o' // value: no ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // Error 0x06, // opcode: find by type value 0x00, 0x00, // group handle: 0x0000 @@ -357,9 +354,9 @@ TEST_F(GATT_ServerTest, FindByTypeValueInvalidPDUError) { db()->NewGrouping(types::kPrimaryService, 0, kTestValue1)->set_active(true); // clang-format off - const auto kInvalidPDU = common::CreateStaticByteBuffer(0x06); + const auto kInvalidPDU = CreateStaticByteBuffer(0x06); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // Error 0x06, // opcode: find by type value 0x00, 0x00, // group handle: 0x0000 @@ -375,14 +372,14 @@ TEST_F(GATT_ServerTest, FindByTypeValueZeroLengthValueError) { db()->NewGrouping(types::kPrimaryService, 0, kTestValue1)->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x06, // opcode: find by type value request 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF 0x00, 0x28 // uuid: primary service group type ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // Error 0x06, // opcode: find by type value 0x00, 0x00, // group handle: 0x0000 @@ -405,7 +402,7 @@ TEST_F(GATT_ServerTest, FindByTypeValueOutsideRangeError) { grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x06, // opcode: find by type value request 0x01, 0x00, // start: 0x0001 0x02, 0x00, // end: 0xFFFF @@ -413,7 +410,7 @@ TEST_F(GATT_ServerTest, FindByTypeValueOutsideRangeError) { 'f', 'o', 'o' // value: foo ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // Error 0x06, // opcode: find by type value 0x00, 0x00, // group handle: 0x0000 @@ -437,13 +434,13 @@ TEST_F(GATT_ServerTest, FindInfomationInactive) { db()->NewGrouping(types::kPrimaryService, 0, kTestValue1)->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x04, // opcode: find information request 0x01, 0x00, // start: 0x0001 0xFF, 0xFF // end: 0xFFFF ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x05, // opcode: find information response 0x01, // format: 16-bit 0x01, 0x00, // handle: 0x0001 @@ -466,13 +463,13 @@ TEST_F(GATT_ServerTest, FindInfomationRange) { db()->NewGrouping(types::kPrimaryService, 0, kTestValue1)->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x04, // opcode: find information request 0x02, 0x00, // start: 0x0002 0x02, 0x00 // end: 0x0002 ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x05, // opcode: find information response 0x01, // format: 16-bit 0x02, 0x00, // handle: 0x0001 @@ -486,8 +483,8 @@ TEST_F(GATT_ServerTest, FindInfomationRange) { TEST_F(GATT_ServerTest, ReadByGroupTypeInvalidPDU) { // Just opcode // clang-format off - const auto kInvalidPDU = common::CreateStaticByteBuffer(0x10); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kInvalidPDU = CreateStaticByteBuffer(0x10); + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x10, // request: read by group type 0x00, 0x00, // handle: 0 @@ -501,7 +498,7 @@ TEST_F(GATT_ServerTest, ReadByGroupTypeInvalidPDU) { TEST_F(GATT_ServerTest, ReadByGroupTypeUnsupportedGroupType) { // 16-bit UUID // clang-format off - const auto kUsing16BitType = common::CreateStaticByteBuffer( + const auto kUsing16BitType = CreateStaticByteBuffer( 0x10, // opcode: read by group type 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF @@ -509,7 +506,7 @@ TEST_F(GATT_ServerTest, ReadByGroupTypeUnsupportedGroupType) { ); // 128-bit UUID - const auto kUsing128BitType = common::CreateStaticByteBuffer( + const auto kUsing128BitType = CreateStaticByteBuffer( 0x10, // opcode: read by group type 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF @@ -518,7 +515,7 @@ TEST_F(GATT_ServerTest, ReadByGroupTypeUnsupportedGroupType) { 0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x10, // request: read by group type 0x01, 0x00, // handle: 0x0001 (start handle in request) @@ -533,14 +530,14 @@ TEST_F(GATT_ServerTest, ReadByGroupTypeUnsupportedGroupType) { TEST_F(GATT_ServerTest, ReadByGroupTypeInvalidHandle) { // Start handle is 0 // clang-format off - const auto kInvalidStartHandle = common::CreateStaticByteBuffer( + const auto kInvalidStartHandle = CreateStaticByteBuffer( 0x10, // opcode: read by group type 0x00, 0x00, // start: 0x0000 0xFF, 0xFF, // end: 0xFFFF 0x00, 0x28 // group type: 0x2800 (primary service) ); - const auto kExpected1 = common::CreateStaticByteBuffer( + const auto kExpected1 = CreateStaticByteBuffer( 0x01, // opcode: error response 0x10, // request: read by group type 0x00, 0x00, // handle: 0x0000 (start handle in request) @@ -548,14 +545,14 @@ TEST_F(GATT_ServerTest, ReadByGroupTypeInvalidHandle) { ); // End handle is smaller than start handle - const auto kInvalidEndHandle = common::CreateStaticByteBuffer( + const auto kInvalidEndHandle = CreateStaticByteBuffer( 0x10, // opcode: read by group type 0x02, 0x00, // start: 0x0002 0x01, 0x00, // end: 0x0001 0x00, 0x28 // group type: 0x2800 (primary service) ); - const auto kExpected2 = common::CreateStaticByteBuffer( + const auto kExpected2 = CreateStaticByteBuffer( 0x01, // opcode: error response 0x10, // request: read by group type 0x02, 0x00, // handle: 0x0002 (start handle in request) @@ -569,14 +566,14 @@ TEST_F(GATT_ServerTest, ReadByGroupTypeInvalidHandle) { TEST_F(GATT_ServerTest, ReadByGroupTypeAttributeNotFound) { // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x10, // opcode: read by group type 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF 0x00, 0x28 // group type: 0x2800 (primary service) ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x10, // request: read by group type 0x01, 0x00, // handle: 0x0001 (start handle in request) @@ -593,23 +590,23 @@ TEST_F(GATT_ServerTest, ReadByGroupTypeAttributeNotFound) { } TEST_F(GATT_ServerTest, ReadByGroupTypeSingle) { - const auto kTestValue = common::CreateStaticByteBuffer('t', 'e', 's', 't'); + const auto kTestValue = CreateStaticByteBuffer('t', 'e', 's', 't'); // Start: 1, end: 2 auto* grp = db()->NewGrouping(types::kPrimaryService, 1, kTestValue); - grp->AddAttribute(common::UUID(), att::AccessRequirements(), + grp->AddAttribute(UUID(), att::AccessRequirements(), att::AccessRequirements()); grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x10, // opcode: read by group type 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF 0x00, 0x28 // group type: 0x2800 (primary service) ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x11, // opcode: read by group type response 0x08, // length: 8 (strlen("test") + 4) 0x01, 0x00, // start: 0x0001 @@ -622,16 +619,16 @@ TEST_F(GATT_ServerTest, ReadByGroupTypeSingle) { } TEST_F(GATT_ServerTest, ReadByGroupTypeSingle128) { - const auto kTestValue = common::CreateStaticByteBuffer('t', 'e', 's', 't'); + const auto kTestValue = CreateStaticByteBuffer('t', 'e', 's', 't'); // Start: 1, end: 2 auto* grp = db()->NewGrouping(types::kPrimaryService, 1, kTestValue); - grp->AddAttribute(common::UUID(), att::AccessRequirements(), + grp->AddAttribute(UUID(), att::AccessRequirements(), att::AccessRequirements()); grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x10, // opcode: read by group type 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF @@ -640,7 +637,7 @@ TEST_F(GATT_ServerTest, ReadByGroupTypeSingle128) { 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x11, // opcode: read by group type response 0x08, // length: 8 (strlen("test") + 4) 0x01, 0x00, // start: 0x0001 @@ -653,21 +650,21 @@ TEST_F(GATT_ServerTest, ReadByGroupTypeSingle128) { } TEST_F(GATT_ServerTest, ReadByGroupTypeSingleTruncated) { - const auto kTestValue = common::CreateStaticByteBuffer('t', 'e', 's', 't'); + const auto kTestValue = CreateStaticByteBuffer('t', 'e', 's', 't'); // Start: 1, end: 1 auto* grp = db()->NewGrouping(types::kPrimaryService, 0, kTestValue); grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x10, // opcode: read by group type 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF 0x00, 0x28 // group type: 0x2800 (primary service) ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x11, // opcode: read by group type response 0x06, // length: 6 (strlen("te") + 4) 0x01, 0x00, // start: 0x0001 @@ -701,14 +698,14 @@ TEST_F(GATT_ServerTest, ReadByGroupTypeMultipleSameValueSize) { db()->NewGrouping(types::kPrimaryService, 0, kTestValue4)->set_active(true); // clang-format off - const auto kRequest1 = common::CreateStaticByteBuffer( + const auto kRequest1 = CreateStaticByteBuffer( 0x10, // opcode: read by group type 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF 0x00, 0x28 // group type: 0x2800 (primary service) ); - const auto kExpected1 = common::CreateStaticByteBuffer( + const auto kExpected1 = CreateStaticByteBuffer( 0x11, // opcode: read by group type response 0x07, // length: 7 (strlen("foo") + 4) 0x01, 0x00, // start: 0x0001 @@ -732,14 +729,14 @@ TEST_F(GATT_ServerTest, ReadByGroupTypeMultipleSameValueSize) { // Search a narrower range. Only two groups should be returned even with room // in MTU. // clang-format off - const auto kRequest2 = common::CreateStaticByteBuffer( + const auto kRequest2 = CreateStaticByteBuffer( 0x10, // opcode: read by group type 0x02, 0x00, // start: 0x0002 0x04, 0x00, // end: 0x0004 0x00, 0x28 // group type: 0x2800 (primary service) ); - const auto kExpected2 = common::CreateStaticByteBuffer( + const auto kExpected2 = CreateStaticByteBuffer( 0x11, // opcode: read by group type response 0x07, // length: 7 (strlen("foo") + 4) 0x02, 0x00, // start: 0x0002 @@ -755,7 +752,7 @@ TEST_F(GATT_ServerTest, ReadByGroupTypeMultipleSameValueSize) { // Make the second group inactive. It should get omitted. // clang-format off - const auto kExpected3 = common::CreateStaticByteBuffer( + const auto kExpected3 = CreateStaticByteBuffer( 0x11, // opcode: read by group type response 0x07, // length: 7 (strlen("foo") + 4) 0x04, 0x00, // start: 0x0004 @@ -780,14 +777,14 @@ TEST_F(GATT_ServerTest, ReadByGroupTypeMultipleVaryingLengths) { db()->NewGrouping(types::kPrimaryService, 0, kTestValue1)->set_active(true); // clang-format off - const auto kRequest2 = common::CreateStaticByteBuffer( + const auto kRequest2 = CreateStaticByteBuffer( 0x10, // opcode: read by group type 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF 0x00, 0x28 // group type: 0x2800 (primary service) ); - const auto kExpected2 = common::CreateStaticByteBuffer( + const auto kExpected2 = CreateStaticByteBuffer( 0x11, // opcode: read by group type response 0x08, // length: 8 (strlen("long") + 4) 0x01, 0x00, // start: 0x0001 @@ -800,8 +797,8 @@ TEST_F(GATT_ServerTest, ReadByGroupTypeMultipleVaryingLengths) { TEST_F(GATT_ServerTest, ReadByTypeInvalidPDU) { // Just opcode // clang-format off - const auto kInvalidPDU = common::CreateStaticByteBuffer(0x08); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kInvalidPDU = CreateStaticByteBuffer(0x08); + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x08, // request: read by type 0x00, 0x00, // handle: 0 @@ -815,14 +812,14 @@ TEST_F(GATT_ServerTest, ReadByTypeInvalidPDU) { TEST_F(GATT_ServerTest, ReadByTypeInvalidHandle) { // Start handle is 0 // clang-format off - const auto kInvalidStartHandle = common::CreateStaticByteBuffer( + const auto kInvalidStartHandle = CreateStaticByteBuffer( 0x08, // opcode: read by type 0x00, 0x00, // start: 0x0000 0xFF, 0xFF, // end: 0xFFFF 0x00, 0x28 // group type: 0x2800 (primary service) ); - const auto kExpected1 = common::CreateStaticByteBuffer( + const auto kExpected1 = CreateStaticByteBuffer( 0x01, // opcode: error response 0x08, // request: read by type 0x00, 0x00, // handle: 0x0000 (start handle in request) @@ -830,14 +827,14 @@ TEST_F(GATT_ServerTest, ReadByTypeInvalidHandle) { ); // End handle is smaller than start handle - const auto kInvalidEndHandle = common::CreateStaticByteBuffer( + const auto kInvalidEndHandle = CreateStaticByteBuffer( 0x08, // opcode: read by type 0x02, 0x00, // start: 0x0002 0x01, 0x00, // end: 0x0001 0x00, 0x28 // group type: 0x2800 (primary service) ); - const auto kExpected2 = common::CreateStaticByteBuffer( + const auto kExpected2 = CreateStaticByteBuffer( 0x01, // opcode: error response 0x08, // request: read by type 0x02, 0x00, // handle: 0x0002 (start handle in request) @@ -851,14 +848,14 @@ TEST_F(GATT_ServerTest, ReadByTypeInvalidHandle) { TEST_F(GATT_ServerTest, ReadByTypeAttributeNotFound) { // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x08, // opcode: read by type 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF 0xEF, 0xBE // type: 0xBEEF ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x08, // request: read by type 0x01, 0x00, // handle: 0x0001 (start handle in request) @@ -875,7 +872,7 @@ TEST_F(GATT_ServerTest, ReadByTypeAttributeNotFound) { } TEST_F(GATT_ServerTest, ReadByTypeDynamicValueNoHandler) { - const auto kTestValue = common::CreateStaticByteBuffer('t', 'e', 's', 't'); + const auto kTestValue = CreateStaticByteBuffer('t', 'e', 's', 't'); auto* grp = db()->NewGrouping(types::kPrimaryService, 1, kTestValue); grp->AddAttribute(kTestType16, AllowedNoSecurity(), @@ -883,14 +880,14 @@ TEST_F(GATT_ServerTest, ReadByTypeDynamicValueNoHandler) { grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x08, // opcode: read by type 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF 0xEF, 0xBE // type: 0xBEEF ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x08, // request: read by type 0x02, 0x00, // handle: 0x0002 (the attribute causing the error) @@ -909,7 +906,7 @@ TEST_F(GATT_ServerTest, ReadByTypeDynamicValue) { EXPECT_EQ(attr->handle(), handle); EXPECT_EQ(0u, offset); result_cb(att::ErrorCode::kNoError, - common::CreateStaticByteBuffer('f', 'o', 'r', 'k')); + CreateStaticByteBuffer('f', 'o', 'r', 'k')); }); // Add a second dynamic attribute, which should be omitted. @@ -917,14 +914,14 @@ TEST_F(GATT_ServerTest, ReadByTypeDynamicValue) { grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x08, // opcode: read by type 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF 0xEF, 0xBE // type: 0xBEEF ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x09, // opcode: read by type response 0x06, // length: 6 (strlen("fork") + 2) 0x02, 0x00, // handle: 0x0002 @@ -941,26 +938,26 @@ TEST_F(GATT_ServerTest, ReadByTypeDynamicValue) { } TEST_F(GATT_ServerTest, ReadByTypeDynamicValueError) { - const auto kTestValue = common::CreateStaticByteBuffer('t', 'e', 's', 't'); + const auto kTestValue = CreateStaticByteBuffer('t', 'e', 's', 't'); auto* grp = db()->NewGrouping(types::kPrimaryService, 1, kTestValue); auto* attr = grp->AddAttribute(kTestType16, AllowedNoSecurity(), att::AccessRequirements()); attr->set_read_handler( [](PeerId peer_id, auto handle, uint16_t offset, const auto& result_cb) { - result_cb(att::ErrorCode::kUnlikelyError, common::BufferView()); + result_cb(att::ErrorCode::kUnlikelyError, BufferView()); }); grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x08, // opcode: read by type 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF 0xEF, 0xBE // type: 0xBEEF ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x08, // request: read by type 0x02, 0x00, // handle: 0x0002 (the attribute causing the error) @@ -972,8 +969,8 @@ TEST_F(GATT_ServerTest, ReadByTypeDynamicValueError) { } TEST_F(GATT_ServerTest, ReadByTypeSingle) { - const auto kTestValue1 = common::CreateStaticByteBuffer('f', 'o', 'o'); - const auto kTestValue2 = common::CreateStaticByteBuffer('t', 'e', 's', 't'); + const auto kTestValue1 = CreateStaticByteBuffer('f', 'o', 'o'); + const auto kTestValue2 = CreateStaticByteBuffer('t', 'e', 's', 't'); auto* grp = db()->NewGrouping(types::kPrimaryService, 1, kTestValue1); grp->AddAttribute(kTestType16, AllowedNoSecurity(), att::AccessRequirements()) @@ -981,14 +978,14 @@ TEST_F(GATT_ServerTest, ReadByTypeSingle) { grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x08, // opcode: read by type 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF 0xEF, 0xBE // type: 0xBEEF ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x09, // opcode: read by type response 0x06, // length: 6 (strlen("test") + 2) 0x02, 0x00, // handle: 0x0002 @@ -1001,8 +998,8 @@ TEST_F(GATT_ServerTest, ReadByTypeSingle) { } TEST_F(GATT_ServerTest, ReadByTypeSingle128) { - const auto kTestValue1 = common::CreateStaticByteBuffer('f', 'o', 'o'); - const auto kTestValue2 = common::CreateStaticByteBuffer('t', 'e', 's', 't'); + const auto kTestValue1 = CreateStaticByteBuffer('f', 'o', 'o'); + const auto kTestValue2 = CreateStaticByteBuffer('t', 'e', 's', 't'); auto* grp = db()->NewGrouping(types::kPrimaryService, 1, kTestValue1); grp->AddAttribute(kTestType128, AllowedNoSecurity(), @@ -1011,7 +1008,7 @@ TEST_F(GATT_ServerTest, ReadByTypeSingle128) { grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x08, // opcode: read by type 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF @@ -1020,7 +1017,7 @@ TEST_F(GATT_ServerTest, ReadByTypeSingle128) { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x09, // opcode: read by type response 0x06, // length: 6 (strlen("test") + 2) 0x02, 0x00, // handle: 0x0002 @@ -1032,7 +1029,7 @@ TEST_F(GATT_ServerTest, ReadByTypeSingle128) { } TEST_F(GATT_ServerTest, ReadByTypeSingleTruncated) { - const auto kVeryLongValue = common::CreateStaticByteBuffer( + const auto kVeryLongValue = CreateStaticByteBuffer( 't', 'e', 's', 't', 'i', 'n', 'g', ' ', 'i', 's', ' ', 'f', 'u', 'n'); auto* grp = db()->NewGrouping(types::kPrimaryService, 1, kTestValue1); @@ -1041,14 +1038,14 @@ TEST_F(GATT_ServerTest, ReadByTypeSingleTruncated) { grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x08, // opcode: read by type 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF 0xEF, 0xBE // type: 0xBEEF ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x09, // opcode: read by type response 0x05, // length: 5 (strlen("tes") + 2) 0x02, 0x00, // handle: 0x0002 @@ -1075,13 +1072,13 @@ TEST_F(GATT_ServerTest, ReadByTypeMultipleExcludeFirstError) { grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x08, // opcode: read by type 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF 0xEF, 0xBE // type: 0xBEEF ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x09, // opcode: read by type response 0x05, // length: 5 (strlen("foo") + 2) 0x01, 0x00, // handle: 0x0001 @@ -1114,14 +1111,14 @@ TEST_F(GATT_ServerTest, ReadByTypeMultipleSameValueSize) { grp->set_active(true); // clang-format off - const auto kRequest1 = common::CreateStaticByteBuffer( + const auto kRequest1 = CreateStaticByteBuffer( 0x08, // opcode: read by type 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF 0xEF, 0xBE // type: 0xBEEF ); - const auto kExpected1 = common::CreateStaticByteBuffer( + const auto kExpected1 = CreateStaticByteBuffer( 0x09, // opcode: read by type response 0x05, // length: 5 (strlen("foo") + 2) 0x02, 0x00, // handle: 0x0002 @@ -1139,7 +1136,7 @@ TEST_F(GATT_ServerTest, ReadByTypeMultipleSameValueSize) { att()->set_mtu(kExpected1.size() - 1); // clang-format off - const auto kExpected2 = common::CreateStaticByteBuffer( + const auto kExpected2 = CreateStaticByteBuffer( 0x09, // opcode: read by type response 0x05, // length: 5 (strlen("foo") + 2) 0x02, 0x00, // handle: 0x0002 @@ -1153,14 +1150,14 @@ TEST_F(GATT_ServerTest, ReadByTypeMultipleSameValueSize) { // Try a different range. // clang-format off - const auto kRequest2 = common::CreateStaticByteBuffer( + const auto kRequest2 = CreateStaticByteBuffer( 0x08, // opcode: read by type 0x03, 0x00, // start: 0x0003 0x05, 0x00, // end: 0x0005 0xEF, 0xBE // type: 0xBEEF ); - const auto kExpected3 = common::CreateStaticByteBuffer( + const auto kExpected3 = CreateStaticByteBuffer( 0x09, // opcode: read by type response 0x05, // length: 5 (strlen("bar") + 2) 0x03, 0x00, // handle: 0x0003 @@ -1176,7 +1173,7 @@ TEST_F(GATT_ServerTest, ReadByTypeMultipleSameValueSize) { grp->set_active(false); // clang-format off - const auto kExpected4 = common::CreateStaticByteBuffer( + const auto kExpected4 = CreateStaticByteBuffer( 0x09, // opcode: read by type response 0x05, // length: 5 (strlen("bar") + 2) 0x03, 0x00, // handle: 0x0003 @@ -1205,37 +1202,37 @@ TEST_F(GATT_ServerTest, ReadByTypeMultipleVaryingLengths) { // sizes. // clang-format off - const auto kRequest1 = common::CreateStaticByteBuffer( + const auto kRequest1 = CreateStaticByteBuffer( 0x08, // opcode: read by type 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF 0xEF, 0xBE // type: 0xBEEF ); - const auto kExpected1 = common::CreateStaticByteBuffer( + const auto kExpected1 = CreateStaticByteBuffer( 0x09, // opcode: read by type response 0x05, // length: 5 (strlen("foo") + 2) 0x01, 0x00, // handle: 0x0001 'f', 'o', 'o' // value: "foo" ); - const auto kRequest2 = common::CreateStaticByteBuffer( + const auto kRequest2 = CreateStaticByteBuffer( 0x08, // opcode: read by type 0x02, 0x00, // start: 0x0002 0xFF, 0xFF, // end: 0xFFFF 0xEF, 0xBE // type: 0xBEEF ); - const auto kExpected2 = common::CreateStaticByteBuffer( + const auto kExpected2 = CreateStaticByteBuffer( 0x09, // opcode: read by type response 0x06, // length: 6 (strlen("long") + 2) 0x02, 0x00, // handle: 0x0002 'l', 'o', 'n', 'g' // value: "long" ); - const auto kRequest3 = common::CreateStaticByteBuffer( + const auto kRequest3 = CreateStaticByteBuffer( 0x08, // opcode: read by type 0x03, 0x00, // start: 0x0003 0xFF, 0xFF, // end: 0xFFFF 0xEF, 0xBE // type: 0xBEEF ); - const auto kExpected3 = common::CreateStaticByteBuffer( + const auto kExpected3 = CreateStaticByteBuffer( 0x09, // opcode: read by type response 0x05, // length: 5 (strlen("foo") + 2) 0x03, 0x00, // handle: 0x0003 @@ -1259,13 +1256,13 @@ TEST_F(GATT_ServerTest, ReadByTypeMultipleExcludeFirstDynamic) { grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x08, // opcode: read by type 0x01, 0x00, // start: 0x0001 0xFF, 0xFF, // end: 0xFFFF 0xEF, 0xBE // type: 0xBEEF ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x09, // opcode: read by type response 0x05, // length: 5 (strlen("foo") + 2) 0x01, 0x00, // handle: 0x0001 @@ -1279,8 +1276,8 @@ TEST_F(GATT_ServerTest, ReadByTypeMultipleExcludeFirstDynamic) { TEST_F(GATT_ServerTest, WriteRequestInvalidPDU) { // Just opcode // clang-format off - const auto kInvalidPDU = common::CreateStaticByteBuffer(0x12); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kInvalidPDU = CreateStaticByteBuffer(0x12); + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x12, // request: write request 0x00, 0x00, // handle: 0 @@ -1293,14 +1290,14 @@ TEST_F(GATT_ServerTest, WriteRequestInvalidPDU) { TEST_F(GATT_ServerTest, WriteRequestInvalidHandle) { // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x12, // opcode: write request 0x01, 0x00, // handle: 0x0001 // value: "test" 't', 'e', 's', 't'); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x12, // request: write request 0x01, 0x00, // handle: 0x0001 @@ -1312,7 +1309,7 @@ TEST_F(GATT_ServerTest, WriteRequestInvalidHandle) { } TEST_F(GATT_ServerTest, WriteRequestSecurity) { - const auto kTestValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kTestValue = CreateStaticByteBuffer('f', 'o', 'o'); auto* grp = db()->NewGrouping(types::kPrimaryService, 1, kTestValue); // Requires encryption @@ -1325,27 +1322,27 @@ TEST_F(GATT_ServerTest, WriteRequestSecurity) { // 2. 0x0002: writable but requires encryption // // clang-format off - const auto kRequest1 = common::CreateStaticByteBuffer( + const auto kRequest1 = CreateStaticByteBuffer( 0x12, // opcode: write request 0x01, 0x00, // handle: 0x0001 // value: "test" 't', 'e', 's', 't'); - const auto kExpected1 = common::CreateStaticByteBuffer( + const auto kExpected1 = CreateStaticByteBuffer( 0x01, // opcode: error response 0x12, // request: write request 0x01, 0x00, // handle: 0x0001 0x03 // error: write not permitted ); - const auto kRequest2 = common::CreateStaticByteBuffer( + const auto kRequest2 = CreateStaticByteBuffer( 0x12, // opcode: write request 0x02, 0x00, // handle: 0x0002 // value: "test" 't', 'e', 's', 't'); - const auto kExpected2 = common::CreateStaticByteBuffer( + const auto kExpected2 = CreateStaticByteBuffer( 0x01, // opcode: error response 0x12, // request: write request 0x02, 0x00, // handle: 0x0002 @@ -1358,7 +1355,7 @@ TEST_F(GATT_ServerTest, WriteRequestSecurity) { } TEST_F(GATT_ServerTest, WriteRequestNoHandler) { - const auto kTestValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kTestValue = CreateStaticByteBuffer('f', 'o', 'o'); auto* grp = db()->NewGrouping(types::kPrimaryService, 1, kTestValue); grp->AddAttribute(kTestType16, att::AccessRequirements(), @@ -1366,14 +1363,14 @@ TEST_F(GATT_ServerTest, WriteRequestNoHandler) { grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x12, // opcode: write request 0x02, 0x00, // handle: 0x0002 // value: "test" 't', 'e', 's', 't'); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x12, // request: write request 0x02, 0x00, // handle: 0x0002 @@ -1385,7 +1382,7 @@ TEST_F(GATT_ServerTest, WriteRequestNoHandler) { } TEST_F(GATT_ServerTest, WriteRequestError) { - const auto kTestValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kTestValue = CreateStaticByteBuffer('f', 'o', 'o'); auto* grp = db()->NewGrouping(types::kPrimaryService, 1, kTestValue); auto* attr = grp->AddAttribute(kTestType16, att::AccessRequirements(), AllowedNoSecurity()); @@ -1396,22 +1393,22 @@ TEST_F(GATT_ServerTest, WriteRequestError) { EXPECT_EQ(kTestPeerId, peer_id); EXPECT_EQ(attr->handle(), handle); EXPECT_EQ(0u, offset); - EXPECT_TRUE(common::ContainersEqual( - common::CreateStaticByteBuffer('t', 'e', 's', 't'), value)); + EXPECT_TRUE( + ContainersEqual(CreateStaticByteBuffer('t', 'e', 's', 't'), value)); result_cb(att::ErrorCode::kUnlikelyError); }); grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x12, // opcode: write request 0x02, 0x00, // handle: 0x0002 // value: "test" 't', 'e', 's', 't'); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x12, // request: write request 0x02, 0x00, // handle: 0x0002 @@ -1423,7 +1420,7 @@ TEST_F(GATT_ServerTest, WriteRequestError) { } TEST_F(GATT_ServerTest, WriteRequestSuccess) { - const auto kTestValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kTestValue = CreateStaticByteBuffer('f', 'o', 'o'); auto* grp = db()->NewGrouping(types::kPrimaryService, 1, kTestValue); auto* attr = grp->AddAttribute(kTestType16, att::AccessRequirements(), AllowedNoSecurity()); @@ -1434,15 +1431,15 @@ TEST_F(GATT_ServerTest, WriteRequestSuccess) { EXPECT_EQ(kTestPeerId, peer_id); EXPECT_EQ(attr->handle(), handle); EXPECT_EQ(0u, offset); - EXPECT_TRUE(common::ContainersEqual( - common::CreateStaticByteBuffer('t', 'e', 's', 't'), value)); + EXPECT_TRUE( + ContainersEqual(CreateStaticByteBuffer('t', 'e', 's', 't'), value)); result_cb(att::ErrorCode::kNoError); }); grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x12, // opcode: write request 0x02, 0x00, // handle: 0x0002 @@ -1451,7 +1448,7 @@ TEST_F(GATT_ServerTest, WriteRequestSuccess) { // clang-format on // opcode: write response - const auto kExpected = common::CreateStaticByteBuffer(0x13); + const auto kExpected = CreateStaticByteBuffer(0x13); EXPECT_TRUE(ReceiveAndExpect(kRequest, kExpected)); } @@ -1460,7 +1457,7 @@ TEST_F(GATT_ServerTest, WriteRequestSuccess) { // Command (NET-387) TEST_F(GATT_ServerTest, WriteCommandSuccess) { - const auto kTestValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kTestValue = CreateStaticByteBuffer('f', 'o', 'o'); auto* grp = db()->NewGrouping(types::kPrimaryService, 1, kTestValue); auto* attr = grp->AddAttribute(kTestType16, att::AccessRequirements(), AllowedNoSecurity()); @@ -1471,13 +1468,13 @@ TEST_F(GATT_ServerTest, WriteCommandSuccess) { EXPECT_EQ(kTestPeerId, peer_id); EXPECT_EQ(attr->handle(), handle); EXPECT_EQ(0u, offset); - EXPECT_TRUE(common::ContainersEqual( - common::CreateStaticByteBuffer('t', 'e', 's', 't'), value)); + EXPECT_TRUE( + ContainersEqual(CreateStaticByteBuffer('t', 'e', 's', 't'), value)); }); grp->set_active(true); // clang-format off - const auto kCmd = common::CreateStaticByteBuffer( + const auto kCmd = CreateStaticByteBuffer( 0x52, // opcode: write command 0x02, 0x00, // handle: 0x0002 't', 'e', 's', 't'); @@ -1490,8 +1487,8 @@ TEST_F(GATT_ServerTest, WriteCommandSuccess) { TEST_F(GATT_ServerTest, ReadRequestInvalidPDU) { // Just opcode // clang-format off - const auto kInvalidPDU = common::CreateStaticByteBuffer(0x0A); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kInvalidPDU = CreateStaticByteBuffer(0x0A); + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x0A, // request: read request 0x00, 0x00, // handle: 0 @@ -1504,12 +1501,12 @@ TEST_F(GATT_ServerTest, ReadRequestInvalidPDU) { TEST_F(GATT_ServerTest, ReadRequestInvalidHandle) { // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x0A, // opcode: read request 0x01, 0x00 // handle: 0x0001 ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x0A, // request: read request 0x01, 0x00, // handle: 0x0001 @@ -1521,7 +1518,7 @@ TEST_F(GATT_ServerTest, ReadRequestInvalidHandle) { } TEST_F(GATT_ServerTest, ReadRequestSecurity) { - const auto kTestValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kTestValue = CreateStaticByteBuffer('f', 'o', 'o'); auto* grp = db()->NewGrouping(types::kPrimaryService, 1, kTestValue); // Requires encryption @@ -1530,11 +1527,11 @@ TEST_F(GATT_ServerTest, ReadRequestSecurity) { grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x0A, // opcode: read request 0x02, 0x00 // handle: 0x0002 ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x0A, // request: read request 0x02, 0x00, // handle: 0x0002 @@ -1546,8 +1543,8 @@ TEST_F(GATT_ServerTest, ReadRequestSecurity) { } TEST_F(GATT_ServerTest, ReadRequestCached) { - const auto kDeclValue = common::CreateStaticByteBuffer('d', 'e', 'c', 'l'); - const auto kTestValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kDeclValue = CreateStaticByteBuffer('d', 'e', 'c', 'l'); + const auto kTestValue = CreateStaticByteBuffer('f', 'o', 'o'); auto* grp = db()->NewGrouping(types::kPrimaryService, 1, kDeclValue); auto* attr = grp->AddAttribute(kTestType16, AllowedNoSecurity(), att::AccessRequirements()); @@ -1555,19 +1552,19 @@ TEST_F(GATT_ServerTest, ReadRequestCached) { grp->set_active(true); // clang-format off - const auto kRequest1 = common::CreateStaticByteBuffer( + const auto kRequest1 = CreateStaticByteBuffer( 0x0A, // opcode: read request 0x01, 0x00 // handle: 0x0001 ); - const auto kExpected1 = common::CreateStaticByteBuffer( + const auto kExpected1 = CreateStaticByteBuffer( 0x0B, // opcode: read response 'd', 'e', 'c', 'l' // value: kDeclValue ); - const auto kRequest2 = common::CreateStaticByteBuffer( + const auto kRequest2 = CreateStaticByteBuffer( 0x0A, // opcode: read request 0x02, 0x00 // handle: 0x0002 ); - const auto kExpected2 = common::CreateStaticByteBuffer( + const auto kExpected2 = CreateStaticByteBuffer( 0x0B, // opcode: read response 'f', 'o', 'o' // value: kTestValue ); @@ -1578,7 +1575,7 @@ TEST_F(GATT_ServerTest, ReadRequestCached) { } TEST_F(GATT_ServerTest, ReadRequestNoHandler) { - const auto kTestValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kTestValue = CreateStaticByteBuffer('f', 'o', 'o'); auto* grp = db()->NewGrouping(types::kPrimaryService, 1, kTestValue); grp->AddAttribute(kTestType16, AllowedNoSecurity(), @@ -1586,12 +1583,12 @@ TEST_F(GATT_ServerTest, ReadRequestNoHandler) { grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x0A, // opcode: read request 0x02, 0x00 // handle: 0x0002 ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x0A, // request: read request 0x02, 0x00, // handle: 0x0002 @@ -1603,7 +1600,7 @@ TEST_F(GATT_ServerTest, ReadRequestNoHandler) { } TEST_F(GATT_ServerTest, ReadRequestError) { - const auto kTestValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kTestValue = CreateStaticByteBuffer('f', 'o', 'o'); auto* grp = db()->NewGrouping(types::kPrimaryService, 1, kTestValue); auto* attr = grp->AddAttribute(kTestType16, AllowedNoSecurity(), att::AccessRequirements()); @@ -1613,17 +1610,17 @@ TEST_F(GATT_ServerTest, ReadRequestError) { EXPECT_EQ(attr->handle(), handle); EXPECT_EQ(0u, offset); - result_cb(att::ErrorCode::kUnlikelyError, common::BufferView()); + result_cb(att::ErrorCode::kUnlikelyError, BufferView()); }); grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x0A, // opcode: read request 0x02, 0x00 // handle: 0x0002 ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x0A, // request: read request 0x02, 0x00, // handle: 0x0002 @@ -1637,8 +1634,8 @@ TEST_F(GATT_ServerTest, ReadRequestError) { TEST_F(GATT_ServerTest, ReadBlobRequestInvalidPDU) { // Just opcode // clang-format off - const auto kInvalidPDU = common::CreateStaticByteBuffer(0x0C); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kInvalidPDU = CreateStaticByteBuffer(0x0C); + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x0C, // request: read blob request 0x00, 0x00, // handle: 0 @@ -1650,8 +1647,8 @@ TEST_F(GATT_ServerTest, ReadBlobRequestInvalidPDU) { } TEST_F(GATT_ServerTest, ReadBlobRequestDynamicSuccess) { - const auto kDeclValue = common::CreateStaticByteBuffer('d', 'e', 'c', 'l'); - const auto kTestValue = common::CreateStaticByteBuffer( + const auto kDeclValue = CreateStaticByteBuffer('d', 'e', 'c', 'l'); + const auto kTestValue = CreateStaticByteBuffer( 'A', ' ', 'V', 'e', 'r', 'y', ' ', 'L', 'o', 'n', 'g', ' ', 'D', 'e', 'v', 'i', 'c', 'e', ' ', 'N', 'a', 'm', 'e', ' ', 'U', 's', 'i', 'n', 'g', ' ', 'A', ' ', 'L', 'o', 'n', 'g', ' ', 'A', 't', 't', 'r', 'i', 'b', 'u', 't', @@ -1667,19 +1664,19 @@ TEST_F(GATT_ServerTest, ReadBlobRequestDynamicSuccess) { EXPECT_EQ(attr->handle(), handle); EXPECT_EQ(22u, offset); result_cb(att::ErrorCode::kNoError, - common::CreateStaticByteBuffer( - 'e', ' ', 'U', 's', 'i', 'n', 'g', ' ', 'A', ' ', 'L', 'o', - 'n', 'g', ' ', 'A', 't', 't', 'r', 'i', 'b', 'u')); + CreateStaticByteBuffer('e', ' ', 'U', 's', 'i', 'n', 'g', ' ', + 'A', ' ', 'L', 'o', 'n', 'g', ' ', 'A', + 't', 't', 'r', 'i', 'b', 'u')); }); grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x0C, // opcode: read blob request 0x02, 0x00, // handle: 0x0002 0x16, 0x00 // offset: 0x0016 ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x0D, // opcode: read blob response // Read Request response 'e', ' ', 'U', 's', 'i', 'n', 'g', ' ', 'A', ' ', 'L', @@ -1691,7 +1688,7 @@ TEST_F(GATT_ServerTest, ReadBlobRequestDynamicSuccess) { } TEST_F(GATT_ServerTest, ReadBlobDynamicRequestError) { - const auto kTestValue = common::CreateStaticByteBuffer( + const auto kTestValue = CreateStaticByteBuffer( 'A', ' ', 'V', 'e', 'r', 'y', ' ', 'L', 'o', 'n', 'g', ' ', 'D', 'e', 'v', 'i', 'c', 'e', ' ', 'N', 'a', 'm', 'e', ' ', 'U', 's', 'i', 'n', 'g', ' ', 'A', ' ', 'L', 'o', 'n', 'g', ' ', 'A', 't', 't', 'r', 'i', 'b', 'u', 't', @@ -1704,17 +1701,17 @@ TEST_F(GATT_ServerTest, ReadBlobDynamicRequestError) { EXPECT_EQ(kTestPeerId, peer_id); EXPECT_EQ(attr->handle(), handle); - result_cb(att::ErrorCode::kUnlikelyError, common::BufferView()); + result_cb(att::ErrorCode::kUnlikelyError, BufferView()); }); grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x0C, // opcode: read blob request 0x02, 0x00, // handle: 0x0002 0x16, 0x00 // offset: 0x0016 ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x0C, // request: read by type 0x02, 0x00, // handle: 0x0002 (the attribute causing the error) @@ -1726,7 +1723,7 @@ TEST_F(GATT_ServerTest, ReadBlobDynamicRequestError) { } TEST_F(GATT_ServerTest, ReadBlobRequestStaticSuccess) { - const auto kTestValue = common::CreateStaticByteBuffer( + const auto kTestValue = CreateStaticByteBuffer( 'A', ' ', 'V', 'e', 'r', 'y', ' ', 'L', 'o', 'n', 'g', ' ', 'D', 'e', 'v', 'i', 'c', 'e', ' ', 'N', 'a', 'm', 'e', ' ', 'U', 's', 'i', 'n', 'g', ' ', 'A', ' ', 'L', 'o', 'n', 'g', ' ', 'A', 't', 't', 'r', 'i', 'b', 'u', 't', @@ -1736,12 +1733,12 @@ TEST_F(GATT_ServerTest, ReadBlobRequestStaticSuccess) { grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x0C, // opcode: read blob request 0x01, 0x00, // handle: 0x0002 0x16, 0x00 // offset: 0x0016 ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x0D, // opcode: read blob response // Read Request response 'e', ' ', 'U', 's', 'i', 'n', 'g', ' ', 'A', ' ', 'L', @@ -1754,18 +1751,18 @@ TEST_F(GATT_ServerTest, ReadBlobRequestStaticSuccess) { TEST_F(GATT_ServerTest, ReadBlobRequestStaticOverflowError) { const auto kTestValue = - common::CreateStaticByteBuffer('s', 'h', 'o', 'r', 't', 'e', 'r'); + CreateStaticByteBuffer('s', 'h', 'o', 'r', 't', 'e', 'r'); auto* grp = db()->NewGrouping(types::kPrimaryService, 0, kTestValue); grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x0C, // opcode: read blob request 0x01, 0x00, // handle: 0x0001 0x16, 0x10 // offset: 0x1016 ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // Error 0x0C, // opcode 0x01, 0x00, // handle: 0x0001 @@ -1777,7 +1774,7 @@ TEST_F(GATT_ServerTest, ReadBlobRequestStaticOverflowError) { } TEST_F(GATT_ServerTest, ReadBlobRequestInvalidHandleError) { - const auto kTestValue = common::CreateStaticByteBuffer( + const auto kTestValue = CreateStaticByteBuffer( 'A', ' ', 'V', 'e', 'r', 'y', ' ', 'L', 'o', 'n', 'g', ' ', 'D', 'e', 'v', 'i', 'c', 'e', ' ', 'N', 'a', 'm', 'e', ' ', 'U', 's', 'i', 'n', 'g', ' ', 'A', ' ', 'L', 'o', 'n', 'g', ' ', 'A', 't', 't', 'r', 'i', 'b', 'u', 't', @@ -1786,12 +1783,12 @@ TEST_F(GATT_ServerTest, ReadBlobRequestInvalidHandleError) { grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x0C, // opcode: read blob request 0x02, 0x30, // handle: 0x0002 0x16, 0x00 // offset: 0x0016 ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x0C, // request: read blob request 0x02, 0x30, // handle: 0x0001 @@ -1803,7 +1800,7 @@ TEST_F(GATT_ServerTest, ReadBlobRequestInvalidHandleError) { } TEST_F(GATT_ServerTest, ReadBlobRequestNotPermitedError) { - const auto kTestValue = common::CreateStaticByteBuffer( + const auto kTestValue = CreateStaticByteBuffer( 'A', ' ', 'V', 'e', 'r', 'y', ' ', 'L', 'o', 'n', 'g', ' ', 'D', 'e', 'v', 'i', 'c', 'e', ' ', 'N', 'a', 'm', 'e', ' ', 'U', 's', 'i', 'n', 'g', ' ', 'A', ' ', 'L', 'o', 'n', 'g', ' ', 'A', 't', 't', 'r', 'i', 'b', 'u', 't', @@ -1816,17 +1813,17 @@ TEST_F(GATT_ServerTest, ReadBlobRequestNotPermitedError) { EXPECT_EQ(kTestPeerId, peer_id); EXPECT_EQ(attr->handle(), handle); - result_cb(att::ErrorCode::kUnlikelyError, common::BufferView()); + result_cb(att::ErrorCode::kUnlikelyError, BufferView()); }); grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x0C, // opcode: read blob request 0x02, 0x00, // handle: 0x0002 0x16, 0x00 // offset: 0x0016 ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x0C, // request: read by type 0x02, 0x00, // handle: 0x0002 (the attribute causing the error) @@ -1838,7 +1835,7 @@ TEST_F(GATT_ServerTest, ReadBlobRequestNotPermitedError) { } TEST_F(GATT_ServerTest, ReadBlobRequestInvalidOffsetError) { - const auto kTestValue = common::CreateStaticByteBuffer( + const auto kTestValue = CreateStaticByteBuffer( 'A', ' ', 'V', 'e', 'r', 'y', ' ', 'L', 'o', 'n', 'g', ' ', 'D', 'e', 'v', 'i', 'c', 'e', ' ', 'N', 'a', 'm', 'e', ' ', 'U', 's', 'i', 'n', 'g', ' ', 'A', ' ', 'L', 'o', 'n', 'g', ' ', 'A', 't', 't', 'r', 'i', 'b', 'u', 't', @@ -1852,17 +1849,17 @@ TEST_F(GATT_ServerTest, ReadBlobRequestInvalidOffsetError) { EXPECT_EQ(kTestPeerId, peer_id); EXPECT_EQ(attr->handle(), handle); - result_cb(att::ErrorCode::kInvalidOffset, common::BufferView()); + result_cb(att::ErrorCode::kInvalidOffset, BufferView()); }); grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x0C, // opcode: read blob request 0x02, 0x00, // handle: 0x0002 0x16, 0x40 // offset: 0x4016 ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x0C, // request: read by type 0x02, 0x00, // handle: 0x0002 (the attribute causing the error) @@ -1874,8 +1871,8 @@ TEST_F(GATT_ServerTest, ReadBlobRequestInvalidOffsetError) { } TEST_F(GATT_ServerTest, ReadRequestSuccess) { - const auto kDeclValue = common::CreateStaticByteBuffer('d', 'e', 'c', 'l'); - const auto kTestValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kDeclValue = CreateStaticByteBuffer('d', 'e', 'c', 'l'); + const auto kTestValue = CreateStaticByteBuffer('f', 'o', 'o'); auto* grp = db()->NewGrouping(types::kPrimaryService, 1, kTestValue); auto* attr = grp->AddAttribute(kTestType16, AllowedNoSecurity(), att::AccessRequirements()); @@ -1890,11 +1887,11 @@ TEST_F(GATT_ServerTest, ReadRequestSuccess) { grp->set_active(true); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x0A, // opcode: read request 0x02, 0x00 // handle: 0x0002 ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x0B, // opcode: read response 'f', 'o', 'o' // value: kTestValue ); @@ -1906,12 +1903,12 @@ TEST_F(GATT_ServerTest, ReadRequestSuccess) { TEST_F(GATT_ServerTest, PrepareWriteRequestInvalidPDU) { // Payload is one byte too short. // clang-format off - const auto kInvalidPDU = common::CreateStaticByteBuffer( + const auto kInvalidPDU = CreateStaticByteBuffer( 0x16, // opcode: prepare write request 0x01, 0x00, // handle: 0x0001 0x01 // offset (should be 2 bytes). ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x16, // request: prepare write request 0x00, 0x00, // handle: 0 @@ -1924,13 +1921,13 @@ TEST_F(GATT_ServerTest, PrepareWriteRequestInvalidPDU) { TEST_F(GATT_ServerTest, PrepareWriteRequestInvalidHandle) { // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x16, // opcode: prepare write request 0x01, 0x00, // handle: 0x0001 0x00, 0x00, // offset: 0 't', 'e', 's', 't' // value: "test" ); - const auto kResponse = common::CreateStaticByteBuffer( + const auto kResponse = CreateStaticByteBuffer( 0x01, // opcode: error response 0x16, // request: prepare write request 0x01, 0x00, // handle: 0x0001 @@ -1942,7 +1939,7 @@ TEST_F(GATT_ServerTest, PrepareWriteRequestInvalidHandle) { } TEST_F(GATT_ServerTest, PrepareWriteRequestSucceeds) { - const auto kTestValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kTestValue = CreateStaticByteBuffer('f', 'o', 'o'); auto* grp = db()->NewGrouping(types::kPrimaryService, 1, kTestValue); // No security requirement @@ -1957,13 +1954,13 @@ TEST_F(GATT_ServerTest, PrepareWriteRequestSucceeds) { ASSERT_EQ(0x0002, attr->handle()); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x16, // opcode: prepare write request 0x02, 0x00, // handle: 0x0002 0x00, 0x00, // offset: 0 't', 'e', 's', 't' // value: "test" ); - const auto kResponse = common::CreateStaticByteBuffer( + const auto kResponse = CreateStaticByteBuffer( 0x17, // opcode: prepare write response 0x02, 0x00, // handle: 0x0002 0x00, 0x00, // offset: 0 @@ -1978,7 +1975,7 @@ TEST_F(GATT_ServerTest, PrepareWriteRequestSucceeds) { } TEST_F(GATT_ServerTest, PrepareWriteRequestPrepareQueueFull) { - const auto kTestValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kTestValue = CreateStaticByteBuffer('f', 'o', 'o'); auto* grp = db()->NewGrouping(types::kPrimaryService, 1, kTestValue); // No security requirement @@ -1990,19 +1987,19 @@ TEST_F(GATT_ServerTest, PrepareWriteRequestPrepareQueueFull) { ASSERT_EQ(0x0002, attr->handle()); // clang-format off - const auto kRequest = common::CreateStaticByteBuffer( + const auto kRequest = CreateStaticByteBuffer( 0x16, // opcode: prepare write request 0x02, 0x00, // handle: 0x0002 0x00, 0x00, // offset: 0 't', 'e', 's', 't' // value: "test" ); - const auto kSuccessResponse = common::CreateStaticByteBuffer( + const auto kSuccessResponse = CreateStaticByteBuffer( 0x17, // opcode: prepare write response 0x02, 0x00, // handle: 0x0002 0x00, 0x00, // offset: 0 't', 'e', 's', 't' // value: "test" ); - const auto kErrorResponse = common::CreateStaticByteBuffer( + const auto kErrorResponse = CreateStaticByteBuffer( 0x01, // opcode: error response 0x16, // request: prepare write request 0x02, 0x00, // handle: 0x0002 @@ -2023,10 +2020,10 @@ TEST_F(GATT_ServerTest, PrepareWriteRequestPrepareQueueFull) { TEST_F(GATT_ServerTest, ExecuteWriteMalformedPayload) { // Payload is one byte too short. // clang-format off - const auto kInvalidPDU = common::CreateStaticByteBuffer( + const auto kInvalidPDU = CreateStaticByteBuffer( 0x18 // opcode: execute write request ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x18, // request: execute write request 0x00, 0x00, // handle: 0 @@ -2040,11 +2037,11 @@ TEST_F(GATT_ServerTest, ExecuteWriteMalformedPayload) { TEST_F(GATT_ServerTest, ExecuteWriteInvalidFlag) { // Payload is one byte too short. // clang-format off - const auto kInvalidPDU = common::CreateStaticByteBuffer( + const auto kInvalidPDU = CreateStaticByteBuffer( 0x18, // opcode: execute write request 0xFF // flag: invalid ); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x01, // opcode: error response 0x18, // request: execute write request 0x00, 0x00, // handle: 0 @@ -2059,11 +2056,11 @@ TEST_F(GATT_ServerTest, ExecuteWriteInvalidFlag) { // success without writing to any attributes. TEST_F(GATT_ServerTest, ExecuteWriteQueueEmpty) { // clang-format off - const auto kExecute = common::CreateStaticByteBuffer( + const auto kExecute = CreateStaticByteBuffer( 0x18, // opcode: execute write request 0x01 // flag: "write pending" ); - const auto kExecuteResponse = common::CreateStaticByteBuffer( + const auto kExecuteResponse = CreateStaticByteBuffer( 0x19 // opcode: execute write response ); // clang-format on @@ -2073,7 +2070,7 @@ TEST_F(GATT_ServerTest, ExecuteWriteQueueEmpty) { } TEST_F(GATT_ServerTest, ExecuteWriteSuccess) { - auto buffer = common::CreateStaticByteBuffer('x', 'x', 'x', 'x', 'x', 'x'); + auto buffer = CreateStaticByteBuffer('x', 'x', 'x', 'x', 'x', 'x'); auto* grp = db()->NewGrouping(types::kPrimaryService, 1, kTestValue1); auto* attr = grp->AddAttribute(kTestType16, att::AccessRequirements(), @@ -2092,25 +2089,25 @@ TEST_F(GATT_ServerTest, ExecuteWriteSuccess) { // Prepare two partial writes of the string "hello!". // clang-format off - const auto kPrepare1 = common::CreateStaticByteBuffer( + const auto kPrepare1 = CreateStaticByteBuffer( 0x016, // opcode: prepare write request 0x02, 0x00, // handle: 0x0002 0x00, 0x00, // offset: 0 'h', 'e', 'l', 'l' // value: "hell" ); - const auto kPrepareResponse1 = common::CreateStaticByteBuffer( + const auto kPrepareResponse1 = CreateStaticByteBuffer( 0x017, // opcode: prepare write response 0x02, 0x00, // handle: 0x0002 0x00, 0x00, // offset: 0 'h', 'e', 'l', 'l' // value: "hell" ); - const auto kPrepare2 = common::CreateStaticByteBuffer( + const auto kPrepare2 = CreateStaticByteBuffer( 0x016, // opcode: prepare write request 0x02, 0x00, // handle: 0x0002 0x04, 0x00, // offset: 4 'o', '!' // value: "o!" ); - const auto kPrepareResponse2 = common::CreateStaticByteBuffer( + const auto kPrepareResponse2 = CreateStaticByteBuffer( 0x017, // opcode: prepare write response 0x02, 0x00, // handle: 0x0002 0x04, 0x00, // offset: 4 @@ -2119,13 +2116,13 @@ TEST_F(GATT_ServerTest, ExecuteWriteSuccess) { // Add an overlapping write that partial overwrites data from previous // payloads. - const auto kPrepare3 = common::CreateStaticByteBuffer( + const auto kPrepare3 = CreateStaticByteBuffer( 0x016, // opcode: prepare write request 0x02, 0x00, // handle: 0x0002 0x02, 0x00, // offset: 2 'r', 'p', '?' // value: "rp?" ); - const auto kPrepareResponse3 = common::CreateStaticByteBuffer( + const auto kPrepareResponse3 = CreateStaticByteBuffer( 0x017, // opcode: prepare write response 0x02, 0x00, // handle: 0x0002 0x02, 0x00, // offset: 2 @@ -2142,11 +2139,11 @@ TEST_F(GATT_ServerTest, ExecuteWriteSuccess) { EXPECT_EQ("xxxxxx", buffer.AsString()); // clang-format off - const auto kExecute = common::CreateStaticByteBuffer( + const auto kExecute = CreateStaticByteBuffer( 0x18, // opcode: execute write request 0x01 // flag: "write pending" ); - const auto kExecuteResponse = common::CreateStaticByteBuffer( + const auto kExecuteResponse = CreateStaticByteBuffer( 0x19 // opcode: execute write response ); // clang-format on @@ -2158,7 +2155,7 @@ TEST_F(GATT_ServerTest, ExecuteWriteSuccess) { // Tests that the rest of the queue is dropped if a prepared write fails. TEST_F(GATT_ServerTest, ExecuteWriteError) { - auto buffer = common::CreateStaticByteBuffer('x', 'x', 'x', 'x', 'x', 'x'); + auto buffer = CreateStaticByteBuffer('x', 'x', 'x', 'x', 'x', 'x'); auto* grp = db()->NewGrouping(types::kPrimaryService, 1, kTestValue1); auto* attr = grp->AddAttribute(kTestType16, att::AccessRequirements(), @@ -2182,25 +2179,25 @@ TEST_F(GATT_ServerTest, ExecuteWriteError) { // Prepare two partial writes of the string "hello!". // clang-format off - const auto kPrepare1 = common::CreateStaticByteBuffer( + const auto kPrepare1 = CreateStaticByteBuffer( 0x016, // opcode: prepare write request 0x02, 0x00, // handle: 0x0002 0x00, 0x00, // offset: 0 'h', 'e', 'l', 'l' // value: "hell" ); - const auto kPrepareResponse1 = common::CreateStaticByteBuffer( + const auto kPrepareResponse1 = CreateStaticByteBuffer( 0x017, // opcode: prepare write response 0x02, 0x00, // handle: 0x0002 0x00, 0x00, // offset: 0 'h', 'e', 'l', 'l' // value: "hell" ); - const auto kPrepare2 = common::CreateStaticByteBuffer( + const auto kPrepare2 = CreateStaticByteBuffer( 0x016, // opcode: prepare write request 0x02, 0x00, // handle: 0x0002 0x04, 0x00, // offset: 4 'o', '!' // value: "o!" ); - const auto kPrepareResponse2 = common::CreateStaticByteBuffer( + const auto kPrepareResponse2 = CreateStaticByteBuffer( 0x017, // opcode: prepare write response 0x02, 0x00, // handle: 0x0002 0x04, 0x00, // offset: 4 @@ -2215,11 +2212,11 @@ TEST_F(GATT_ServerTest, ExecuteWriteError) { EXPECT_EQ("xxxxxx", buffer.AsString()); // clang-format off - const auto kExecute = common::CreateStaticByteBuffer( + const auto kExecute = CreateStaticByteBuffer( 0x18, // opcode: execute write request 0x01 // flag: "write pending" ); - const auto kExecuteResponse = common::CreateStaticByteBuffer( + const auto kExecuteResponse = CreateStaticByteBuffer( 0x01, // opcode: error response 0x18, // request: execute write request 0x02, 0x00, // handle: 2 (the attribute in error) @@ -2248,20 +2245,19 @@ TEST_F(GATT_ServerTest, ExecuteWriteAbort) { EXPECT_EQ(kTestPeerId, peer_id); EXPECT_EQ(attr->handle(), handle); EXPECT_EQ(0u, offset); - EXPECT_TRUE(common::ContainersEqual( - common::CreateStaticByteBuffer('l', 'o', 'l'), value)); + EXPECT_TRUE(ContainersEqual(CreateStaticByteBuffer('l', 'o', 'l'), value)); result_cb(att::ErrorCode::kNoError); }); grp->set_active(true); // clang-format off - const auto kPrepareToAbort = common::CreateStaticByteBuffer( + const auto kPrepareToAbort = CreateStaticByteBuffer( 0x016, // opcode: prepare write request 0x02, 0x00, // handle: 0x0002 0x00, 0x00, // offset: 0 't', 'e', 's', 't' // value: "test" ); - const auto kPrepareToAbortResponse = common::CreateStaticByteBuffer( + const auto kPrepareToAbortResponse = CreateStaticByteBuffer( 0x017, // opcode: prepare write response 0x02, 0x00, // handle: 0x0002 0x00, 0x00, // offset: 0 @@ -2278,11 +2274,11 @@ TEST_F(GATT_ServerTest, ExecuteWriteAbort) { // Abort the writes. They should get dropped. // clang-format off - const auto kAbort = common::CreateStaticByteBuffer( + const auto kAbort = CreateStaticByteBuffer( 0x18, // opcode: execute write request 0x00 // flag: "cancel all" ); - const auto kAbortResponse = common::CreateStaticByteBuffer( + const auto kAbortResponse = CreateStaticByteBuffer( 0x19 // opcode: execute write response ); // clang-format on @@ -2292,23 +2288,23 @@ TEST_F(GATT_ServerTest, ExecuteWriteAbort) { // Prepare and commit a new write request. This one should take effect without // involving the previously aborted writes. // clang-format off - const auto kPrepareToCommit = common::CreateStaticByteBuffer( + const auto kPrepareToCommit = CreateStaticByteBuffer( 0x016, // opcode: prepare write request 0x02, 0x00, // handle: 0x0002 0x00, 0x00, // offset: 0 'l', 'o', 'l' // value: "lol" ); - const auto kPrepareToCommitResponse = common::CreateStaticByteBuffer( + const auto kPrepareToCommitResponse = CreateStaticByteBuffer( 0x017, // opcode: prepare write response 0x02, 0x00, // handle: 0x0002 0x00, 0x00, // offset: 0 'l', 'o', 'l' // value: "lol" ); - const auto kCommit = common::CreateStaticByteBuffer( + const auto kCommit = CreateStaticByteBuffer( 0x18, // opcode: execute write request 0x01 // flag: "write pending" ); - const auto kCommitResponse = common::CreateStaticByteBuffer( + const auto kCommitResponse = CreateStaticByteBuffer( 0x19 // opcode: execute write response ); // clang-format on @@ -2320,10 +2316,10 @@ TEST_F(GATT_ServerTest, ExecuteWriteAbort) { TEST_F(GATT_ServerTest, SendNotificationEmpty) { constexpr att::Handle kHandle = 0x1234; - const common::BufferView kTestValue; + const BufferView kTestValue; // clang-format off - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x1B, // opcode: notification 0x34, 0x12 // handle: |kHandle| ); @@ -2338,10 +2334,10 @@ TEST_F(GATT_ServerTest, SendNotificationEmpty) { TEST_F(GATT_ServerTest, SendNotification) { constexpr att::Handle kHandle = 0x1234; - const auto kTestValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kTestValue = CreateStaticByteBuffer('f', 'o', 'o'); // clang-format off - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x1B, // opcode: notification 0x34, 0x12, // handle: |kHandle| 'f', 'o', 'o' // value: |kTestValue| @@ -2357,10 +2353,10 @@ TEST_F(GATT_ServerTest, SendNotification) { TEST_F(GATT_ServerTest, SendIndicationEmpty) { constexpr att::Handle kHandle = 0x1234; - const common::BufferView kTestValue; + const BufferView kTestValue; // clang-format off - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x1D, // opcode: indication 0x34, 0x12 // handle: |kHandle| ); @@ -2375,10 +2371,10 @@ TEST_F(GATT_ServerTest, SendIndicationEmpty) { TEST_F(GATT_ServerTest, SendIndication) { constexpr att::Handle kHandle = 0x1234; - const auto kTestValue = common::CreateStaticByteBuffer('f', 'o', 'o'); + const auto kTestValue = CreateStaticByteBuffer('f', 'o', 'o'); // clang-format off - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x1D, // opcode: indication 0x34, 0x12, // handle: |kHandle| 'f', 'o', 'o' // value: |kTestValue| @@ -2457,12 +2453,14 @@ class GATT_ServerTest_Security : public GATT_ServerTest { // received from the fake channel (i.e. received FROM the ATT bearer). bool ExpectAttError(att::OpCode request, att::Handle handle, att::ErrorCode ecode) { - return Expect(common::CreateStaticByteBuffer( - 0x01, // opcode: error response - request, // request opcode - LowerBits(handle), UpperBits(handle), // handle - ecode // error code + // clang-format off + return Expect(CreateStaticByteBuffer( + 0x01, // opcode: error response + request, // request opcode + LowerBits(handle), UpperBits(handle), // handle + ecode // error code )); + // clang-format on } // Helpers for emulating the receipt of an ATT read/write request PDU and @@ -2470,14 +2468,14 @@ class GATT_ServerTest_Security : public GATT_ServerTest { // |expected_ecode| is att::ErrorCode::kNoError. bool EmulateReadByTypeRequest(att::Handle handle, att::ErrorCode expected_ecode) { - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x08, // opcode: read by type LowerBits(handle), UpperBits(handle), // start handle LowerBits(handle), UpperBits(handle), // end handle 0xEF, 0xBE // type: 0xBEEF, i.e. kTestType16 )); if (expected_ecode == att::ErrorCode::kNoError) { - return Expect(common::CreateStaticByteBuffer( + return Expect(CreateStaticByteBuffer( 0x09, // opcode: read by type response 0x05, // length: 5 (strlen("foo") + 2) LowerBits(handle), UpperBits(handle), // handle @@ -2490,13 +2488,15 @@ class GATT_ServerTest_Security : public GATT_ServerTest { bool EmulateReadBlobRequest(att::Handle handle, att::ErrorCode expected_ecode) { - fake_chan()->Receive(common::CreateStaticByteBuffer( + // clang-format off + fake_chan()->Receive(CreateStaticByteBuffer( 0x0C, // opcode: read blob LowerBits(handle), UpperBits(handle), // handle 0x00, 0x00 // offset: 0 )); + // clang-format on if (expected_ecode == att::ErrorCode::kNoError) { - return Expect(common::CreateStaticByteBuffer( + return Expect(CreateStaticByteBuffer( 0x0D, // opcode: read blob response 'f', 'o', 'o' // value: "foo", i.e. kTestValue1 )); @@ -2506,12 +2506,14 @@ class GATT_ServerTest_Security : public GATT_ServerTest { } bool EmulateReadRequest(att::Handle handle, att::ErrorCode expected_ecode) { - fake_chan()->Receive(common::CreateStaticByteBuffer( - 0x0A, // opcode: read request + // clang-format off + fake_chan()->Receive(CreateStaticByteBuffer( + 0x0A, // opcode: read request LowerBits(handle), UpperBits(handle) // handle )); + // clang-format on if (expected_ecode == att::ErrorCode::kNoError) { - return Expect(common::CreateStaticByteBuffer( + return Expect(CreateStaticByteBuffer( 0x0B, // opcode: read response 'f', 'o', 'o' // value: "foo", i.e. kTestValue1 )); @@ -2521,14 +2523,14 @@ class GATT_ServerTest_Security : public GATT_ServerTest { } bool EmulateWriteRequest(att::Handle handle, att::ErrorCode expected_ecode) { - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x12, // opcode: write request LowerBits(handle), UpperBits(handle), // handle 't', 'e', 's', 't' // value: "test" )); if (expected_ecode == att::ErrorCode::kNoError) { - return Expect(common::CreateStaticByteBuffer(0x13 // write response - )); + return Expect(CreateStaticByteBuffer(0x13 // write response + )); } else { return ExpectAttError(0x12, handle, expected_ecode); } @@ -2536,19 +2538,21 @@ class GATT_ServerTest_Security : public GATT_ServerTest { bool EmulatePrepareWriteRequest(att::Handle handle, att::ErrorCode expected_ecode) { - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x16, // opcode: prepare write request LowerBits(handle), UpperBits(handle), // handle 0x00, 0x00, // offset: 0 't', 'e', 's', 't' // value: "test" )); if (expected_ecode == att::ErrorCode::kNoError) { - return Expect(common::CreateStaticByteBuffer( - 0x17, // prepare write response - LowerBits(handle), UpperBits(handle), // handle - 0x00, 0x00, // offset: 0 - 't', 'e', 's', 't' // value: "test" + // clang-format off + return Expect(CreateStaticByteBuffer( + 0x17, // prepare write response + LowerBits(handle), UpperBits(handle), // handle + 0x00, 0x00, // offset: 0 + 't', 'e', 's', 't' // value: "test" )); + // clang-format on } else { return ExpectAttError(0x16, handle, expected_ecode); } @@ -2557,7 +2561,7 @@ class GATT_ServerTest_Security : public GATT_ServerTest { // Emulates the receipt of a Write Command. The expected error code parameter // is unused since ATT commands do not have a response. bool EmulateWriteCommand(att::Handle handle, att::ErrorCode) { - fake_chan()->Receive(common::CreateStaticByteBuffer( + fake_chan()->Receive(CreateStaticByteBuffer( 0x52, // opcode: write command LowerBits(handle), UpperBits(handle), // handle 't', 'e', 's', 't' // value: "test" diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/types.cc b/src/connectivity/bluetooth/core/bt-host/gatt/types.cc index b4d380929040defc58c272e53d5cbc67ba48a724..945b64afabed98fa129e2551970441ef98249865 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/types.cc +++ b/src/connectivity/bluetooth/core/bt-host/gatt/types.cc @@ -7,13 +7,11 @@ namespace bt { namespace gatt { -Service::Service(bool primary, const common::UUID& type) +Service::Service(bool primary, const UUID& type) : primary_(primary), type_(type) {} Characteristic::Characteristic( - IdType id, - const common::UUID& type, - uint8_t properties, + IdType id, const UUID& type, uint8_t properties, uint16_t extended_properties, const att::AccessRequirements& read_permissions, const att::AccessRequirements& write_permissions, @@ -26,8 +24,7 @@ Characteristic::Characteristic( write_permissions_(write_permissions), update_permissions_(update_permissions) {} -Descriptor::Descriptor(IdType id, - const common::UUID& type, +Descriptor::Descriptor(IdType id, const UUID& type, const att::AccessRequirements& read_permissions, const att::AccessRequirements& write_permissions) : id_(id), diff --git a/src/connectivity/bluetooth/core/bt-host/gatt/types.h b/src/connectivity/bluetooth/core/bt-host/gatt/types.h index 2eb6593367ff6db87a64c2bfc6c8ffcfec051cf3..a508da614e8b10bd0b172bf0f5fd9f3cff44460c 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt/types.h +++ b/src/connectivity/bluetooth/core/bt-host/gatt/types.h @@ -25,11 +25,11 @@ using CharacteristicPtr = std::unique_ptr<Characteristic>; // characteristics, includes, etc and is not intended to carry service state. class Service final { public: - Service(bool primary, const common::UUID& type); + Service(bool primary, const UUID& type); ~Service() = default; bool primary() const { return primary_; } - const common::UUID& type() const { return type_; } + const UUID& type() const { return type_; } // The list of characteristics that have been added to this service. const std::vector<CharacteristicPtr>& characteristics() const { @@ -50,7 +50,7 @@ class Service final { private: bool primary_; - common::UUID type_; + UUID type_; std::vector<CharacteristicPtr> characteristics_; DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(Service); @@ -65,7 +65,7 @@ using DescriptorPtr = std::unique_ptr<Descriptor>; // composition/structure of a characteristic and is not intended to carry state. class Characteristic final { public: - Characteristic(IdType id, const common::UUID& type, uint8_t properties, + Characteristic(IdType id, const UUID& type, uint8_t properties, uint16_t extended_properties, const att::AccessRequirements& read_permissions, const att::AccessRequirements& write_permissions, @@ -73,7 +73,7 @@ class Characteristic final { ~Characteristic() = default; IdType id() const { return id_; } - const common::UUID& type() const { return type_; } + const UUID& type() const { return type_; } uint8_t properties() const { return properties_; } uint16_t extended_properties() const { return extended_properties_; } @@ -102,7 +102,7 @@ class Characteristic final { private: IdType id_; - common::UUID type_; + UUID type_; uint8_t properties_; uint16_t extended_properties_; att::AccessRequirements read_permissions_; @@ -118,13 +118,13 @@ class Characteristic final { // to carry state. class Descriptor final { public: - Descriptor(IdType id, const common::UUID& type, + Descriptor(IdType id, const UUID& type, const att::AccessRequirements& read_permissions, const att::AccessRequirements& write_permissions); ~Descriptor() = default; IdType id() const { return id_; } - const common::UUID& type() const { return type_; } + const UUID& type() const { return type_; } const att::AccessRequirements& read_permissions() const { return read_permissions_; @@ -136,7 +136,7 @@ class Descriptor final { private: IdType id_; - common::UUID type_; + UUID type_; att::AccessRequirements read_permissions_; att::AccessRequirements write_permissions_; diff --git a/src/connectivity/bluetooth/core/bt-host/gatt_host.cc b/src/connectivity/bluetooth/core/bt-host/gatt_host.cc index 6c5510aed8074fc76ddc3a4a0297bded89ff8ed1..007240979e2f8079aff4559272bf3c8ed0d8f822 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt_host.cc +++ b/src/connectivity/bluetooth/core/bt-host/gatt_host.cc @@ -18,7 +18,7 @@ fbl::RefPtr<GattHost> GattHost::Create(std::string thrd_name) { } GattHost::GattHost(std::string thrd_name) - : bt::common::TaskDomain<GattHost>(this, std::move(thrd_name)), + : bt::TaskDomain<GattHost>(this, std::move(thrd_name)), weak_ptr_factory_(this) { // Initialize the profile to operate on our task runner. gatt_ = gatt::GATT::Create(dispatcher()); @@ -54,7 +54,7 @@ void GattHost::ShutDown() { remote_service_watcher_ = {}; } - bt::common::TaskDomain<GattHost>::ScheduleCleanUp(); + bt::TaskDomain<GattHost>::ScheduleCleanUp(); } void GattHost::CleanUp() { diff --git a/src/connectivity/bluetooth/core/bt-host/gatt_host.h b/src/connectivity/bluetooth/core/bt-host/gatt_host.h index e8c1640e21b04eec41a972b80357b3821148c9f7..5dc1bbc98a81aeb44c91a97d2c2644e6010b355d 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt_host.h +++ b/src/connectivity/bluetooth/core/bt-host/gatt_host.h @@ -37,7 +37,7 @@ class GattServerServer; // at least once to properly clean up this object before destruction (this is // asserted). class GattHost final : public fbl::RefCounted<GattHost>, - public bt::common::TaskDomain<GattHost> { + public bt::TaskDomain<GattHost> { public: // Type that can be used as a token in some of the functions below. Pointers // are allowed to be used as tokens. diff --git a/src/connectivity/bluetooth/core/bt-host/gatt_remote_service_device.cc b/src/connectivity/bluetooth/core/bt-host/gatt_remote_service_device.cc index 3f07d91b5fc6edebe43b39825cec54950a224256..d47c43f82cea66ae7afb773fc41dcf512367a885 100644 --- a/src/connectivity/bluetooth/core/bt-host/gatt_remote_service_device.cc +++ b/src/connectivity/bluetooth/core/bt-host/gatt_remote_service_device.cc @@ -17,7 +17,7 @@ namespace bthost { namespace { -void CopyUUIDBytes(bt_gatt_uuid_t* dest, const common::UUID source) { +void CopyUUIDBytes(bt_gatt_uuid_t* dest, const UUID source) { memcpy(dest->bytes, source.value().data(), sizeof(dest->bytes)); } @@ -65,25 +65,25 @@ bt_gatt_err_t AttErrorToDdkError(bt::att::ErrorCode error) { return BT_GATT_ERR_NO_ERROR; } -zx_status_t HostErrorToZxError(bt::common::HostError error) { +zx_status_t HostErrorToZxError(bt::HostError error) { switch (error) { - case bt::common::HostError::kNoError: + case bt::HostError::kNoError: return ZX_OK; - case bt::common::HostError::kNotFound: + case bt::HostError::kNotFound: return ZX_ERR_NOT_FOUND; - case bt::common::HostError::kNotReady: + case bt::HostError::kNotReady: return ZX_ERR_SHOULD_WAIT; - case bt::common::HostError::kTimedOut: + case bt::HostError::kTimedOut: return ZX_ERR_TIMED_OUT; - case bt::common::HostError::kInvalidParameters: + case bt::HostError::kInvalidParameters: return ZX_ERR_INVALID_ARGS; - case bt::common::HostError::kCanceled: + case bt::HostError::kCanceled: return ZX_ERR_CANCELED; - case bt::common::HostError::kNotSupported: + case bt::HostError::kNotSupported: return ZX_ERR_NOT_SUPPORTED; - case bt::common::HostError::kLinkDisconnected: + case bt::HostError::kLinkDisconnected: return ZX_ERR_CONNECTION_ABORTED; - case bt::common::HostError::kOutOfMemory: + case bt::HostError::kOutOfMemory: return ZX_ERR_NO_MEMORY; default: return ZX_ERR_INTERNAL; @@ -138,7 +138,7 @@ zx_status_t GattRemoteServiceDevice::Bind() { // The bind program of an attaching device driver can either bind using to the // well known short 16 bit UUID of the service if available or the full 128 // bit UUID (split across 4 32 bit values). - const common::UUID& uuid = service_->uuid(); + const UUID& uuid = service_->uuid(); uint32_t uuid16 = 0; if (uuid.CompactSize() == 2) { @@ -147,7 +147,7 @@ zx_status_t GattRemoteServiceDevice::Bind() { } uint32_t uuid01, uuid02, uuid03, uuid04 = 0; - common::UInt128 uuid_bytes = uuid.value(); + UInt128 uuid_bytes = uuid.value(); uuid01 = le32toh(*reinterpret_cast<uint32_t*>(&uuid_bytes[0])); uuid02 = le32toh(*reinterpret_cast<uint32_t*>(&uuid_bytes[4])); @@ -268,7 +268,7 @@ void GattRemoteServiceDevice::ReadCharacteristic( bt_gatt_id_t id, bt_gatt_svc_read_characteristic_callback read_cb, void* cookie) { auto read_callback = [id, cookie, read_cb](att::Status status, - const common::ByteBuffer& buff) { + const ByteBuffer& buff) { bt_gatt_status_t ddk_status = AttStatusToDdkStatus(status); read_cb(cookie, &ddk_status, id, buff.data(), buff.size()); }; @@ -282,7 +282,7 @@ void GattRemoteServiceDevice::ReadLongCharacteristic( bt_gatt_id_t id, uint16_t offset, size_t max_bytes, bt_gatt_svc_read_characteristic_callback read_cb, void* cookie) { auto read_callback = [id, cookie, read_cb](att::Status status, - const common::ByteBuffer& buff) { + const ByteBuffer& buff) { bt_gatt_status_t ddk_status = AttStatusToDdkStatus(status); read_cb(cookie, &ddk_status, id, buff.data(), buff.size()); }; @@ -318,7 +318,7 @@ void GattRemoteServiceDevice::EnableNotifications( bt_gatt_id_t id, const bt_gatt_notification_value_t* value, bt_gatt_svc_enable_notifications_callback status_cb, void* cookie) { auto value_cb = *value; - auto notif_callback = [cookie, id, value_cb](const common::ByteBuffer& buff) { + auto notif_callback = [cookie, id, value_cb](const ByteBuffer& buff) { value_cb.callback(value_cb.ctx, id, buff.data(), buff.size()); }; diff --git a/src/connectivity/bluetooth/core/bt-host/hci/acl_data_channel.cc b/src/connectivity/bluetooth/core/bt-host/hci/acl_data_channel.cc index e63891db00a78ade26d39bf05736cf54287c38f3..238aa7b9323cb26b016ff02ebcd4db4fbf8f7019 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/acl_data_channel.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/acl_data_channel.cc @@ -5,16 +5,16 @@ #include "acl_data_channel.h" #include <endian.h> - #include <lib/async/default.h> #include <zircon/assert.h> #include <zircon/status.h> +#include "slab_allocators.h" +#include "transport.h" + #include "src/connectivity/bluetooth/core/bt-host/common/log.h" #include "src/connectivity/bluetooth/core/bt-host/common/run_task_sync.h" #include "src/lib/fxl/strings/string_printf.h" -#include "slab_allocators.h" -#include "transport.h" namespace bt { namespace hci { @@ -73,7 +73,7 @@ void ACLDataChannel::Initialize(const DataBufferInfo& bredr_buffer_info, }; io_dispatcher_ = transport_->io_dispatcher(); - common::RunTaskSync(setup_handler_task, io_dispatcher_); + RunTaskSync(setup_handler_task, io_dispatcher_); // TODO(jamuraa): return whether we successfully initialized? if (channel_wait_.object() == ZX_HANDLE_INVALID) @@ -107,7 +107,7 @@ void ACLDataChannel::ShutDown() { } }; - common::RunTaskSync(handler_cleanup_task, io_dispatcher_); + RunTaskSync(handler_cleanup_task, io_dispatcher_); transport_->command_channel()->RemoveEventHandler(event_handler_id_); @@ -153,7 +153,7 @@ bool ACLDataChannel::SendPacket(ACLDataPacketPtr data_packet, return true; } -bool ACLDataChannel::SendPackets(common::LinkedList<ACLDataPacket> packets, +bool ACLDataChannel::SendPackets(LinkedList<ACLDataPacket> packets, Connection::LinkType ll_type) { if (!is_initialized_) { bt_log(TRACE, "hci", "cannot send packets while uninitialized"); @@ -397,11 +397,9 @@ void ACLDataChannel::IncrementLETotalNumPacketsLocked(size_t count) { le_num_sent_packets_ += count; } -void ACLDataChannel::OnChannelReady( - async_dispatcher_t* dispatcher, - async::WaitBase* wait, - zx_status_t status, - const zx_packet_signal_t* signal) { +void ACLDataChannel::OnChannelReady(async_dispatcher_t* dispatcher, + async::WaitBase* wait, zx_status_t status, + const zx_packet_signal_t* signal) { if (status != ZX_OK) { bt_log(ERROR, "hci", "channel error: %s", zx_status_get_string(status)); return; @@ -465,10 +463,10 @@ void ACLDataChannel::OnChannelReady( ZX_DEBUG_ASSERT(rx_dispatcher_); - async::PostTask(rx_dispatcher_, - [cb = rx_callback_.share(), packet = std::move(packet)]() mutable { - cb(std::move(packet)); - }); + async::PostTask(rx_dispatcher_, [cb = rx_callback_.share(), + packet = std::move(packet)]() mutable { + cb(std::move(packet)); + }); } status = wait->Begin(dispatcher); diff --git a/src/connectivity/bluetooth/core/bt-host/hci/acl_data_channel.h b/src/connectivity/bluetooth/core/bt-host/hci/acl_data_channel.h index 161af7db97c204fe67657af4784713faec502f3c..1e5772aa9d791ece7de0c062a917b123d5a42194 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/acl_data_channel.h +++ b/src/connectivity/bluetooth/core/bt-host/hci/acl_data_channel.h @@ -122,7 +122,7 @@ class ACLDataChannel final { // // Takes ownership of the contents of |packets|. Returns false if |packets| // contains an element that exceeds the MTU for |ll_type| or it is empty. - bool SendPackets(common::LinkedList<ACLDataPacket> packets, + bool SendPackets(LinkedList<ACLDataPacket> packets, Connection::LinkType ll_type); // Cleans up all outgoing data buffering state related to the logical link @@ -259,7 +259,7 @@ class ACLDataChannel final { // * Helps address the packet-prioritization TODO above. // * Also: having separate queues, which know their own // Connection::LinkType, would let us replace std::list<QueuedDataPacket> - // with common::LinkedList<ACLDataPacket> which has a more efficient + // with LinkedList<ACLDataPacket> which has a more efficient // memory layout. using DataPacketQueue = std::list<QueuedDataPacket>; DataPacketQueue send_queue_ __TA_GUARDED(send_mutex_); diff --git a/src/connectivity/bluetooth/core/bt-host/hci/acl_data_channel_unittest.cc b/src/connectivity/bluetooth/core/bt-host/hci/acl_data_channel_unittest.cc index 6b15acd7c11e7ad0267604fdd4ca353eb9a312f9..62d8ccdd2c04d37997c9e3960b3099ae68c1550e 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/acl_data_channel_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/acl_data_channel_unittest.cc @@ -80,11 +80,11 @@ TEST_F(HCI_ACLDataChannelTest, SendPacketBREDRBuffer) { int handle1_packet_count = 0; // Callback invoked by TestDevice when it receive a data packet from us. - auto data_callback = [&](const common::ByteBuffer& bytes) { + auto data_callback = [&](const ByteBuffer& bytes) { ZX_DEBUG_ASSERT(bytes.size() >= sizeof(ACLDataHeader)); - common::PacketView<hci::ACLDataHeader> packet( - &bytes, bytes.size() - sizeof(ACLDataHeader)); + PacketView<hci::ACLDataHeader> packet(&bytes, + bytes.size() - sizeof(ACLDataHeader)); ConnectionHandle connection_handle = le16toh(packet.header().handle_and_flags) & 0xFFF; @@ -118,7 +118,7 @@ TEST_F(HCI_ACLDataChannelTest, SendPacketBREDRBuffer) { EXPECT_EQ(2, handle1_packet_count); // Notify the processed packets with a Number Of Completed Packet HCI event. - auto event_buffer = common::CreateStaticByteBuffer( + auto event_buffer = CreateStaticByteBuffer( 0x13, 0x09, // Event header 0x02, // Number of handles 0x01, 0x00, 0x03, 0x00, // 3 packets on handle 0x0001 @@ -154,11 +154,11 @@ TEST_F(HCI_ACLDataChannelTest, SendPacketLEBuffer) { size_t handle0_packet_count = 0; size_t handle1_packet_count = 0; - auto data_callback = [&](const common::ByteBuffer& bytes) { + auto data_callback = [&](const ByteBuffer& bytes) { ZX_DEBUG_ASSERT(bytes.size() >= sizeof(ACLDataHeader)); - common::PacketView<hci::ACLDataHeader> packet( - &bytes, bytes.size() - sizeof(ACLDataHeader)); + PacketView<hci::ACLDataHeader> packet(&bytes, + bytes.size() - sizeof(ACLDataHeader)); ConnectionHandle connection_handle = le16toh(packet.header().handle_and_flags) & 0xFFF; @@ -200,10 +200,10 @@ TEST_F(HCI_ACLDataChannelTest, SendPacketLEBuffer) { EXPECT_EQ(0u, handle1_packet_count); // Notify the processed packets with a Number Of Completed Packet HCI event. - auto event_buffer = common::CreateStaticByteBuffer( - 0x13, 0x05, // Event header - 0x01, // Number of handles - 0x01, 0x00, 0x03, 0x00 // 3 packets on handle 0x0001 + auto event_buffer = CreateStaticByteBuffer(0x13, 0x05, // Event header + 0x01, // Number of handles + 0x01, 0x00, 0x03, + 0x00 // 3 packets on handle 0x0001 ); test_device()->SendCommandChannelPacket(event_buffer); @@ -235,11 +235,11 @@ TEST_F(HCI_ACLDataChannelTest, SendLEPacketBothBuffers) { int handle0_packet_count = 0; int handle1_packet_count = 0; - auto data_callback = [&](const common::ByteBuffer& bytes) { + auto data_callback = [&](const ByteBuffer& bytes) { ZX_DEBUG_ASSERT(bytes.size() >= sizeof(ACLDataHeader)); - common::PacketView<hci::ACLDataHeader> packet( - &bytes, bytes.size() - sizeof(ACLDataHeader)); + PacketView<hci::ACLDataHeader> packet(&bytes, + bytes.size() - sizeof(ACLDataHeader)); ConnectionHandle connection_handle = le16toh(packet.header().handle_and_flags) & 0xFFF; @@ -273,7 +273,7 @@ TEST_F(HCI_ACLDataChannelTest, SendLEPacketBothBuffers) { EXPECT_EQ(2, handle1_packet_count); // Notify the processed packets with a Number Of Completed Packet HCI event. - auto event_buffer = common::CreateStaticByteBuffer( + auto event_buffer = CreateStaticByteBuffer( 0x13, 0x09, // Event header 0x02, // Number of handles 0x01, 0x00, 0x03, 0x00, // 3 packets on handle 0x0001 @@ -309,11 +309,11 @@ TEST_F(HCI_ACLDataChannelTest, SendBREDRPacketBothBuffers) { int handle0_packet_count = 0; int handle1_packet_count = 0; - auto data_callback = [&](const common::ByteBuffer& bytes) { + auto data_callback = [&](const ByteBuffer& bytes) { ZX_DEBUG_ASSERT(bytes.size() >= sizeof(ACLDataHeader)); - common::PacketView<hci::ACLDataHeader> packet( - &bytes, bytes.size() - sizeof(ACLDataHeader)); + PacketView<hci::ACLDataHeader> packet(&bytes, + bytes.size() - sizeof(ACLDataHeader)); ConnectionHandle connection_handle = le16toh(packet.header().handle_and_flags) & 0xFFF; @@ -347,7 +347,7 @@ TEST_F(HCI_ACLDataChannelTest, SendBREDRPacketBothBuffers) { EXPECT_EQ(2, handle1_packet_count); // Notify the processed packets with a Number Of Completed Packet HCI event. - auto event_buffer = common::CreateStaticByteBuffer( + auto event_buffer = CreateStaticByteBuffer( 0x13, 0x09, // Event header 0x02, // Number of handles 0x01, 0x00, 0x03, 0x00, // 3 packets on handle 0x0001 @@ -380,11 +380,11 @@ TEST_F(HCI_ACLDataChannelTest, SendPacketFromMultipleThreads) { int handle1_processed_count = 0; int handle2_processed_count = 0; int total_packet_count = 0; - auto data_cb = [&](const common::ByteBuffer& bytes) { + auto data_cb = [&](const ByteBuffer& bytes) { ZX_DEBUG_ASSERT(bytes.size() >= sizeof(ACLDataHeader)); - common::PacketView<hci::ACLDataHeader> packet( - &bytes, bytes.size() - sizeof(ACLDataHeader)); + PacketView<hci::ACLDataHeader> packet(&bytes, + bytes.size() - sizeof(ACLDataHeader)); ConnectionHandle connection_handle = le16toh(packet.header().handle_and_flags) & 0xFFF; @@ -405,7 +405,7 @@ TEST_F(HCI_ACLDataChannelTest, SendPacketFromMultipleThreads) { if ((total_packet_count % kLEMaxNumPackets) == 0) { // NOTE(armansito): Here we include handles even when the processed-count // is 0. This is OK; ACLDataChannel should ignore those. - auto event_buffer = common::CreateStaticByteBuffer( + auto event_buffer = CreateStaticByteBuffer( 0x13, 0x0D, // Event header 0x03, // Number of handles @@ -463,11 +463,11 @@ TEST_F(HCI_ACLDataChannelTest, SendPacketsFailure) { InitializeACLDataChannel(DataBufferInfo(kMaxMTU, 100), DataBufferInfo()); // Empty packet list. - EXPECT_FALSE(acl_data_channel()->SendPackets( - common::LinkedList<ACLDataPacket>(), Connection::LinkType::kACL)); + EXPECT_FALSE(acl_data_channel()->SendPackets(LinkedList<ACLDataPacket>(), + Connection::LinkType::kACL)); // Packet exceeds MTU - common::LinkedList<ACLDataPacket> packets; + LinkedList<ACLDataPacket> packets; packets.push_back( ACLDataPacket::New(0x0001, ACLPacketBoundaryFlag::kFirstNonFlushable, ACLBroadcastFlag::kPointToPoint, kMaxMTU + 1)); @@ -482,10 +482,10 @@ TEST_F(HCI_ACLDataChannelTest, SendPackets) { bool pass = true; int seq_no = 0; - auto data_cb = [&pass, &seq_no](const common::ByteBuffer& bytes) { + auto data_cb = [&pass, &seq_no](const ByteBuffer& bytes) { ZX_DEBUG_ASSERT(bytes.size() >= sizeof(ACLDataHeader)); - common::PacketView<hci::ACLDataHeader> packet( - &bytes, bytes.size() - sizeof(ACLDataHeader)); + PacketView<hci::ACLDataHeader> packet(&bytes, + bytes.size() - sizeof(ACLDataHeader)); EXPECT_EQ(1u, packet.payload_size()); int cur_no = packet.payload_bytes()[0]; @@ -498,7 +498,7 @@ TEST_F(HCI_ACLDataChannelTest, SendPackets) { }; test_device()->SetDataCallback(data_cb, dispatcher()); - common::LinkedList<ACLDataPacket> packets; + LinkedList<ACLDataPacket> packets; for (int i = 1; i <= kExpectedPacketCount; ++i) { auto packet = ACLDataPacket::New(1, ACLPacketBoundaryFlag::kFirstNonFlushable, @@ -524,16 +524,16 @@ TEST_F(HCI_ACLDataChannelTest, SendPacketsAtomically) { InitializeACLDataChannel(DataBufferInfo(1024, 100), DataBufferInfo()); - std::vector<std::unique_ptr<common::ByteBuffer>> received; - auto data_cb = [&received](const common::ByteBuffer& bytes) { + std::vector<std::unique_ptr<ByteBuffer>> received; + auto data_cb = [&received](const ByteBuffer& bytes) { ZX_DEBUG_ASSERT(bytes.size() >= sizeof(ACLDataHeader)); - received.push_back(std::make_unique<common::DynamicByteBuffer>(bytes)); + received.push_back(std::make_unique<DynamicByteBuffer>(bytes)); }; test_device()->SetDataCallback(data_cb, dispatcher()); // Each thread will send a sequence of kPacketsPerThread packets. The payload // of each packet encodes an integer - common::LinkedList<ACLDataPacket> packets[kThreadCount]; + LinkedList<ACLDataPacket> packets[kThreadCount]; for (size_t i = 0; i < kThreadCount; ++i) { for (size_t j = 1; j <= kPacketsPerThread; ++j) { auto packet = @@ -569,7 +569,7 @@ TEST_F(HCI_ACLDataChannelTest, SendPacketsAtomically) { // Verify that the contents of |received| are in the correct sequence. for (size_t i = 0; i < kExpectedPacketCount; ++i) { - common::PacketView<hci::ACLDataHeader> packet( + PacketView<hci::ACLDataHeader> packet( received[i].get(), received[i]->size() - sizeof(ACLDataHeader)); EXPECT_EQ(1u, packet.payload_size()); EXPECT_EQ((i % kPacketsPerThread) + 1, packet.payload_bytes()[0]); @@ -640,17 +640,17 @@ TEST_F(HCI_ACLDataChannelTest, ReceiveData) { set_data_received_callback(std::move(data_rx_cb)); // Malformed packet: smaller than the ACL header. - auto invalid0 = common::CreateStaticByteBuffer(0x01, 0x00, 0x00); + auto invalid0 = CreateStaticByteBuffer(0x01, 0x00, 0x00); // Malformed packet: the payload size given in the header doesn't match the // actual payload size. - auto invalid1 = common::CreateStaticByteBuffer(0x01, 0x00, 0x02, 0x00, 0x00); + auto invalid1 = CreateStaticByteBuffer(0x01, 0x00, 0x02, 0x00, 0x00); // Valid packet on handle 1. - auto valid0 = common::CreateStaticByteBuffer(0x01, 0x00, 0x01, 0x00, 0x00); + auto valid0 = CreateStaticByteBuffer(0x01, 0x00, 0x01, 0x00, 0x00); // Valid packet on handle 2. - auto valid1 = common::CreateStaticByteBuffer(0x02, 0x00, 0x01, 0x00, 0x00); + auto valid1 = CreateStaticByteBuffer(0x02, 0x00, 0x01, 0x00, 0x00); async::PostTask(dispatcher(), [&, this] { test_device()->SendACLDataChannelPacket(invalid0); diff --git a/src/connectivity/bluetooth/core/bt-host/hci/advertising_report_parser_unittest.cc b/src/connectivity/bluetooth/core/bt-host/hci/advertising_report_parser_unittest.cc index 54d5de8f516e358f7207138165b7d729d9318559..80145194728b2b9085542ffa3d39422ca236de14 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/advertising_report_parser_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/advertising_report_parser_unittest.cc @@ -5,7 +5,6 @@ #include "src/connectivity/bluetooth/core/bt-host/hci/advertising_report_parser.h" #include "gtest/gtest.h" - #include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" #include "src/connectivity/bluetooth/core/bt-host/hci/control_packets.h" @@ -16,7 +15,7 @@ namespace test { namespace { TEST(HCI_AdvertisingReportParserTest, EmptyReport) { - auto bytes = common::CreateStaticByteBuffer(0x3E, 0x02, 0x02, 0x00); + auto bytes = CreateStaticByteBuffer(0x3E, 0x02, 0x02, 0x00); auto event = EventPacket::New(bytes.size() - sizeof(EventHeader)); event->mutable_view()->mutable_data().Write(bytes); @@ -33,7 +32,7 @@ TEST(HCI_AdvertisingReportParserTest, EmptyReport) { TEST(HCI_AdvertisingReportParserTest, SingleReportMalformed) { // clang-format off - auto bytes = common::CreateStaticByteBuffer( + auto bytes = CreateStaticByteBuffer( 0x3E, 0x0B, 0x02, 0x01, // HCI event header and LE Meta Event params 0x03, 0x02, // event_type, address_type 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // address @@ -59,7 +58,7 @@ TEST(HCI_AdvertisingReportParserTest, SingleReportMalformed) { TEST(HCI_AdvertisingReportParserTest, SingleReportNoData) { // clang-format off - auto bytes = common::CreateStaticByteBuffer( + auto bytes = CreateStaticByteBuffer( 0x3E, 0x0C, 0x02, 0x01, // HCI event header and LE Meta Event params 0x03, 0x02, // event_type, address_type 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // address @@ -94,7 +93,7 @@ TEST(HCI_AdvertisingReportParserTest, SingleReportNoData) { TEST(HCI_AdvertisingReportParserTest, ReportsValidInvalid) { // clang-format off - auto bytes = common::CreateStaticByteBuffer( + auto bytes = CreateStaticByteBuffer( 0x3E, 0x16, 0x02, 0x02, // HCI event header and LE Meta Event params 0x03, 0x02, // event_type, address_type 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // address @@ -135,7 +134,7 @@ TEST(HCI_AdvertisingReportParserTest, ReportsValidInvalid) { TEST(HCI_AdvertisingReportParserTest, ReportsAllValid) { // clang-format off - auto bytes = common::CreateStaticByteBuffer( + auto bytes = CreateStaticByteBuffer( 0x3E, 0x28, 0x02, 0x03, // HCI event header and LE Meta Event params 0x03, 0x02, // event_type, address_type 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // address @@ -176,8 +175,7 @@ TEST(HCI_AdvertisingReportParserTest, ReportsAllValid) { EXPECT_EQ(LEAddressType::kRandom, data->address_type); EXPECT_EQ("0C:0B:0A:09:08:07", data->address.ToString()); EXPECT_EQ(3, data->length_data); - EXPECT_TRUE( - common::ContainersEqual(std::array<uint8_t, 3>{{0x01, 0x02, 0x03}}, + EXPECT_TRUE(ContainersEqual(std::array<uint8_t, 3>{{0x01, 0x02, 0x03}}, data->data, data->length_data)); EXPECT_EQ(15, rssi); @@ -188,9 +186,9 @@ TEST(HCI_AdvertisingReportParserTest, ReportsAllValid) { EXPECT_EQ(LEAddressType::kPublic, data->address_type); EXPECT_EQ("12:11:10:0F:0E:0D", data->address.ToString()); EXPECT_EQ(5, data->length_data); - EXPECT_TRUE(common::ContainersEqual( - std::array<uint8_t, 5>{{0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}, data->data, - data->length_data)); + EXPECT_TRUE( + ContainersEqual(std::array<uint8_t, 5>{{0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}, + data->data, data->length_data)); EXPECT_EQ(1, rssi); // No more reports. @@ -203,7 +201,7 @@ TEST(HCI_AdvertisingReportParserTest, ReportsAllValid) { TEST(HCI_AdvertisingReportParserTest, ReportCountLessThanPayloadSize) { // clang-format off - auto bytes = common::CreateStaticByteBuffer( + auto bytes = CreateStaticByteBuffer( 0x3E, 0x28, 0x02, // HCI event header and LE Meta Event param 0x01, // Event count is 1, even though packet contains 3 0x03, 0x02, // event_type, address_type @@ -252,7 +250,7 @@ TEST(HCI_AdvertisingReportParserTest, ReportCountLessThanPayloadSize) { TEST(HCI_AdvertisingReportParserTest, ReportCountGreaterThanPayloadSize) { // clang-format off - auto bytes = common::CreateStaticByteBuffer( + auto bytes = CreateStaticByteBuffer( 0x3E, 0x0C, 0x02, // HCI event header and LE Meta Event param 0x02, // Event count is 2, even though packet contains 1 0x03, 0x02, // event_type, address_type diff --git a/src/connectivity/bluetooth/core/bt-host/hci/bredr_connection_request.cc b/src/connectivity/bluetooth/core/bt-host/hci/bredr_connection_request.cc index 01f1cbde6e619ab9582cf371fafda981cf25537b..97db291b6e4f6b28a156c86bd8a9c8a51a97fd39 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/bredr_connection_request.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/bredr_connection_request.cc @@ -15,10 +15,6 @@ namespace bt { namespace hci { -using common::DeviceAddress; -using common::HostError; -using common::PeerId; - std::unique_ptr<CommandPacket> CreateConnectionPacket( DeviceAddress address, std::optional<PageScanRepetitionMode> page_scan_repetition_mode, diff --git a/src/connectivity/bluetooth/core/bt-host/hci/bredr_connection_request.h b/src/connectivity/bluetooth/core/bt-host/hci/bredr_connection_request.h index ada55c5d8303e16c377669350290f933f6666944..9d5b3cb14d2bfe4c53a3da53b5811addf0c4c21e 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/bredr_connection_request.h +++ b/src/connectivity/bluetooth/core/bt-host/hci/bredr_connection_request.h @@ -48,10 +48,9 @@ constexpr PacketTypeType kEnableAllPacketTypes = // BrEdrConnectionManager class BrEdrConnectionRequest final { public: - using OnCompleteDelegate = fit::function<void(Status, common::PeerId)>; + using OnCompleteDelegate = fit::function<void(Status, PeerId)>; - BrEdrConnectionRequest(common::PeerId id, common::DeviceAddress addr, - fit::closure timeout_cb) + BrEdrConnectionRequest(PeerId id, DeviceAddress addr, fit::closure timeout_cb) : state_(RequestState::kPending), peer_id_(id), peer_address_(addr), @@ -74,8 +73,8 @@ class BrEdrConnectionRequest final { std::optional<PageScanRepetitionMode> page_scan_repetition_mode, zx::duration timeout, OnCompleteDelegate on_command_fail); - common::PeerId peer_id() const { return peer_id_; } - common::DeviceAddress peer_address() const { return peer_address_; } + PeerId peer_id() const { return peer_id_; } + DeviceAddress peer_address() const { return peer_address_; } // Complete the request, either successfully or not, and return the status // of the Request - In the case of Timeout or Cancellation, this will be @@ -93,8 +92,8 @@ class BrEdrConnectionRequest final { private: RequestState state_; - common::PeerId peer_id_; - common::DeviceAddress peer_address_; + PeerId peer_id_; + DeviceAddress peer_address_; async::TaskClosure timeout_task_; diff --git a/src/connectivity/bluetooth/core/bt-host/hci/command_channel.cc b/src/connectivity/bluetooth/core/bt-host/hci/command_channel.cc index 476c907af27b80183b6f570a572e344dc551741f..9b4845aaf5283ff84634b535cf0e4d95062ed7cf 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/command_channel.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/command_channel.cc @@ -5,19 +5,18 @@ #include "command_channel.h" #include <endian.h> - #include <lib/async/default.h> #include <zircon/assert.h> #include <zircon/status.h> -#include "src/lib/fxl/strings/string_printf.h" -#include "src/lib/fxl/time/time_delta.h" +#include "slab_allocators.h" +#include "transport.h" + #include "src/connectivity/bluetooth/core/bt-host/common/log.h" #include "src/connectivity/bluetooth/core/bt-host/common/run_or_post.h" #include "src/connectivity/bluetooth/core/bt-host/common/run_task_sync.h" - -#include "slab_allocators.h" -#include "transport.h" +#include "src/lib/fxl/strings/string_printf.h" +#include "src/lib/fxl/time/time_delta.h" namespace bt { namespace hci { @@ -139,7 +138,7 @@ void CommandChannel::Initialize() { }; io_dispatcher_ = transport_->io_dispatcher(); - common::RunTaskSync(setup_handler_task, io_dispatcher_); + RunTaskSync(setup_handler_task, io_dispatcher_); if (channel_wait_.object() == ZX_HANDLE_INVALID) return; @@ -156,7 +155,7 @@ void CommandChannel::ShutDown() { bt_log(INFO, "hci", "shutting down"); - common::RunTaskSync([this] { ShutDownInternal(); }, io_dispatcher_); + RunTaskSync([this] { ShutDownInternal(); }, io_dispatcher_); io_dispatcher_ = nullptr; } @@ -586,16 +585,15 @@ void CommandChannel::NotifyEventHandler(std::unique_ptr<EventPacket> event) { auto it = pending_callbacks.begin(); for (; it != pending_callbacks.end() - 1; ++it) { auto event_copy = EventPacket::New(event->view().payload_size()); - common::MutableBufferView buf = event_copy->mutable_view()->mutable_data(); + MutableBufferView buf = event_copy->mutable_view()->mutable_data(); event->view().data().Copy(&buf); - common::RunOrPost( + RunOrPost( [ev = std::move(event_copy), cb = std::move(it->first)]() { cb(*ev); }, it->second); } // Don't copy for the last callback. - common::RunOrPost( - [ev = std::move(event), cb = std::move(it->first)]() { cb(*ev); }, - it->second); + RunOrPost([ev = std::move(event), cb = std::move(it->first)]() { cb(*ev); }, + it->second); } void CommandChannel::OnChannelReady(async_dispatcher_t* dispatcher, diff --git a/src/connectivity/bluetooth/core/bt-host/hci/command_channel_unittest.cc b/src/connectivity/bluetooth/core/bt-host/hci/command_channel_unittest.cc index 502b859ea1dd9706ea75ce8226e778a04705f99e..cc5235fb45cce98d0165f87a4db468b26fbf9c61 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/command_channel_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/command_channel_unittest.cc @@ -17,8 +17,8 @@ namespace bt { namespace hci { namespace { -using bt::common::LowerBits; -using bt::common::UpperBits; +using bt::LowerBits; +using bt::UpperBits; using bt::testing::CommandTransaction; using TestingBase = @@ -48,12 +48,12 @@ TEST_F(HCI_CommandChannelTest, SingleRequestResponse) { // Set up expectations: // clang-format off // HCI_Reset - auto req = common::CreateStaticByteBuffer( + auto req = CreateStaticByteBuffer( LowerBits(kReset), UpperBits(kReset), // HCI_Reset opcode 0x00 // parameter_total_size ); // HCI_CommandComplete - auto rsp = common::CreateStaticByteBuffer( + auto rsp = CreateStaticByteBuffer( kCommandCompleteEventCode, 0x04, // parameter_total_size (4 byte payload) 0x01, // num_hci_command_packets (1 can be sent) @@ -101,7 +101,7 @@ TEST_F(HCI_CommandChannelTest, SingleAsynchronousRequest) { // Set up expectations: // clang-format off // HCI_Inquiry (general, unlimited, 1s) - auto req = common::CreateStaticByteBuffer( + auto req = CreateStaticByteBuffer( LowerBits(kInquiry), UpperBits(kInquiry), // HCI_Inquiry opcode 0x05, // parameter_total_size 0x33, 0x8B, 0x9E, // General Inquiry @@ -109,14 +109,14 @@ TEST_F(HCI_CommandChannelTest, SingleAsynchronousRequest) { 0x00 // Unlimited responses ); // HCI_CommandStatus - auto rsp0 = common::CreateStaticByteBuffer( + auto rsp0 = CreateStaticByteBuffer( kCommandStatusEventCode, 0x04, // parameter_total_size (4 byte payload) StatusCode::kSuccess, 0x01, // status, num_hci_command_packets (1 can be sent) LowerBits(kInquiry), UpperBits(kInquiry) // HCI_Inquiry opcode ); // HCI_InquiryComplete - auto rsp1 = common::CreateStaticByteBuffer( + auto rsp1 = CreateStaticByteBuffer( kInquiryCompleteEventCode, 0x01, // parameter_total_size (1 byte payload) StatusCode::kSuccess); @@ -159,12 +159,12 @@ TEST_F(HCI_CommandChannelTest, SingleRequestWithStatusResponse) { // Set up expectations // clang-format off // HCI_Reset for the sake of testing - auto req = common::CreateStaticByteBuffer( + auto req = CreateStaticByteBuffer( LowerBits(kReset), UpperBits(kReset), // HCI_Reset opcode 0x00 // parameter_total_size ); // HCI_CommandStatus - auto rsp = common::CreateStaticByteBuffer( + auto rsp = CreateStaticByteBuffer( kCommandStatusEventCode, 0x04, // parameter_total_size (4 byte payload) StatusCode::kSuccess, 0x01, // status, num_hci_command_packets (1 can be sent) @@ -204,27 +204,27 @@ TEST_F(HCI_CommandChannelTest, OneSentUntilStatus) { // Set up expectations // clang-format off // HCI_Reset for the sake of testing - auto req1 = common::CreateStaticByteBuffer( + auto req1 = CreateStaticByteBuffer( LowerBits(kReset), UpperBits(kReset), // HCI_Reset opcode 0x00 // parameter_total_size ); - auto rsp1 = common::CreateStaticByteBuffer( + auto rsp1 = CreateStaticByteBuffer( kCommandCompleteEventCode, 0x03, // parameter_total_size (4 byte payload) 0x00, // num_hci_command_packets (None can be sent) LowerBits(kReset), UpperBits(kReset) // HCI_Reset opcode ); - auto req2 = common::CreateStaticByteBuffer( + auto req2 = CreateStaticByteBuffer( LowerBits(kInquiryCancel), UpperBits(kInquiryCancel), // HCI_InquiryCancel opcode 0x00 // parameter_total_size ); - auto rsp2 = common::CreateStaticByteBuffer( + auto rsp2 = CreateStaticByteBuffer( kCommandCompleteEventCode, 0x03, // parameter_total_size (4 byte payload) 0x01, // num_hci_command_packets (1 can be sent) LowerBits(kInquiryCancel), UpperBits(kInquiryCancel) // HCI_InquiryCancel opcode ); - auto rsp_commandsavail = common::CreateStaticByteBuffer( + auto rsp_commandsavail = CreateStaticByteBuffer( kCommandStatusEventCode, 0x04, // parameter_total_size (3 byte payload) StatusCode::kSuccess, 0x01, // status, num_hci_command_packets (1 can be sent) @@ -283,27 +283,27 @@ TEST_F(HCI_CommandChannelTest, QueuedCommands) { // Set up expectations // clang-format off // HCI_Reset for the sake of testing - auto req_reset = common::CreateStaticByteBuffer( + auto req_reset = CreateStaticByteBuffer( LowerBits(kReset), UpperBits(kReset), // HCI_Reset opcode 0x00 // parameter_total_size ); - auto rsp_reset = common::CreateStaticByteBuffer( + auto rsp_reset = CreateStaticByteBuffer( kCommandCompleteEventCode, 0x03, // parameter_total_size (4 byte payload) 0xFF, // num_hci_command_packets (255 can be sent) LowerBits(kReset), UpperBits(kReset) // HCI_Reset opcode ); - auto req_inqcancel = common::CreateStaticByteBuffer( + auto req_inqcancel = CreateStaticByteBuffer( LowerBits(kInquiryCancel), UpperBits(kInquiryCancel), // HCI_InquiryCancel opcode 0x00 // parameter_total_size ); - auto rsp_inqcancel = common::CreateStaticByteBuffer( + auto rsp_inqcancel = CreateStaticByteBuffer( kCommandCompleteEventCode, 0x03, // parameter_total_size (4 byte payload) 0xFF, // num_hci_command_packets (255 can be sent) LowerBits(kInquiryCancel), UpperBits(kInquiryCancel) // HCI_Reset opcode ); - auto rsp_commandsavail = common::CreateStaticByteBuffer( + auto rsp_commandsavail = CreateStaticByteBuffer( kCommandStatusEventCode, 0x04, // parameter_total_size (3 byte payload) StatusCode::kSuccess, 0xFA, // status, num_hci_command_packets (250 can be sent) @@ -382,27 +382,27 @@ TEST_F(HCI_CommandChannelTest, AsynchronousCommands) { // Set up expectations // clang-format off // Using HCI_Reset for testing. - auto req_reset = common::CreateStaticByteBuffer( + auto req_reset = CreateStaticByteBuffer( LowerBits(kReset), UpperBits(kReset), // HCI_Reset opcode 0x00 // parameter_total_size ); - auto rsp_resetstatus = common::CreateStaticByteBuffer( + auto rsp_resetstatus = CreateStaticByteBuffer( kCommandStatusEventCode, 0x04, // parameter_total_size (4 byte payload) StatusCode::kSuccess, 0xFA, // status, num_hci_command_packets (250 can be sent) LowerBits(kReset), UpperBits(kReset) // HCI_Reset opcode ); - auto req_inqcancel = common::CreateStaticByteBuffer( + auto req_inqcancel = CreateStaticByteBuffer( LowerBits(kInquiryCancel), UpperBits(kInquiryCancel), // HCI_InquiryCancel opcode 0x00 // parameter_total_size ); - auto rsp_inqstatus = common::CreateStaticByteBuffer( + auto rsp_inqstatus = CreateStaticByteBuffer( kCommandStatusEventCode, 0x04, // parameter_total_size (4 byte payload) StatusCode::kSuccess, 0xFA, // status, num_hci_command_packets (250 can be sent) LowerBits(kInquiryCancel), UpperBits(kInquiryCancel) // HCI_Reset opcode ); - auto rsp_bogocomplete = common::CreateStaticByteBuffer( + auto rsp_bogocomplete = CreateStaticByteBuffer( kTestEventCode0, 0x00 // parameter_total_size (no payload) ); @@ -481,27 +481,27 @@ TEST_F(HCI_CommandChannelTest, AsyncQueueWhenBlocked) { // Set up expectations // clang-format off // Using HCI_Reset for testing. - auto req_reset = common::CreateStaticByteBuffer( + auto req_reset = CreateStaticByteBuffer( LowerBits(kReset), UpperBits(kReset), // HCI_Reset opcode 0x00 // parameter_total_size ); - auto rsp_resetstatus = common::CreateStaticByteBuffer( + auto rsp_resetstatus = CreateStaticByteBuffer( kCommandStatusEventCode, 0x04, // parameter_total_size (4 byte payload) StatusCode::kSuccess, 0xFA, // status, num_hci_command_packets (250 can be sent) LowerBits(kReset), UpperBits(kReset) // HCI_Reset opcode ); - auto rsp_bogocomplete = common::CreateStaticByteBuffer( + auto rsp_bogocomplete = CreateStaticByteBuffer( kTestEventCode0, 0x00 // parameter_total_size (no payload) ); - auto rsp_nocommandsavail = common::CreateStaticByteBuffer( + auto rsp_nocommandsavail = CreateStaticByteBuffer( kCommandStatusEventCode, 0x04, // parameter_total_size (3 byte payload) StatusCode::kSuccess, 0x00, // status, num_hci_command_packets (none can be sent) 0x00, 0x00 // No associated opcode. ); - auto rsp_commandsavail = common::CreateStaticByteBuffer( + auto rsp_commandsavail = CreateStaticByteBuffer( kCommandStatusEventCode, 0x04, // parameter_total_size (3 byte payload) StatusCode::kSuccess, 0x01, // status, num_hci_command_packets (one can be sent) @@ -572,12 +572,12 @@ TEST_F(HCI_CommandChannelTest, AsyncQueueWhenBlocked) { TEST_F(HCI_CommandChannelTest, EventHandlerBasic) { constexpr EventCode kTestEventCode0 = 0xFE; constexpr EventCode kTestEventCode1 = 0xFF; - auto cmd_status = common::CreateStaticByteBuffer( - kCommandStatusEventCode, 0x04, 0x00, 0x01, 0x00, 0x00); - auto cmd_complete = common::CreateStaticByteBuffer(kCommandCompleteEventCode, - 0x03, 0x01, 0x00, 0x00); - auto event0 = common::CreateStaticByteBuffer(kTestEventCode0, 0x00); - auto event1 = common::CreateStaticByteBuffer(kTestEventCode1, 0x00); + auto cmd_status = CreateStaticByteBuffer(kCommandStatusEventCode, 0x04, 0x00, + 0x01, 0x00, 0x00); + auto cmd_complete = + CreateStaticByteBuffer(kCommandCompleteEventCode, 0x03, 0x01, 0x00, 0x00); + auto event0 = CreateStaticByteBuffer(kTestEventCode0, 0x00); + auto event1 = CreateStaticByteBuffer(kTestEventCode1, 0x00); int event_count0 = 0; auto event_cb0 = [&event_count0, kTestEventCode0](const EventPacket& event) { @@ -685,12 +685,12 @@ TEST_F(HCI_CommandChannelTest, EventHandlerBasic) { TEST_F(HCI_CommandChannelTest, EventHandlerEventWhileTransactionPending) { // clang-format off // HCI_Reset - auto req = common::CreateStaticByteBuffer( + auto req = CreateStaticByteBuffer( LowerBits(kReset), UpperBits(kReset), // HCI_Reset opcode 0x00 // parameter_total_size ); - auto req_complete = common::CreateStaticByteBuffer( + auto req_complete = CreateStaticByteBuffer( kCommandCompleteEventCode, 0x03, // parameter_total_size (3 byte payload) 0x01, // num_hci_command_packets (1 can be sent) @@ -699,7 +699,7 @@ TEST_F(HCI_CommandChannelTest, EventHandlerEventWhileTransactionPending) { // clang-format on constexpr EventCode kTestEventCode = 0xFF; - auto event = common::CreateStaticByteBuffer(kTestEventCode, 0x01, 0x00); + auto event = CreateStaticByteBuffer(kTestEventCode, 0x01, 0x00); // We will send the HCI_Reset command with kTestEventCode as the completion // event. The event handler we register below should only get invoked once and @@ -736,10 +736,10 @@ TEST_F(HCI_CommandChannelTest, EventHandlerEventWhileTransactionPending) { TEST_F(HCI_CommandChannelTest, LEMetaEventHandler) { constexpr EventCode kTestSubeventCode0 = 0xFE; constexpr EventCode kTestSubeventCode1 = 0xFF; - auto le_meta_event_bytes0 = common::CreateStaticByteBuffer( - hci::kLEMetaEventCode, 0x01, kTestSubeventCode0); - auto le_meta_event_bytes1 = common::CreateStaticByteBuffer( - hci::kLEMetaEventCode, 0x01, kTestSubeventCode1); + auto le_meta_event_bytes0 = + CreateStaticByteBuffer(hci::kLEMetaEventCode, 0x01, kTestSubeventCode0); + auto le_meta_event_bytes1 = + CreateStaticByteBuffer(hci::kLEMetaEventCode, 0x01, kTestSubeventCode1); int event_count0 = 0; auto event_cb0 = [&event_count0, kTestSubeventCode0, @@ -829,11 +829,11 @@ TEST_F(HCI_CommandChannelTest, // Set up expectations for the asynchronous command and its corresponding // command status event. // clang-format off - auto cmd = common::CreateStaticByteBuffer( + auto cmd = CreateStaticByteBuffer( LowerBits(kInquiry), UpperBits(kInquiry), // HCI_Inquiry opcode 0x00 // parameter_total_size ); - auto cmd_status = common::CreateStaticByteBuffer( + auto cmd_status = CreateStaticByteBuffer( kCommandStatusEventCode, 0x04, // parameter_total_size (4 byte payload) StatusCode::kSuccess, 0x01, // status, num_hci_command_packets (1 can be sent) @@ -874,11 +874,11 @@ TEST_F(HCI_CommandChannelTest, std::move(async_cmd_cb), kTestEventCode); // clang-format off - auto event_bytes = common::CreateStaticByteBuffer( + auto event_bytes = CreateStaticByteBuffer( kTestEventCode, 0x01, // parameter_total_size StatusCode::kSuccess); - auto le_event_bytes = common::CreateStaticByteBuffer( + auto le_event_bytes = CreateStaticByteBuffer( kLEMetaEventCode, 0x01, // parameter_total_size kTestEventCode); @@ -925,7 +925,7 @@ TEST_F(HCI_CommandChannelTest, TransportClosedCallback) { TEST_F(HCI_CommandChannelTest, CommandTimeout) { constexpr zx::duration kCommandTimeout = zx::sec(12); - auto req_reset = common::CreateStaticByteBuffer( + auto req_reset = CreateStaticByteBuffer( LowerBits(kReset), UpperBits(kReset), // HCI_Reset opcode 0x00 // parameter_total_size ); @@ -976,27 +976,27 @@ TEST_F(HCI_CommandChannelTest, AsynchronousCommandChaining) { // Set up expectations // clang-format off // Using HCI_Reset for testing. - auto req_reset = common::CreateStaticByteBuffer( + auto req_reset = CreateStaticByteBuffer( LowerBits(kReset), UpperBits(kReset), // HCI_Reset opcode 0x00 // parameter_total_size (no payload) ); - auto rsp_resetstatus = common::CreateStaticByteBuffer( + auto rsp_resetstatus = CreateStaticByteBuffer( kCommandStatusEventCode, 0x04, // parameter_total_size (4 byte payload) StatusCode::kSuccess, 0xFA, // status, num_hci_command_packets (250) LowerBits(kReset), UpperBits(kReset) // HCI_Reset opcode ); - auto req_inqcancel = common::CreateStaticByteBuffer( + auto req_inqcancel = CreateStaticByteBuffer( LowerBits(kInquiryCancel), UpperBits(kInquiryCancel), // HCI_InquiryCancel 0x00 // parameter_total_size (no payload) ); - auto rsp_inqstatus = common::CreateStaticByteBuffer( + auto rsp_inqstatus = CreateStaticByteBuffer( kCommandStatusEventCode, 0x04, // parameter_total_size (4 byte payload) StatusCode::kSuccess, 0xFA, // status, num_hci_command_packets (250) LowerBits(kInquiryCancel), UpperBits(kInquiryCancel) // HCI_InquiryCanacel ); - auto rsp_bogocomplete = common::CreateStaticByteBuffer( + auto rsp_bogocomplete = CreateStaticByteBuffer( kTestEventCode0, 0x00 // parameter_total_size (no payload) ); @@ -1080,39 +1080,39 @@ TEST_F(HCI_CommandChannelTest, ExclusiveCommands) { // - kExclusiveTwo finishes with kExclTwoCompleteEvent // - kNonExclusive can run whenever it wants. // - For testing, we omit the payloads of all commands. - auto excl_one_cmd = common::CreateStaticByteBuffer( + auto excl_one_cmd = CreateStaticByteBuffer( LowerBits(kExclusiveOne), UpperBits(kExclusiveOne), 0x00 // (no payload) ); - auto rsp_excl_one_status = common::CreateStaticByteBuffer( + auto rsp_excl_one_status = CreateStaticByteBuffer( kCommandStatusEventCode, 0x04, // parameter_total_size (4 byte payload) StatusCode::kSuccess, 0xFA, // status, num_hci_command_packets (250) LowerBits(kExclusiveOne), UpperBits(kExclusiveOne) // HCI opcode ); - auto rsp_one_complete = common::CreateStaticByteBuffer( + auto rsp_one_complete = CreateStaticByteBuffer( kExclOneCompleteEvent, 0x00 // parameter_total_size (no payload) ); - auto excl_two_cmd = common::CreateStaticByteBuffer( + auto excl_two_cmd = CreateStaticByteBuffer( LowerBits(kExclusiveTwo), UpperBits(kExclusiveTwo), 0x00 // (no payload) ); - auto rsp_excl_two_status = common::CreateStaticByteBuffer( + auto rsp_excl_two_status = CreateStaticByteBuffer( kCommandStatusEventCode, 0x04, // parameter_total_size (4 byte payload) StatusCode::kSuccess, 0xFA, // status, num_hci_command_packets (250) LowerBits(kExclusiveTwo), UpperBits(kExclusiveTwo) // HCI opcode ); - auto rsp_two_complete = common::CreateStaticByteBuffer( + auto rsp_two_complete = CreateStaticByteBuffer( kExclTwoCompleteEvent, 0x00 // parameter_total_size (no payload) ); - auto nonexclusive_cmd = common::CreateStaticByteBuffer( + auto nonexclusive_cmd = CreateStaticByteBuffer( LowerBits(kNonExclusive), UpperBits(kNonExclusive), // HCI opcode 0x00 // parameter_total_size (no payload) ); - auto nonexclusive_complete = common::CreateStaticByteBuffer( + auto nonexclusive_complete = CreateStaticByteBuffer( kCommandCompleteEventCode, 0x04, // parameter_total_size (4 byte payload) 0xFA, // num_hci_command_packets (250) diff --git a/src/connectivity/bluetooth/core/bt-host/hci/connection.cc b/src/connectivity/bluetooth/core/bt-host/hci/connection.cc index 8524d89ca738c38a6e2c826bbdf061af6460fa15..408f9cf07c8e7eff98f32c61f8a537b21460d19c 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/connection.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/connection.cc @@ -19,9 +19,8 @@ namespace hci { class ConnectionImpl final : public Connection { public: ConnectionImpl(ConnectionHandle handle, LinkType ll_type, Role role, - const common::DeviceAddress& local_address, - const common::DeviceAddress& peer_address, - fxl::RefPtr<Transport> hci); + const DeviceAddress& local_address, + const DeviceAddress& peer_address, fxl::RefPtr<Transport> hci); ~ConnectionImpl() override; // Connection overrides: @@ -101,12 +100,11 @@ CommandChannel::EventCallback BindEventHandler( // static std::unique_ptr<Connection> Connection::CreateLE( - ConnectionHandle handle, Role role, - const common::DeviceAddress& local_address, - const common::DeviceAddress& peer_address, - const LEConnectionParameters& params, fxl::RefPtr<Transport> hci) { - ZX_DEBUG_ASSERT(local_address.type() != common::DeviceAddress::Type::kBREDR); - ZX_DEBUG_ASSERT(peer_address.type() != common::DeviceAddress::Type::kBREDR); + ConnectionHandle handle, Role role, const DeviceAddress& local_address, + const DeviceAddress& peer_address, const LEConnectionParameters& params, + fxl::RefPtr<Transport> hci) { + ZX_DEBUG_ASSERT(local_address.type() != DeviceAddress::Type::kBREDR); + ZX_DEBUG_ASSERT(peer_address.type() != DeviceAddress::Type::kBREDR); auto conn = std::make_unique<ConnectionImpl>( handle, LinkType::kLE, role, local_address, peer_address, hci); conn->set_low_energy_parameters(params); @@ -115,19 +113,18 @@ std::unique_ptr<Connection> Connection::CreateLE( // static std::unique_ptr<Connection> Connection::CreateACL( - ConnectionHandle handle, Role role, - const common::DeviceAddress& local_address, - const common::DeviceAddress& peer_address, fxl::RefPtr<Transport> hci) { - ZX_DEBUG_ASSERT(local_address.type() == common::DeviceAddress::Type::kBREDR); - ZX_DEBUG_ASSERT(peer_address.type() == common::DeviceAddress::Type::kBREDR); + ConnectionHandle handle, Role role, const DeviceAddress& local_address, + const DeviceAddress& peer_address, fxl::RefPtr<Transport> hci) { + ZX_DEBUG_ASSERT(local_address.type() == DeviceAddress::Type::kBREDR); + ZX_DEBUG_ASSERT(peer_address.type() == DeviceAddress::Type::kBREDR); auto conn = std::make_unique<ConnectionImpl>( handle, LinkType::kACL, role, local_address, peer_address, hci); return conn; } Connection::Connection(ConnectionHandle handle, LinkType ll_type, Role role, - const common::DeviceAddress& local_address, - const common::DeviceAddress& peer_address) + const DeviceAddress& local_address, + const DeviceAddress& peer_address) : ll_type_(ll_type), handle_(handle), role_(role), @@ -151,9 +148,8 @@ std::string Connection::ToString() const { // ====== ConnectionImpl member methods ====== ConnectionImpl::ConnectionImpl(ConnectionHandle handle, LinkType ll_type, - Role role, - const common::DeviceAddress& local_address, - const common::DeviceAddress& peer_address, + Role role, const DeviceAddress& local_address, + const DeviceAddress& peer_address, fxl::RefPtr<Transport> hci) : Connection(handle, ll_type, role, local_address, peer_address), hci_(hci), @@ -354,7 +350,7 @@ void ConnectionImpl::ValidateAclEncryptionKeySize( if (key_size < hci::kMinEncryptionKeySize) { bt_log(WARN, "hci", "%#.4x: encryption key size %hhu insufficient", self->handle(), key_size); - status = Status(common::HostError::kInsufficientSecurity); + status = Status(HostError::kInsufficientSecurity); } } valid_cb(status); diff --git a/src/connectivity/bluetooth/core/bt-host/hci/connection.h b/src/connectivity/bluetooth/core/bt-host/hci/connection.h index 5a3229a4444500d3a37756419da8a8bac263add9..24d0f1d685a20467ad421838f3f154625ab7c365 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/connection.h +++ b/src/connectivity/bluetooth/core/bt-host/hci/connection.h @@ -71,16 +71,14 @@ class Connection { // Initializes this as a LE connection. static std::unique_ptr<Connection> CreateLE( - ConnectionHandle handle, Role role, - const common::DeviceAddress& local_address, - const common::DeviceAddress& peer_address, - const LEConnectionParameters& params, fxl::RefPtr<Transport> hci); + ConnectionHandle handle, Role role, const DeviceAddress& local_address, + const DeviceAddress& peer_address, const LEConnectionParameters& params, + fxl::RefPtr<Transport> hci); // Initializes this as a BR/EDR ACL connection. static std::unique_ptr<Connection> CreateACL( - ConnectionHandle handle, Role role, - const common::DeviceAddress& local_address, - const common::DeviceAddress& peer_address, fxl::RefPtr<Transport> hci); + ConnectionHandle handle, Role role, const DeviceAddress& local_address, + const DeviceAddress& peer_address, fxl::RefPtr<Transport> hci); // The destructor closes this connection. virtual ~Connection() = default; @@ -117,10 +115,10 @@ class Connection { } // The local device address used while establishing the connection. - const common::DeviceAddress& local_address() const { return local_address_; } + const DeviceAddress& local_address() const { return local_address_; } // The peer address used while establishing the connection. - const common::DeviceAddress& peer_address() const { return peer_address_; } + const DeviceAddress& peer_address() const { return peer_address_; } // Returns true if this connection is currently open. bool is_open() const { return is_open_; } @@ -158,8 +156,8 @@ class Connection { protected: Connection(ConnectionHandle handle, LinkType ll_type, Role role, - const common::DeviceAddress& local_address, - const common::DeviceAddress& peer_address); + const DeviceAddress& local_address, + const DeviceAddress& peer_address); const EncryptionChangeCallback& encryption_change_callback() const { return encryption_change_callback_; @@ -172,8 +170,8 @@ class Connection { bool is_open_; // Addresses used while creating the link. - common::DeviceAddress local_address_; - common::DeviceAddress peer_address_; + DeviceAddress local_address_; + DeviceAddress peer_address_; // Connection parameters for a LE link. Not nullptr if the link type is LE. LEConnectionParameters le_params_; diff --git a/src/connectivity/bluetooth/core/bt-host/hci/connection_unittest.cc b/src/connectivity/bluetooth/core/bt-host/hci/connection_unittest.cc index c023472d9a3f85d7d62531ea9a6b571fe9b69dbd..14a6322b54483e00f48abbc3e4ab5f2a5412efa4 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/connection_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/connection_unittest.cc @@ -12,11 +12,6 @@ namespace bt { namespace hci { namespace { -using common::CreateStaticByteBuffer; -using common::DeviceAddress; -using common::HostError; -using common::UInt128; - constexpr ConnectionHandle kTestHandle = 0x0001; const LEConnectionParameters kTestParams(1, 1, 1); const DeviceAddress kLEAddress1(DeviceAddress::Type::kLEPublic, diff --git a/src/connectivity/bluetooth/core/bt-host/hci/control_packets.cc b/src/connectivity/bluetooth/core/bt-host/hci/control_packets.cc index e80451ad6a1baa228ffb0314f25a82a176529e61..af79cbb69919d6ad3c194a339051dfc71b751feb 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/control_packets.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/control_packets.cc @@ -13,11 +13,9 @@ namespace hci { namespace slab_allocators { // Slab-allocator traits for command packets. -using LargeCommandTraits = PacketTraits<CommandHeader, - kLargeControlPacketSize, +using LargeCommandTraits = PacketTraits<CommandHeader, kLargeControlPacketSize, kNumLargeControlPackets>; -using SmallCommandTraits = PacketTraits<CommandHeader, - kSmallControlPacketSize, +using SmallCommandTraits = PacketTraits<CommandHeader, kSmallControlPacketSize, kNumSmallControlPackets>; // Slab-allocator traits for event packets. Since event packets are only @@ -67,8 +65,7 @@ bool StatusCodeFromEvent(const EventPacket& event, hci::StatusCode* out_code) { // Specialization for the CommandComplete event. template <> bool StatusCodeFromEvent<CommandCompleteEventParams>( - const EventPacket& event, - hci::StatusCode* out_code) { + const EventPacket& event, hci::StatusCode* out_code) { ZX_DEBUG_ASSERT(out_code); const auto* params = event.return_params<SimpleReturnParams>(); @@ -134,7 +131,7 @@ bool EventPacket::ToStatusCode(StatusCode* out_code) const { Status EventPacket::ToStatus() const { StatusCode code; if (!ToStatusCode(&code)) { - return Status(common::HostError::kPacketMalformed); + return Status(HostError::kPacketMalformed); } return Status(code); } diff --git a/src/connectivity/bluetooth/core/bt-host/hci/fake_connection.cc b/src/connectivity/bluetooth/core/bt-host/hci/fake_connection.cc index 8b9e8826281f8ac5dd04d58ee68823056cec0dfa..93c5374ad85cd300e0cbaa52ff0037fa582b18b6 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/fake_connection.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/fake_connection.cc @@ -9,9 +9,8 @@ namespace hci { namespace testing { FakeConnection::FakeConnection(ConnectionHandle handle, LinkType ll_type, - Role role, - const common::DeviceAddress& local_address, - const common::DeviceAddress& peer_address) + Role role, const DeviceAddress& local_address, + const DeviceAddress& peer_address) : Connection(handle, ll_type, role, local_address, peer_address), weak_ptr_factory_(this) {} diff --git a/src/connectivity/bluetooth/core/bt-host/hci/fake_connection.h b/src/connectivity/bluetooth/core/bt-host/hci/fake_connection.h index 22ab04e0ccb56ed3214bff3923b6da5af3342091..2ebd70d2b38a4766e734cb4c5937b7f717011473 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/fake_connection.h +++ b/src/connectivity/bluetooth/core/bt-host/hci/fake_connection.h @@ -14,8 +14,8 @@ namespace testing { class FakeConnection final : public Connection { public: FakeConnection(ConnectionHandle handle, LinkType ll_type, Role role, - const common::DeviceAddress& local_address, - const common::DeviceAddress& peer_address); + const DeviceAddress& local_address, + const DeviceAddress& peer_address); // Triggers the encryption change callback. void TriggerEncryptionChangeCallback(Status status, bool enabled); diff --git a/src/connectivity/bluetooth/core/bt-host/hci/fake_local_address_delegate.h b/src/connectivity/bluetooth/core/bt-host/hci/fake_local_address_delegate.h index 9547948665c34cd15d3cc92f53687385fd335434..0d628056c4e8a1e9b4bfbf65d7c168b51b478d7f 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/fake_local_address_delegate.h +++ b/src/connectivity/bluetooth/core/bt-host/hci/fake_local_address_delegate.h @@ -16,21 +16,19 @@ class FakeLocalAddressDelegate : public LocalAddressDelegate { FakeLocalAddressDelegate() = default; ~FakeLocalAddressDelegate() override = default; - std::optional<common::UInt128> irk() const override { return std::nullopt; } - common::DeviceAddress identity_address() const override { return {}; } + std::optional<UInt128> irk() const override { return std::nullopt; } + DeviceAddress identity_address() const override { return {}; } void EnsureLocalAddress(AddressCallback callback) override; // If set to true EnsureLocalAddress runs its callback asynchronously. void set_async(bool value) { async_ = value; } - void set_local_address(const common::DeviceAddress& value) { - local_address_ = value; - } + void set_local_address(const DeviceAddress& value) { local_address_ = value; } private: bool async_ = false; - common::DeviceAddress local_address_ = common::DeviceAddress( - common::DeviceAddress::Type::kLEPublic, "00:00:00:00:00:00"); + DeviceAddress local_address_ = + DeviceAddress(DeviceAddress::Type::kLEPublic, "00:00:00:00:00:00"); }; } // namespace hci diff --git a/src/connectivity/bluetooth/core/bt-host/hci/hci.h b/src/connectivity/bluetooth/core/bt-host/hci/hci.h index 2e24528a9ceb0cce2d8db23ec0b43c0ccfd20946..813eb6451d4e9c3eb0df18e221359e89c62bc8d5 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/hci.h +++ b/src/connectivity/bluetooth/core/bt-host/hci/hci.h @@ -23,8 +23,8 @@ // the Bluetooth Core Specification version 5.0 // // NOTE: Avoid casting raw buffer pointers to the packet payload structure types -// below; use as template parameter to common::PacketView::payload() and -// common::MutableBufferView::mutable_payload() instead. Take extra care when +// below; use as template parameter to PacketView::payload() and +// MutableBufferView::mutable_payload() instead. Take extra care when // accessing flexible array members. namespace bt { @@ -150,7 +150,7 @@ constexpr OpCode kCreateConnection = LinkControlOpCode(0x0005); struct CreateConnectionCommandParams { // BD_ADDR of the device to be connected - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; // Mask of allowable packet types. See PacketTypeBits in hci_constants.h for // values. @@ -205,7 +205,7 @@ constexpr OpCode kCreateConnectionCancel = LinkControlOpCode(0x0008); struct CreateConnectionCancelCommandParams { // BD_ADDR of the Create Connection Command Request - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; } __PACKED; struct CreateConnectionCancelReturnParams { @@ -213,7 +213,7 @@ struct CreateConnectionCancelReturnParams { StatusCode status; // BD_ADDR of the Create Connection Command Request - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; } __PACKED; // ========================================= @@ -222,7 +222,7 @@ constexpr OpCode kAcceptConnectionRequest = LinkControlOpCode(0x0009); struct AcceptConnectionRequestCommandParams { // BD_ADDR of the device to be connected - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; // Role. Allowable values: // - kMaster - Host will become the master (Link Master will role switch) @@ -236,7 +236,7 @@ constexpr OpCode kRejectConnectionRequest = LinkControlOpCode(0x000A); struct RejectConnectionRequestCommandParams { // BD_ADDR of the device to reject the connection from - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; // Reason. // Must be one of kConnectionRejected* from Status in hci_constants.h @@ -253,7 +253,7 @@ constexpr OpCode kLinkKeyRequestReply = LinkControlOpCode(0x000B); struct LinkKeyRequestReplyCommandParams { // BD_ADDR of the peer device the link key is for. - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; // Link key to use for the connection with the peer device. uint8_t link_key[16]; @@ -264,7 +264,7 @@ struct LinkKeyRequestReplyReturnParams { StatusCode status; // BD_ADDR of the device whose Link Key Request was fulfilled. - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; } __PACKED; // ============================================================= @@ -273,7 +273,7 @@ constexpr OpCode kLinkKeyRequestNegativeReply = LinkControlOpCode(0x000C); struct LinkKeyRequestNegativeReplyCommandParams { // BD_ADDR of the peer device that the host does not have a link key for. - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; } __PACKED; struct LinkKeyRequestNegativeReplyReturnParams { @@ -281,7 +281,7 @@ struct LinkKeyRequestNegativeReplyReturnParams { StatusCode status; // BD_ADDR of the device whose Link Key Request was denied. - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; } __PACKED; // ============================================================ @@ -290,7 +290,7 @@ constexpr OpCode kRemoteNameRequest = LinkControlOpCode(0x0019); struct RemoteNameRequestCommandParams { // Address of the device whose name is to be requested. - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; // Page Scan Repetition Mode of the device, obtained by Inquiry. PageScanRepetitionMode page_scan_repetition_mode; @@ -369,7 +369,7 @@ constexpr OpCode kIOCapabilityRequestReply = LinkControlOpCode(0x002B); struct IOCapabilityRequestReplyCommandParams { // The BD_ADDR of the remote device involved in simple pairing process - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; // The IOCapabilities of this device IOCapability io_capability; @@ -391,7 +391,7 @@ struct IOCapabilityRequestReplyReturnParams { StatusCode status; // BD_ADDR of the remote device involved in simple pairing process - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; } __PACKED; // ======= Controller & Baseband Commands ======= @@ -407,7 +407,7 @@ constexpr OpCode kUserConfirmationRequestReply = LinkControlOpCode(0x002C); struct UserConfirmationRequestReplyCommandParams { // The BD_ADDR of the remote device involved in the simple pairing process. - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; } __PACKED; // ====================================================================== @@ -417,7 +417,7 @@ constexpr OpCode kUserConfirmationRequestNegativeReply = struct UserConfirmationRequestNegativeReplyCommandParams { // The BD_ADDR of the remote device involved in the simple pairing process. - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; } __PACKED; // ============================= @@ -558,7 +558,7 @@ struct ReadClassOfDeviceReturnParams { // See enum StatusCode in hci_constants.h. StatusCode status; - common::DeviceClass class_of_device; + DeviceClass class_of_device; } __PACKED; // ============================================= @@ -566,7 +566,7 @@ struct ReadClassOfDeviceReturnParams { constexpr OpCode kWriteClassOfDevice = ControllerAndBasebandOpCode(0x0024); struct WriteClassOfDeviceCommandParams { - common::DeviceClass class_of_device; + DeviceClass class_of_device; } __PACKED; // =============================================================== @@ -891,7 +891,7 @@ struct ReadBDADDRReturnParams { // See enum StatusCode in hci_constants.h. StatusCode status; - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; } __PACKED; // ======================================================= @@ -926,7 +926,7 @@ constexpr EventCode kInquiryResultEventCode = 0x02; struct InquiryResult { // The address for the device which responded. - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; // The Page Scan Repetition Mode being used by the remote device. PageScanRepetitionMode page_scan_repetition_mode; @@ -938,7 +938,7 @@ struct InquiryResult { uint8_t page_scan_mode; // Class of device - common::DeviceClass class_of_device; + DeviceClass class_of_device; // Clock Offset // the 15 lower bits represent bits 16-2 of CLKNslave-CLK @@ -969,7 +969,7 @@ struct ConnectionCompleteEventParams { ConnectionHandle connection_handle; // The address of the connected device - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; // See enum LinkType in hci_constants.h. // ExtendedSCO is not valid as a link type. @@ -986,10 +986,10 @@ constexpr EventCode kConnectionRequestEventCode = 0x04; struct ConnectionRequestEventParams { // The address of the device that's requesting the connection. - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; // The Class of Device of the device which requests the connection. - common::DeviceClass class_of_device; + DeviceClass class_of_device; // See enum LinkType in hci_constants.h LinkType link_type; @@ -1044,7 +1044,7 @@ struct RemoteNameRequestCompleteEventParams { StatusCode status; // Address of the device - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; // Remote Name - UTF-8 encoded friendly name. // If the name is less than 248 characters, it is null terminated and @@ -1162,7 +1162,7 @@ constexpr EventCode kLinkKeyRequestEventCode = 0x17; struct LinkKeyRequestParams { // The address for the device that a host-stored link key is being requested. - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; } __PACKED; // ======================================== @@ -1171,7 +1171,7 @@ constexpr EventCode kLinkKeyNotificationEventCode = 0x18; struct LinkKeyNotificationEventParams { // The address for the device for which a new link key has been generated. - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; // Link key for the associated address. uint8_t link_key[16]; @@ -1186,7 +1186,7 @@ constexpr EventCode kInquiryResultWithRSSIEventCode = 0x22; struct InquiryResultRSSI { // The address for the device which responded. - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; // The Page Scan Repetition Mode being used by the remote device. PageScanRepetitionMode page_scan_repetition_mode; @@ -1195,7 +1195,7 @@ struct InquiryResultRSSI { uint8_t page_scan_period_mode; // Class of device - common::DeviceClass class_of_device; + DeviceClass class_of_device; // Clock Offset // the 15 lower bits represent bits 16-2 of CLKNslave-CLK @@ -1253,7 +1253,7 @@ struct ExtendedInquiryResultEventParams { uint8_t num_responses; // BD_ADDR of the device that responded. - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; // The Page Scan Repetition Mode being used by the remote device. PageScanRepetitionMode page_scan_repetition_mode; @@ -1262,7 +1262,7 @@ struct ExtendedInquiryResultEventParams { uint8_t reserved; // Class of device - common::DeviceClass class_of_device; + DeviceClass class_of_device; // Clock offset // the 15 lower bits represent bits 16-2 of CLKNslave-CLK @@ -1297,7 +1297,7 @@ constexpr EventCode kIOCapabilityRequestEventCode = 0x31; struct IOCapabilityRequestEventParams { // The address of the remote device involved in the simple pairing process - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; } __PACKED; // ============================================= @@ -1306,7 +1306,7 @@ constexpr EventCode kIOCapabilityResponseEventCode = 0x32; struct IOCapabilityResponseEventParams { // The address of the remote device which the IO capabilities apply - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; // IO Capabilities of the device IOCapability io_capability; @@ -1328,7 +1328,7 @@ constexpr EventCode kUserConfirmationRequestEventCode = 0x33; struct UserConfirmationRequestEventParams { // Address of the device involved in simple pairing process - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; // Numeric valud to be displayed. Valid values are 0 - 999999 uint32_t numeric_value; @@ -1365,7 +1365,7 @@ struct LEConnectionCompleteSubeventParams { LEPeerAddressType peer_address_type; // Public Device Address or Random Device Address of the peer device. - common::DeviceAddressBytes peer_address; + DeviceAddressBytes peer_address; // Range: see kLEConnectionInterval[Min|Max] in hci_constants.h // Time: N * 1.25 ms @@ -1400,7 +1400,7 @@ struct LEAdvertisingReportData { // Public Device Address, Random Device Address, Public Identity Address or // Random (static) Identity Address of the advertising device. - common::DeviceAddressBytes address; + DeviceAddressBytes address; // Length of the advertising data payload. uint8_t length_data; @@ -1578,10 +1578,10 @@ struct LEEnhancedConnectionCompleteSubeventParams { // Public Device Address, or Random Device Address, Public Identity Address or // Random (static) Identity Address of the device to be connected. - common::DeviceAddressBytes peer_address; + DeviceAddressBytes peer_address; - common::DeviceAddressBytes local_resolvable_private_address; - common::DeviceAddressBytes peer_resolvable_private_address; + DeviceAddressBytes local_resolvable_private_address; + DeviceAddressBytes peer_resolvable_private_address; // Range: see kLEConnectionInterval[Min|Max] in hci_constants.h // Time: N * 1.25 ms @@ -1614,12 +1614,12 @@ struct LEDirectedAdvertisingReportData { // Public Device Address, Random Device Address, Public Identity Address or // Random (static) Identity Address of the advertising device. - common::DeviceAddressBytes address; + DeviceAddressBytes address; // By default this is set to LEAddressType::kRandom and |direct_address| will // contain a random device address. LEAddressType direct_address_type; - common::DeviceAddressBytes direct_address; + DeviceAddressBytes direct_address; // Range: -127 <= N <= +20 // Units: dBm @@ -1675,7 +1675,7 @@ struct LEExtendedAdvertisingReportData { // Public Device Address, Random Device Address, Public Identity Address or // Random (static) Identity Address of the advertising device. - common::DeviceAddressBytes address; + DeviceAddressBytes address; // Indicates the PHY used to send the advertising PDU on the primary // advertising channel. Legacy PDUs always use LEPHY::kLE1M @@ -1712,7 +1712,7 @@ struct LEExtendedAdvertisingReportData { // Public Device Address, Random Device Address, Public Identity Address or // Random (static) Identity Address of the target device. - common::DeviceAddressBytes direct_address; + DeviceAddressBytes direct_address; // Length of the data field. uint8_t data_length; @@ -1754,7 +1754,7 @@ struct LEPeriodicAdvertisingSyncEstablishedSubeventParams { // Public Device Address, Random Device Address, Public Identity Address, or // Random (static) Identity Address of the advertiser. - common::DeviceAddressBytes advertiser_address; + DeviceAddressBytes advertiser_address; // Advertiser_PHY. LEPHY advertiser_phy; @@ -1844,7 +1844,7 @@ struct LEScanRequestReceivedSubeventParams { // Public Device Address, Random Device Address, Public Identity Address or // Random (static) Identity Address of the scanning device. - common::DeviceAddressBytes scanner_address; + DeviceAddressBytes scanner_address; } __PACKED; // LE Channel Selection Algorithm Event (v5.0) (LE) @@ -2009,7 +2009,7 @@ struct LEReadLocalSupportedFeaturesReturnParams { constexpr OpCode kLESetRandomAddress = LEControllerCommandOpCode(0x0005); struct LESetRandomAddressCommandParams { - common::DeviceAddressBytes random_address; + DeviceAddressBytes random_address; } __PACKED; // ================================================= @@ -2039,7 +2039,7 @@ struct LESetAdvertisingParametersCommandParams { // Public Device Address, Random Device Address, Public Identity Address, or // Random (static) Identity Address of the device to be connected. - common::DeviceAddressBytes peer_address; + DeviceAddressBytes peer_address; // (See the constants kLEAdvertisingChannel* in hci_constants.h for possible // values). @@ -2152,7 +2152,7 @@ struct LECreateConnectionCommandParams { GenericEnableParam initiator_filter_policy; LEAddressType peer_address_type; - common::DeviceAddressBytes peer_address; + DeviceAddressBytes peer_address; LEOwnAddressType own_address_type; // Range: see kLEConnectionInterval[Min|Max] in hci_constants.h @@ -2209,7 +2209,7 @@ struct LEAddDeviceToWhiteListCommandParams { // Public Device Address or Random Device Address of the device to be added to // the White List. - common::DeviceAddressBytes address; + DeviceAddressBytes address; } __PACKED; // ==================================================== @@ -2224,7 +2224,7 @@ struct LERemoveDeviceFromWhiteListCommandParams { // Public Device Address or Random Device Address of the device to be removed // from the White List. - common::DeviceAddressBytes address; + DeviceAddressBytes address; } __PACKED; // ======================================== @@ -2338,7 +2338,7 @@ constexpr OpCode kLEEncrypt = LEControllerCommandOpCode(0x0017); struct LEEncryptCommandParams { // 128 bit key for the encryption of the data given in the command. - common::UInt128 key; + UInt128 key; // 128 bit data block that is requested to be encrypted. uint8_t plaintext_data[16]; @@ -2383,7 +2383,7 @@ struct LEStartEncryptionCommandParams { uint16_t encrypted_diversifier; // 128-bit long-term key (LTK). - common::UInt128 long_term_key; + UInt128 long_term_key; } __PACKED; // NOTE on Return Params: A Command Complete event is not sent by the Controller @@ -2402,7 +2402,7 @@ struct LELongTermKeyRequestReplyCommandParams { ConnectionHandle connection_handle; // 128-bit long term key for the current connection. - common::UInt128 long_term_key; + UInt128 long_term_key; } __PACKED; struct LELongTermKeyRequestReplyReturnParams { @@ -2654,13 +2654,13 @@ struct LEAddDeviceToResolvingListCommandParams { LEPeerAddressType peer_identity_address_type; // Public or Random (static) Identity address of the peer device - common::DeviceAddressBytes peer_identity_address; + DeviceAddressBytes peer_identity_address; // IRK (Identity Resolving Key) of the peer device - common::UInt128 peer_irk; + UInt128 peer_irk; // IRK (Identity Resolving Key) of the local device - common::UInt128 local_irk; + UInt128 local_irk; } __PACKED; // ======================================================== @@ -2673,7 +2673,7 @@ struct LERemoveDeviceFromResolvingListCommandParams { LEPeerAddressType peer_identity_address_type; // Public or Random (static) Identity address of the peer device - common::DeviceAddressBytes peer_identity_address; + DeviceAddressBytes peer_identity_address; } __PACKED; // =========================================== @@ -2702,7 +2702,7 @@ struct LEReadPeerResolvableAddressCommandParams { LEPeerAddressType peer_identity_address_type; // Public or Random (static) Identity address of the peer device. - common::DeviceAddressBytes peer_identity_address; + DeviceAddressBytes peer_identity_address; } __PACKED; struct LEReadPeerResolvableAddressReturnParams { @@ -2710,7 +2710,7 @@ struct LEReadPeerResolvableAddressReturnParams { StatusCode status; // Resolvable Private Address being used by the peer device. - common::DeviceAddressBytes peer_resolvable_address; + DeviceAddressBytes peer_resolvable_address; } __PACKED; // ==================================================== @@ -2723,7 +2723,7 @@ struct LEReadLocalResolvableAddressCommandParams { LEPeerAddressType peer_identity_address_type; // Public or Random (static) Identity address of the peer device - common::DeviceAddressBytes peer_identity_address; + DeviceAddressBytes peer_identity_address; } __PACKED; struct LEReadLocalResolvableAddressReturnParams { @@ -2731,7 +2731,7 @@ struct LEReadLocalResolvableAddressReturnParams { StatusCode status; // Resolvable Private Address being used by the local device. - common::DeviceAddressBytes local_resolvable_address; + DeviceAddressBytes local_resolvable_address; } __PACKED; // ==================================================== @@ -2896,7 +2896,7 @@ struct LESetAdvertisingSetRandomAddressCommandParams { AdvertisingHandle adv_handle; // Random Device Address. - common::DeviceAddressBytes adv_random_address; + DeviceAddressBytes adv_random_address; } __PACKED; // ========================================================== @@ -2927,7 +2927,7 @@ struct LESetExtendedAdvertisingParametersCommandParams { // Public Device Address, Random Device Address, Public Identity Address, or // Random (static) Identity Address of the device to be connected. - common::DeviceAddressBytes peer_address; + DeviceAddressBytes peer_address; LEAdvFilterPolicy adv_filter_policy; @@ -3248,7 +3248,7 @@ struct LEExtendedCreateConnectionCommandParams { // Public Device Address, Random Device Address, Public Identity Address, or // Random (static) Identity Address of the device to be connected. - common::DeviceAddressBytes peer_address; + DeviceAddressBytes peer_address; // See the kLEPHYBit* constants in hci_constants.h for possible bitfield // values. @@ -3281,7 +3281,7 @@ struct LEPeriodicAdvertisingCreateSyncCommandParams { // Public Device Address, Random Device Address, Public Identity Address, or // Random (static) Identity Address of the advertiser. - common::DeviceAddressBytes advertiser_address; + DeviceAddressBytes advertiser_address; // The number of periodic advertising packets that can be skipped after a // successful receive. @@ -3334,7 +3334,7 @@ struct LEAddDeviceToPeriodicAdvertiserListCommandParams { // Public Device Address, Random Device Address, Public Identity Address, or // Random (static) Identity Address of the advertiser. - common::DeviceAddressBytes advertiser_address; + DeviceAddressBytes advertiser_address; // Advertising SID subfield in the ADI field used to identify the Periodic // Advertising. @@ -3353,7 +3353,7 @@ struct LERemoveDeviceFromPeriodicAdvertiserListCommandParams { // Public Device Address, Random Device Address, Public Identity Address, or // Random (static) Identity Address of the advertiser. - common::DeviceAddressBytes advertiser_address; + DeviceAddressBytes advertiser_address; // Advertising SID subfield in the ADI field used to identify the Periodic // Advertising. @@ -3433,7 +3433,7 @@ struct LESetPrivacyModeCommandParams { // Public Identity Address or Random (static) Identity Address of the // advertiser. - common::DeviceAddressBytes peer_identity_address; + DeviceAddressBytes peer_identity_address; // The privacy mode to be used for the given entry on the resolving list. LEPrivacyMode privacy_mode; diff --git a/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_advertiser.cc b/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_advertiser.cc index fbbb53a1f1eb52406d7830ef002e7b2b8aeb9a70..d64bc2b26e3fc548ee15e2d0cf8bf3a7e60cbdfe 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_advertiser.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_advertiser.cc @@ -29,8 +29,7 @@ std::unique_ptr<CommandPacket> BuildEnablePacket(GenericEnableParam enable) { return packet; } -std::unique_ptr<CommandPacket> BuildSetAdvertisingData( - const common::ByteBuffer& data) { +std::unique_ptr<CommandPacket> BuildSetAdvertisingData(const ByteBuffer& data) { auto packet = CommandPacket::New(kLESetAdvertisingData, sizeof(LESetAdvertisingDataCommandParams)); packet->mutable_view()->mutable_payload_data().SetToZeros(); @@ -39,14 +38,14 @@ std::unique_ptr<CommandPacket> BuildSetAdvertisingData( ->mutable_payload<LESetAdvertisingDataCommandParams>(); params->adv_data_length = data.size(); - common::MutableBufferView adv_view(params->adv_data, params->adv_data_length); + MutableBufferView adv_view(params->adv_data, params->adv_data_length); data.Copy(&adv_view); return packet; } std::unique_ptr<CommandPacket> BuildSetScanResponse( - const common::ByteBuffer& scan_rsp) { + const ByteBuffer& scan_rsp) { auto packet = CommandPacket::New(kLESetScanResponseData, sizeof(LESetScanResponseDataCommandParams)); packet->mutable_view()->mutable_payload_data().SetToZeros(); @@ -55,8 +54,8 @@ std::unique_ptr<CommandPacket> BuildSetScanResponse( ->mutable_payload<LESetScanResponseDataCommandParams>(); params->scan_rsp_data_length = scan_rsp.size(); - common::MutableBufferView scan_data_view(params->scan_rsp_data, - sizeof(params->scan_rsp_data)); + MutableBufferView scan_data_view(params->scan_rsp_data, + sizeof(params->scan_rsp_data)); scan_rsp.Copy(&scan_data_view); return packet; @@ -132,22 +131,22 @@ bool LegacyLowEnergyAdvertiser::AllowsRandomAddressChange() const { } void LegacyLowEnergyAdvertiser::StartAdvertising( - const common::DeviceAddress& address, const common::ByteBuffer& data, - const common::ByteBuffer& scan_rsp, ConnectionCallback connect_callback, + const DeviceAddress& address, const ByteBuffer& data, + const ByteBuffer& scan_rsp, ConnectionCallback connect_callback, zx::duration interval, bool anonymous, AdvertisingStatusCallback callback) { ZX_DEBUG_ASSERT(callback); - ZX_DEBUG_ASSERT(address.type() != common::DeviceAddress::Type::kBREDR); + ZX_DEBUG_ASSERT(address.type() != DeviceAddress::Type::kBREDR); if (anonymous) { bt_log(TRACE, "hci-le", "anonymous advertising not supported"); - callback(zx::duration(), Status(common::HostError::kNotSupported)); + callback(zx::duration(), Status(HostError::kNotSupported)); return; } if (advertising()) { if (address != advertised_) { bt_log(TRACE, "hci-le", "already advertising"); - callback(zx::duration(), Status(common::HostError::kNotSupported)); + callback(zx::duration(), Status(HostError::kNotSupported)); return; } bt_log(TRACE, "hci-le", "updating existing advertisement"); @@ -155,20 +154,20 @@ void LegacyLowEnergyAdvertiser::StartAdvertising( if (data.size() > GetSizeLimit()) { bt_log(TRACE, "hci-le", "advertising data too large"); - callback(zx::duration(), Status(common::HostError::kInvalidParameters)); + callback(zx::duration(), Status(HostError::kInvalidParameters)); return; } if (scan_rsp.size() > GetSizeLimit()) { bt_log(TRACE, "hci-le", "scan response too large"); - callback(zx::duration(), Status(common::HostError::kInvalidParameters)); + callback(zx::duration(), Status(HostError::kInvalidParameters)); return; } if (!hci_cmd_runner_->IsReady()) { if (starting_) { bt_log(TRACE, "hci-le", "already starting"); - callback(zx::duration(), Status(common::HostError::kInProgress)); + callback(zx::duration(), Status(HostError::kInProgress)); return; } @@ -202,7 +201,7 @@ void LegacyLowEnergyAdvertiser::StartAdvertising( } LEOwnAddressType own_addr_type; - if (address.type() == common::DeviceAddress::Type::kLEPublic) { + if (address.type() == DeviceAddress::Type::kLEPublic) { own_addr_type = LEOwnAddressType::kPublic; } else { own_addr_type = LEOwnAddressType::kRandom; @@ -237,8 +236,7 @@ void LegacyLowEnergyAdvertiser::StartAdvertising( }); } -bool LegacyLowEnergyAdvertiser::StopAdvertising( - const common::DeviceAddress& address) { +bool LegacyLowEnergyAdvertiser::StopAdvertising(const DeviceAddress& address) { if (advertised_ != address) { // not advertising, or not on this address. return false; @@ -293,7 +291,7 @@ void LegacyLowEnergyAdvertiser::StopAdvertisingInternal() { void LegacyLowEnergyAdvertiser::OnIncomingConnection( ConnectionHandle handle, Connection::Role role, - const common::DeviceAddress& peer_address, + const DeviceAddress& peer_address, const LEConnectionParameters& conn_params) { if (!advertising()) { bt_log(TRACE, "hci-le", "connection received without advertising!"); diff --git a/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_advertiser.h b/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_advertiser.h index 07b8cdeb6e370c59022da2c982de28a5b36236f1..a38a6896322eb9c313953373789ee8285a9835d5 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_advertiser.h +++ b/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_advertiser.h @@ -29,9 +29,8 @@ class LegacyLowEnergyAdvertiser final : public LowEnergyAdvertiser { // 1. If called while a start request is pending, reports kRepeatedAttempts. // 2. If called while a stop request is pending, then cancels the stop request // and proceeds with start. - void StartAdvertising(const common::DeviceAddress& address, - const common::ByteBuffer& data, - const common::ByteBuffer& scan_rsp, + void StartAdvertising(const DeviceAddress& address, const ByteBuffer& data, + const ByteBuffer& scan_rsp, ConnectionCallback connect_callback, zx::duration interval, bool anonymous, AdvertisingStatusCallback callback) override; @@ -40,12 +39,12 @@ class LegacyLowEnergyAdvertiser final : public LowEnergyAdvertiser { // If called while a start request is pending, then cancels the start // request and proceeds with start. // Returns false if called while not advertising. - bool StopAdvertising(const common::DeviceAddress& address) override; + bool StopAdvertising(const DeviceAddress& address) override; // Clears the advertising state before passing |link| on to // |connect_callback_|. void OnIncomingConnection(ConnectionHandle handle, Connection::Role role, - const common::DeviceAddress& peer_address, + const DeviceAddress& peer_address, const LEConnectionParameters& conn_params) override; private: @@ -53,7 +52,7 @@ class LegacyLowEnergyAdvertiser final : public LowEnergyAdvertiser { void StopAdvertisingInternal(); // Returns true if currently advertising. - bool advertising() const { return advertised_ != common::DeviceAddress(); } + bool advertising() const { return advertised_ != DeviceAddress(); } // The transport that's used to issue commands fxl::RefPtr<Transport> hci_; @@ -64,7 +63,7 @@ class LegacyLowEnergyAdvertiser final : public LowEnergyAdvertiser { std::unique_ptr<SequentialCommandRunner> hci_cmd_runner_; // Non-zero if advertising has been enabled. - common::DeviceAddress advertised_; + DeviceAddress advertised_; // if not null, the callback for connectable advertising. ConnectionCallback connect_callback_; diff --git a/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_advertiser_unittest.cc b/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_advertiser_unittest.cc index d4dd4b6c07c78350564fd702c06d1f0708548005..ba50389499ef432836abc786c3b305054c453459 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_advertiser_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_advertiser_unittest.cc @@ -17,7 +17,6 @@ namespace bt { -using common::BufferView; using testing::FakeController; namespace hci { @@ -27,10 +26,10 @@ using TestingBase = bt::testing::FakeControllerTest<FakeController>; constexpr ConnectionHandle kHandle = 0x0001; -const common::DeviceAddress kPublicAddress( - common::DeviceAddress::Type::kLEPublic, "00:00:00:00:00:01"); -const common::DeviceAddress kRandomAddress( - common::DeviceAddress::Type::kLERandom, "00:00:00:00:00:02"); +const DeviceAddress kPublicAddress(DeviceAddress::Type::kLEPublic, + "00:00:00:00:00:01"); +const DeviceAddress kRandomAddress(DeviceAddress::Type::kLERandom, + "00:00:00:00:00:02"); constexpr size_t kDefaultAdSize = 20; constexpr zx::duration kTestInterval = zx::sec(1); @@ -90,8 +89,8 @@ class HCI_LegacyLowEnergyAdvertiserTest : public TestingBase { std::optional<Status> MoveLastStatus() { return std::move(last_status_); } // Makes some fake advertising data of a specific |packed_size| - common::DynamicByteBuffer GetExampleData(size_t size = kDefaultAdSize) { - common::DynamicByteBuffer result(size); + DynamicByteBuffer GetExampleData(size_t size = kDefaultAdSize) { + DynamicByteBuffer result(size); // Count backwards. for (size_t i = 0; i < size; i++) { result[i] = (uint8_t)((size - i) % 255); @@ -112,15 +111,15 @@ class HCI_LegacyLowEnergyAdvertiserTest : public TestingBase { // - Error when the advertisement data is too large TEST_F(HCI_LegacyLowEnergyAdvertiserTest, AdvertisementSizeTest) { // 4 bytes long (adv length: 7 bytes) - auto reasonable_data = common::CreateStaticByteBuffer(0x20, 0x06, 0xaa, 0xfe, - 'T', 'e', 's', 't'); + auto reasonable_data = + CreateStaticByteBuffer(0x20, 0x06, 0xaa, 0xfe, 'T', 'e', 's', 't'); // 30 bytes long (adv length: 33 bytes) - auto oversize_data = common::CreateStaticByteBuffer( + auto oversize_data = CreateStaticByteBuffer( 0x20, 0x20, 0xaa, 0xfe, 'T', 'h', 'e', 'q', 'u', 'i', 'c', 'k', 'b', 'r', 'o', 'w', 'n', 'f', 'o', 'x', 'w', 'a', 'g', 'g', 'e', 'd', 'i', 't', 's', 't', 'a', 'i', 'l', '.'); - common::DynamicByteBuffer scan_data; + DynamicByteBuffer scan_data; // Should accept ads that are of reasonable size advertiser()->StartAdvertising(kPublicAddress, reasonable_data, scan_data, @@ -145,8 +144,8 @@ TEST_F(HCI_LegacyLowEnergyAdvertiserTest, AdvertisementSizeTest) { // - Checks that advertising state is cleaned up. // - Checks that it is possible to restart advertising. TEST_F(HCI_LegacyLowEnergyAdvertiserTest, ConnectionTest) { - common::DynamicByteBuffer ad = GetExampleData(); - common::DynamicByteBuffer scan_data; + DynamicByteBuffer ad = GetExampleData(); + DynamicByteBuffer scan_data; ConnectionPtr link; auto conn_cb = [&link](auto cb_link) { link = std::move(cb_link); }; @@ -192,8 +191,8 @@ TEST_F(HCI_LegacyLowEnergyAdvertiserTest, ConnectionTest) { // Tests that advertising can be restarted right away in a connection callback. TEST_F(HCI_LegacyLowEnergyAdvertiserTest, RestartInConnectionCallback) { - common::DynamicByteBuffer ad = GetExampleData(); - common::DynamicByteBuffer scan_data; + DynamicByteBuffer ad = GetExampleData(); + DynamicByteBuffer scan_data; ConnectionPtr link; auto conn_cb = [&, this](auto cb_link) { @@ -234,8 +233,8 @@ TEST_F(HCI_LegacyLowEnergyAdvertiserTest, RestartInConnectionCallback) { // Tests starting and stopping an advertisement. TEST_F(HCI_LegacyLowEnergyAdvertiserTest, StartAndStop) { constexpr zx::duration kInterval = zx::msec(500); - common::DynamicByteBuffer ad = GetExampleData(); - common::DynamicByteBuffer scan_data; + DynamicByteBuffer ad = GetExampleData(); + DynamicByteBuffer scan_data; advertiser()->StartAdvertising(kRandomAddress, ad, scan_data, nullptr, kInterval, false, GetSuccessCallback()); @@ -280,9 +279,9 @@ TEST_F(HCI_LegacyLowEnergyAdvertiserTest, AdvertisingParameters) { } TEST_F(HCI_LegacyLowEnergyAdvertiserTest, StartWhileStarting) { - common::DynamicByteBuffer ad = GetExampleData(); - common::DynamicByteBuffer scan_data; - common::DeviceAddress addr = kRandomAddress; + DynamicByteBuffer ad = GetExampleData(); + DynamicByteBuffer scan_data; + DeviceAddress addr = kRandomAddress; advertiser()->StartAdvertising(addr, ad, scan_data, nullptr, kTestInterval, false, [](auto, auto) {}); @@ -293,13 +292,13 @@ TEST_F(HCI_LegacyLowEnergyAdvertiserTest, StartWhileStarting) { EXPECT_FALSE(test_device()->le_advertising_state().enabled); auto status = MoveLastStatus(); ASSERT_TRUE(status); - EXPECT_EQ(common::HostError::kInProgress, status->error()); + EXPECT_EQ(HostError::kInProgress, status->error()); } TEST_F(HCI_LegacyLowEnergyAdvertiserTest, StartWhileStopping) { - common::DynamicByteBuffer ad = GetExampleData(); - common::DynamicByteBuffer scan_data; - common::DeviceAddress addr = kRandomAddress; + DynamicByteBuffer ad = GetExampleData(); + DynamicByteBuffer scan_data; + DeviceAddress addr = kRandomAddress; // Get to a started state. advertiser()->StartAdvertising(addr, ad, scan_data, nullptr, kTestInterval, @@ -337,8 +336,8 @@ TEST_F(HCI_LegacyLowEnergyAdvertiserTest, StartWhileStopping) { // - Sets the advertisement data to null when stopped to prevent data leakage // (re-enable advertising without changing data, intercept) TEST_F(HCI_LegacyLowEnergyAdvertiserTest, StopAdvertisingConditions) { - common::DynamicByteBuffer ad = GetExampleData(); - common::DynamicByteBuffer scan_data; + DynamicByteBuffer ad = GetExampleData(); + DynamicByteBuffer scan_data; advertiser()->StartAdvertising(kRandomAddress, ad, scan_data, nullptr, kTestInterval, false, GetSuccessCallback()); @@ -367,8 +366,8 @@ TEST_F(HCI_LegacyLowEnergyAdvertiserTest, StopAdvertisingConditions) { // - Rejects StartAdvertising for a different address when Advertising already TEST_F(HCI_LegacyLowEnergyAdvertiserTest, NoAdvertiseTwice) { - common::DynamicByteBuffer ad = GetExampleData(); - common::DynamicByteBuffer scan_data; + DynamicByteBuffer ad = GetExampleData(); + DynamicByteBuffer scan_data; advertiser()->StartAdvertising(kRandomAddress, ad, scan_data, nullptr, kTestInterval, false, GetSuccessCallback()); @@ -399,8 +398,8 @@ TEST_F(HCI_LegacyLowEnergyAdvertiserTest, NoAdvertiseTwice) { // - Updates data and params for the same address when advertising already TEST_F(HCI_LegacyLowEnergyAdvertiserTest, AdvertiseUpdate) { - common::DynamicByteBuffer ad = GetExampleData(); - common::DynamicByteBuffer scan_data; + DynamicByteBuffer ad = GetExampleData(); + DynamicByteBuffer scan_data; advertiser()->StartAdvertising(kRandomAddress, ad, scan_data, nullptr, kTestInterval, false, GetSuccessCallback()); @@ -426,8 +425,8 @@ TEST_F(HCI_LegacyLowEnergyAdvertiserTest, AdvertiseUpdate) { // - Rejects anonymous advertisement (unsupported) TEST_F(HCI_LegacyLowEnergyAdvertiserTest, NoAnonymous) { - common::DynamicByteBuffer ad = GetExampleData(); - common::DynamicByteBuffer scan_data; + DynamicByteBuffer ad = GetExampleData(); + DynamicByteBuffer scan_data; advertiser()->StartAdvertising(kRandomAddress, ad, scan_data, nullptr, kTestInterval, true, GetErrorCallback()); diff --git a/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner.cc b/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner.cc index a8b1637c7cb378c6e5fef5404f7cb120d7d19010..728418b5bd63bd289dcd8a09489ea7ae56e25620 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner.cc @@ -17,9 +17,6 @@ namespace bt { -using common::BufferView; -using common::DeviceAddress; - namespace hci { namespace { @@ -107,8 +104,8 @@ bool LegacyLowEnergyScanner::StartScan(bool active, uint16_t scan_interval, } void LegacyLowEnergyScanner::StartScanInternal( - const common::DeviceAddress& local_address, bool active, - uint16_t scan_interval, uint16_t scan_window, bool filter_duplicates, + const DeviceAddress& local_address, bool active, uint16_t scan_interval, + uint16_t scan_window, bool filter_duplicates, LEScanFilterPolicy filter_policy, zx::duration period, ScanStatusCallback callback) { // Check if the scan request was canceled by StopScan() while we were waiting @@ -157,7 +154,7 @@ void LegacyLowEnergyScanner::StartScanInternal( ZX_DEBUG_ASSERT(state() == State::kInitiating); if (!status) { - if (status.error() == common::HostError::kCanceled) { + if (status.error() == HostError::kCanceled) { bt_log(TRACE, "hci-le", "scan canceled"); return; } @@ -303,7 +300,7 @@ void LegacyLowEnergyScanner::OnAdvertisingReportEvent( continue; } - common::DeviceAddress address; + DeviceAddress address; bool resolved; if (!DeviceAddressFromAdvReport(*report, &address, &resolved)) continue; @@ -332,7 +329,7 @@ void LegacyLowEnergyScanner::OnAdvertisingReportEvent( void LegacyLowEnergyScanner::HandleScanResponse( const LEAdvertisingReportData& report, int8_t rssi) { - common::DeviceAddress address; + DeviceAddress address; bool resolved; if (!DeviceAddressFromAdvReport(report, &address, &resolved)) return; @@ -363,7 +360,7 @@ void LegacyLowEnergyScanner::HandleScanResponse( } void LegacyLowEnergyScanner::NotifyPeerFound(const LowEnergyScanResult& result, - const common::ByteBuffer& data) { + const ByteBuffer& data) { delegate()->OnPeerFound(result, data); } diff --git a/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner.h b/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner.h index 7c23a5c28ec158835ac58ffadda62030345cd882..c2ab77a200236830e8f304576a1ec9ac7bb5da3a 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner.h +++ b/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner.h @@ -51,13 +51,13 @@ class LegacyLowEnergyScanner : public LowEnergyScanner { // Make this large enough to store both advertising and scan response data // PDUs. size_t adv_data_len; - common::StaticByteBuffer<kMaxLEAdvertisingDataLength * 2> data; + StaticByteBuffer<kMaxLEAdvertisingDataLength * 2> data; }; // Called by StartScan() after the local peer address has been obtained. - void StartScanInternal(const common::DeviceAddress& local_address, - bool active, uint16_t scan_interval, - uint16_t scan_window, bool filter_duplicates, + void StartScanInternal(const DeviceAddress& local_address, bool active, + uint16_t scan_interval, uint16_t scan_window, + bool filter_duplicates, LEScanFilterPolicy filter_policy, zx::duration period, ScanStatusCallback callback); @@ -72,7 +72,7 @@ class LegacyLowEnergyScanner : public LowEnergyScanner { // Notifies observers of a peer that was found. void NotifyPeerFound(const LowEnergyScanResult& result, - const common::ByteBuffer& data); + const ByteBuffer& data); // Called when the scan timeout task executes. void OnScanPeriodComplete(); @@ -92,7 +92,7 @@ class LegacyLowEnergyScanner : public LowEnergyScanner { // Scannable advertising events for which a Scan Response PDU has not been // received. This is accumulated during a discovery procedure and always // cleared at the end of the scan period. - std::unordered_map<common::DeviceAddress, PendingScanResult> pending_results_; + std::unordered_map<DeviceAddress, PendingScanResult> pending_results_; fxl::ThreadChecker thread_checker_; DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(LegacyLowEnergyScanner); diff --git a/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner_unittest.cc b/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner_unittest.cc index 3398e1f6b5f6fb5e76bf95207e1c043f078002a5..3a6e27aabcb3a037256e76a6ec57ae5b7d3a2f38 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner_unittest.cc @@ -17,7 +17,6 @@ namespace bt { namespace hci { namespace { -using common::DeviceAddress; using testing::FakeController; using testing::FakePeer; using TestingBase = testing::FakeControllerTest<FakeController>; @@ -71,8 +70,8 @@ class LegacyLowEnergyScannerTest : public TestingBase, TestingBase::TearDown(); } - using PeerFoundCallback = fit::function<void(const LowEnergyScanResult&, - const common::ByteBuffer&)>; + using PeerFoundCallback = + fit::function<void(const LowEnergyScanResult&, const ByteBuffer&)>; void set_peer_found_callback(PeerFoundCallback cb) { peer_found_cb_ = std::move(cb); } @@ -92,7 +91,7 @@ class LegacyLowEnergyScannerTest : public TestingBase, // LowEnergyScanner::Observer override: void OnPeerFound(const LowEnergyScanResult& result, - const common::ByteBuffer& data) override { + const ByteBuffer& data) override { if (peer_found_cb_) { peer_found_cb_(result, data); } @@ -109,9 +108,9 @@ class LegacyLowEnergyScannerTest : public TestingBase, void AddFakePeers() { // We use malformed data for testing purposes, as we don't care about // integrity here. - auto adv_data = common::CreateStaticByteBuffer('T', 'e', 's', 't'); - auto scan_rsp = common::CreateStaticByteBuffer('D', 'a', 't', 'a'); - auto empty_data = common::DynamicByteBuffer(); + auto adv_data = CreateStaticByteBuffer('T', 'e', 's', 't'); + auto scan_rsp = CreateStaticByteBuffer('D', 'a', 't', 'a'); + auto empty_data = DynamicByteBuffer(); // Generates ADV_IND, scan response is reported in a single HCI event. auto fake_peer = std::make_unique<FakePeer>(kPublicAddress1, true, true); diff --git a/src/connectivity/bluetooth/core/bt-host/hci/link_key.cc b/src/connectivity/bluetooth/core/bt-host/hci/link_key.cc index b1825e3619cae15a94f05c9a26efaa27fa12d59b..4de230932518ce99c1b7990a368e06d2d7f3787b 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/link_key.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/link_key.cc @@ -9,7 +9,7 @@ namespace hci { LinkKey::LinkKey() : rand_(0), ediv_(0) { value_.fill(0); } -LinkKey::LinkKey(const common::UInt128& ltk, uint64_t rand, uint16_t ediv) +LinkKey::LinkKey(const UInt128& ltk, uint64_t rand, uint16_t ediv) : value_(ltk), rand_(rand), ediv_(ediv) {} } // namespace hci diff --git a/src/connectivity/bluetooth/core/bt-host/hci/link_key.h b/src/connectivity/bluetooth/core/bt-host/hci/link_key.h index 9769c8ea49f99954d74a1885aae62899f79fd811..97f06173d53be89ef199b2c224ed85b7e6b2f022 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/link_key.h +++ b/src/connectivity/bluetooth/core/bt-host/hci/link_key.h @@ -16,10 +16,10 @@ namespace hci { class LinkKey final { public: LinkKey(); - LinkKey(const common::UInt128& value, uint64_t rand, uint16_t ediv); + LinkKey(const UInt128& value, uint64_t rand, uint16_t ediv); // 128-bit BR/EDR link key, LE Long Term Key, or LE Short Term key. - const common::UInt128& value() const { return value_; } + const UInt128& value() const { return value_; } // Encrypted diversifier and random values used to identify the LTK. These // values are set to 0 for the LE Legacy STK, LE Secure Connections LTK, and @@ -33,7 +33,7 @@ class LinkKey final { } private: - common::UInt128 value_; + UInt128 value_; uint64_t rand_; uint16_t ediv_; }; diff --git a/src/connectivity/bluetooth/core/bt-host/hci/local_address_delegate.h b/src/connectivity/bluetooth/core/bt-host/hci/local_address_delegate.h index 99fc51ecfec90a98fc2949696624d1269ba9391e..c7e405fd71ed9fa732473c45e45d3e4714192bb6 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/local_address_delegate.h +++ b/src/connectivity/bluetooth/core/bt-host/hci/local_address_delegate.h @@ -22,10 +22,10 @@ class LocalAddressDelegate { virtual ~LocalAddressDelegate() = default; // Returns the currently assigned IRK, if any. - virtual std::optional<common::UInt128> irk() const = 0; + virtual std::optional<UInt128> irk() const = 0; // Returns the identity address. - virtual common::DeviceAddress identity_address() const = 0; + virtual DeviceAddress identity_address() const = 0; // Asynchronously returns the local LE controller address used by all LE link // layer procedures with the exception of 5.0 advertising sets. These include: @@ -41,7 +41,7 @@ class LocalAddressDelegate { // // This method runs |callback| when the procedure ends. |callback| may run // synchronously or asynchronously. - using AddressCallback = fit::function<void(const common::DeviceAddress&)>; + using AddressCallback = fit::function<void(const DeviceAddress&)>; virtual void EnsureLocalAddress(AddressCallback callback) = 0; }; diff --git a/src/connectivity/bluetooth/core/bt-host/hci/low_energy_advertiser.h b/src/connectivity/bluetooth/core/bt-host/hci/low_energy_advertiser.h index 21be93420b12dae156d617eeff748f1b164454bd..a6867192ee4d98464de44f37fefa9a36bc88fc38 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/low_energy_advertiser.h +++ b/src/connectivity/bluetooth/core/bt-host/hci/low_energy_advertiser.h @@ -75,16 +75,16 @@ class LowEnergyAdvertiser : public LocalAddressClient { using AdvertisingStatusCallback = fit::function<void(zx::duration interval, Status status)>; using ConnectionCallback = fit::function<void(ConnectionPtr link)>; - virtual void StartAdvertising(const common::DeviceAddress& address, - const common::ByteBuffer& data, - const common::ByteBuffer& scan_rsp, + virtual void StartAdvertising(const DeviceAddress& address, + const ByteBuffer& data, + const ByteBuffer& scan_rsp, ConnectionCallback connect_callback, zx::duration interval, bool anonymous, AdvertisingStatusCallback callback) = 0; // Stops any advertisement currently active on |address|. Idempotent and // asynchronous. Returns true if advertising will be stopped, false otherwise. - virtual bool StopAdvertising(const common::DeviceAddress& address) = 0; + virtual bool StopAdvertising(const DeviceAddress& address) = 0; // Callback for an incoming LE connection. This function should be called // in reaction to any connection that was not initiated locally. This object @@ -93,7 +93,7 @@ class LowEnergyAdvertiser : public LocalAddressClient { // TODO(armansito): Require advertising handle. virtual void OnIncomingConnection( ConnectionHandle handle, Connection::Role role, - const common::DeviceAddress& peer_address, + const DeviceAddress& peer_address, const LEConnectionParameters& conn_params) = 0; }; diff --git a/src/connectivity/bluetooth/core/bt-host/hci/low_energy_connector.cc b/src/connectivity/bluetooth/core/bt-host/hci/low_energy_connector.cc index 2bd07dc0758037f1b2bf4a474d954ba5c420ebe0..042207b12a6a931df90926e4912db61cb23ef677 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/low_energy_connector.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/low_energy_connector.cc @@ -18,9 +18,6 @@ namespace bt { namespace hci { -using common::DeviceAddress; -using common::HostError; - LowEnergyConnector::PendingRequest::PendingRequest( const DeviceAddress& peer_address, StatusCallback status_callback) : peer_address(peer_address), status_callback(std::move(status_callback)) {} diff --git a/src/connectivity/bluetooth/core/bt-host/hci/low_energy_connector.h b/src/connectivity/bluetooth/core/bt-host/hci/low_energy_connector.h index b4253734487bfd3c574849ca2aec72a345a99509..89ca516c533e0c8e09034fdd86e3887cb9a65855 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/low_energy_connector.h +++ b/src/connectivity/bluetooth/core/bt-host/hci/low_energy_connector.h @@ -55,7 +55,7 @@ class LowEnergyConnector : public LocalAddressClient { // is established due to an incoming request (remote initiated). using IncomingConnectionDelegate = fit::function<void(ConnectionHandle handle, Connection::Role role, - const common::DeviceAddress& peer_address, + const DeviceAddress& peer_address, const LEConnectionParameters& conn_params)>; LowEnergyConnector(fxl::RefPtr<Transport> hci, LocalAddressDelegate* local_addr_delegate, @@ -81,7 +81,7 @@ class LowEnergyConnector : public LocalAddressClient { // called with a null |link| and a |status| with error Host::Error::kTimedOut. using StatusCallback = fit::function<void(Status status, ConnectionPtr link)>; bool CreateConnection( - bool use_whitelist, const common::DeviceAddress& peer_address, + bool use_whitelist, const DeviceAddress& peer_address, uint16_t scan_interval, uint16_t scan_window, const LEPreferredConnectionParameters& initial_parameters, StatusCallback status_callback, zx::duration timeout); @@ -104,22 +104,22 @@ class LowEnergyConnector : public LocalAddressClient { private: struct PendingRequest { PendingRequest() = default; - PendingRequest(const common::DeviceAddress& peer_address, + PendingRequest(const DeviceAddress& peer_address, StatusCallback status_callback); bool initiating = false; // True if the HCI command has been sent. bool canceled = false; bool timed_out = false; - common::DeviceAddress local_address; - common::DeviceAddress peer_address; + DeviceAddress local_address; + DeviceAddress peer_address; StatusCallback status_callback; }; // Called by CreateConnection() after the local device address has been // obtained. void CreateConnectionInternal( - const common::DeviceAddress& local_address, bool use_whitelist, - const common::DeviceAddress& peer_address, uint16_t scan_interval, + const DeviceAddress& local_address, bool use_whitelist, + const DeviceAddress& peer_address, uint16_t scan_interval, uint16_t scan_window, const LEPreferredConnectionParameters& initial_parameters, StatusCallback status_callback, zx::duration timeout); diff --git a/src/connectivity/bluetooth/core/bt-host/hci/low_energy_connector_unittest.cc b/src/connectivity/bluetooth/core/bt-host/hci/low_energy_connector_unittest.cc index 48ebf4f4044dfce118b0abdc7af3cacc2daeaf24..8b8c734c2c85bd1c1bccc95fe5d1342e3c04cf5e 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/low_energy_connector_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/low_energy_connector_unittest.cc @@ -24,13 +24,12 @@ using bt::testing::FakeController; using bt::testing::FakePeer; using TestingBase = bt::testing::FakeControllerTest<FakeController>; -using common::HostError; -const common::DeviceAddress kLocalAddress( - common::DeviceAddress::Type::kLEPublic, "00:00:00:00:00:FF"); -const common::DeviceAddress kRandomAddress( - common::DeviceAddress::Type::kLERandom, "00:00:00:00:00:FE"); -const common::DeviceAddress kTestAddress(common::DeviceAddress::Type::kLEPublic, - "00:00:00:00:00:01"); +const DeviceAddress kLocalAddress(DeviceAddress::Type::kLEPublic, + "00:00:00:00:00:FF"); +const DeviceAddress kRandomAddress(DeviceAddress::Type::kLERandom, + "00:00:00:00:00:FE"); +const DeviceAddress kTestAddress(DeviceAddress::Type::kLEPublic, + "00:00:00:00:00:01"); const LEPreferredConnectionParameters kTestParams(1, 1, 1, 1); constexpr zx::duration kConnectTimeout = zx::sec(10); @@ -83,15 +82,15 @@ class LowEnergyConnectorTest : public TestingBase { private: void OnIncomingConnectionCreated(ConnectionHandle handle, Connection::Role role, - const common::DeviceAddress& peer_address, + const DeviceAddress& peer_address, const LEConnectionParameters& conn_params) { in_connections_.push_back(std::make_unique<testing::FakeConnection>( handle, hci::Connection::LinkType::kLE, role, kLocalAddress, peer_address)); } - void OnConnectionStateChanged(const common::DeviceAddress& address, - bool connected, bool canceled) { + void OnConnectionStateChanged(const DeviceAddress& address, bool connected, + bool canceled) { request_canceled = canceled; } @@ -276,7 +275,7 @@ TEST_F(HCI_LowEnergyConnectorTest, IncomingConnect) { event.connection_handle = 1; test_device()->SendLEMetaEvent(kLEConnectionCompleteSubeventCode, - common::BufferView(&event, sizeof(event))); + BufferView(&event, sizeof(event))); RunLoopUntilIdle(); @@ -291,8 +290,8 @@ TEST_F(HCI_LowEnergyConnectorTest, IncomingConnect) { } TEST_F(HCI_LowEnergyConnectorTest, IncomingConnectDuringConnectionRequest) { - const common::DeviceAddress kIncomingAddress( - common::DeviceAddress::Type::kLEPublic, "00:00:00:00:00:02"); + const DeviceAddress kIncomingAddress(DeviceAddress::Type::kLEPublic, + "00:00:00:00:00:02"); EXPECT_TRUE(in_connections().empty()); EXPECT_FALSE(connector()->request_pending()); @@ -325,7 +324,7 @@ TEST_F(HCI_LowEnergyConnectorTest, IncomingConnectDuringConnectionRequest) { event.connection_handle = 2; test_device()->SendLEMetaEvent(kLEConnectionCompleteSubeventCode, - common::BufferView(&event, sizeof(event))); + BufferView(&event, sizeof(event))); }); RunLoopUntilIdle(); diff --git a/src/connectivity/bluetooth/core/bt-host/hci/low_energy_scanner.cc b/src/connectivity/bluetooth/core/bt-host/hci/low_energy_scanner.cc index 3b34f95a4ce9a864b9ed2d01bbc72b2db21e022e..9eed4218e1103c01dfd0008e276abe7e50a63425 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/low_energy_scanner.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/low_energy_scanner.cc @@ -15,7 +15,7 @@ namespace hci { // Default implementations do nothing. void LowEnergyScanner::Delegate::OnPeerFound(const LowEnergyScanResult& result, - const common::ByteBuffer& data) {} + const ByteBuffer& data) {} void LowEnergyScanner::Delegate::OnDirectedAdvertisement( const LowEnergyScanResult& result) {} @@ -23,7 +23,7 @@ void LowEnergyScanner::Delegate::OnDirectedAdvertisement( LowEnergyScanResult::LowEnergyScanResult() : resolved(false), connectable(false), rssi(hci::kRSSIInvalid) {} -LowEnergyScanResult::LowEnergyScanResult(const common::DeviceAddress& address, +LowEnergyScanResult::LowEnergyScanResult(const DeviceAddress& address, bool resolved, bool connectable, int8_t rssi) : address(address), diff --git a/src/connectivity/bluetooth/core/bt-host/hci/low_energy_scanner.h b/src/connectivity/bluetooth/core/bt-host/hci/low_energy_scanner.h index 81f18a32585433252ca47c9f5bc605a4a489f22a..03335c2849ba265817a508d138d0fa3386b1b6a7 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/low_energy_scanner.h +++ b/src/connectivity/bluetooth/core/bt-host/hci/low_energy_scanner.h @@ -25,11 +25,11 @@ class Transport; // Represents a discovered Bluetooth Low Energy peer. struct LowEnergyScanResult { LowEnergyScanResult(); - LowEnergyScanResult(const common::DeviceAddress& address, bool resolved, + LowEnergyScanResult(const DeviceAddress& address, bool resolved, bool connectable, int8_t rssi); // The device address of the remote peer. - common::DeviceAddress address; + DeviceAddress address; // True if |address| is a static or random identity address resolved by the // controller. @@ -82,7 +82,7 @@ class LowEnergyScanner : public LocalAddressClient { // Called when a peer is found. |data| contains the advertising data, as // well as any scan response data that was received during an active scan. virtual void OnPeerFound(const LowEnergyScanResult& result, - const common::ByteBuffer& data); + const ByteBuffer& data); // Called when a directed advertising report is received from the peer // with the given address. diff --git a/src/connectivity/bluetooth/core/bt-host/hci/packet.h b/src/connectivity/bluetooth/core/bt-host/hci/packet.h index ed86450c11762ccd86f5f309620ca3bdc6991ca5..65e2cc7a4d1dae994e1f565ddf19a83abb7f1e85 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/packet.h +++ b/src/connectivity/bluetooth/core/bt-host/hci/packet.h @@ -38,12 +38,12 @@ namespace hci { // class FixedBufferPacket : public Packet<HeaderType> { // public: // void Init(size_t payload_size) { -// this->init_view(common::MutablePacketView<HeaderType>(&buffer_, +// this->init_view(MutablePacketView<HeaderType>(&buffer_, // payload_size)); // } // // private: -// common::StaticByteBuffer<BufferSize> buffer_; +// StaticByteBuffer<BufferSize> buffer_; // }; // // std::unique_ptr<Packet<MyHeaderType>> packet = @@ -93,26 +93,26 @@ namespace hci { // linked-listability. Intended to be inherited by the Packet template and all // of its specializations. template <typename HeaderType, typename T> -class PacketBase : public common::LinkedListable<T> { +class PacketBase : public LinkedListable<T> { public: virtual ~PacketBase() = default; - const common::PacketView<HeaderType>& view() const { return view_; } - common::MutablePacketView<HeaderType>* mutable_view() { return &view_; } + const PacketView<HeaderType>& view() const { return view_; } + MutablePacketView<HeaderType>* mutable_view() { return &view_; } protected: PacketBase() = default; // Called by derived classes to initialize |view_| after initializing the // corresponding buffer. - void init_view(const common::MutablePacketView<HeaderType>& view) { + void init_view(const MutablePacketView<HeaderType>& view) { ZX_DEBUG_ASSERT(!view_.is_valid()); ZX_DEBUG_ASSERT(view.is_valid()); view_ = view; } private: - common::MutablePacketView<HeaderType> view_; + MutablePacketView<HeaderType> view_; DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(PacketBase); }; diff --git a/src/connectivity/bluetooth/core/bt-host/hci/packet_unittest.cc b/src/connectivity/bluetooth/core/bt-host/hci/packet_unittest.cc index b2f6d74b7aecda59c007594792a48c818fc26455..ff6530283b58d343d40140a78d130739d2e78723 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/packet_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/packet_unittest.cc @@ -2,21 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "src/connectivity/bluetooth/core/bt-host/hci/acl_data_packet.h" -#include "src/connectivity/bluetooth/core/bt-host/hci/control_packets.h" +#include <endian.h> +#include <zircon/compiler.h> #include <array> #include <cstdint> -#include <endian.h> -#include <zircon/compiler.h> - #include "gtest/gtest.h" - #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" +#include "src/connectivity/bluetooth/core/bt-host/hci/acl_data_packet.h" +#include "src/connectivity/bluetooth/core/bt-host/hci/control_packets.h" -using bt::common::ContainersEqual; -using bt::common::StaticByteBuffer; +using bt::ContainersEqual; +using bt::StaticByteBuffer; namespace bt { namespace hci { @@ -41,7 +39,7 @@ TEST(HCI_PacketTest, CommandPacket) { // clang-format off - auto kExpected = common::CreateStaticByteBuffer( + auto kExpected = CreateStaticByteBuffer( 0xFF, 0x07, // opcode 0x01, // parameter_total_size 0x7F // foo @@ -58,7 +56,7 @@ TEST(HCI_PacketTest, EventPacket) { // clang-format off - auto bytes = common::CreateStaticByteBuffer( + auto bytes = CreateStaticByteBuffer( 0xFF, // event code 0x01, // parameter_total_size 0x7F // foo @@ -76,7 +74,7 @@ TEST(HCI_PacketTest, EventPacket) { TEST(HCI_PacketTest, EventPacketReturnParams) { // clang-format off - auto correct_size_bad_event_code = common::CreateStaticByteBuffer( + auto correct_size_bad_event_code = CreateStaticByteBuffer( // Event header 0xFF, 0x04, // (event_code is not CommandComplete) @@ -85,13 +83,13 @@ TEST(HCI_PacketTest, EventPacketReturnParams) { // Return parameters 0x7F); - auto cmd_complete_small_payload = common::CreateStaticByteBuffer( + auto cmd_complete_small_payload = CreateStaticByteBuffer( // Event header 0x0E, 0x03, // CommandCompleteEventParams 0x01, 0xFF, 0x07); - auto valid = common::CreateStaticByteBuffer( + auto valid = CreateStaticByteBuffer( // Event header 0x0E, 0x04, @@ -128,7 +126,7 @@ TEST(HCI_PacketTest, EventPacketReturnParams) { TEST(HCI_PacketTest, EventPacketStatus) { // clang-format off - auto evt = common::CreateStaticByteBuffer( + auto evt = CreateStaticByteBuffer( // Event header 0x05, 0x04, // (event_code is DisconnectionComplete) @@ -150,7 +148,7 @@ TEST(HCI_PacketTest, EventPacketStatus) { TEST(HCI_PacketTest, CommandCompleteEventStatus) { // clang-format off - auto evt = common::CreateStaticByteBuffer( + auto evt = CreateStaticByteBuffer( // Event header 0x0E, 0x04, // (event code is CommandComplete) @@ -172,7 +170,7 @@ TEST(HCI_PacketTest, CommandCompleteEventStatus) { TEST(HCI_PacketTest, EventPacketMalformed) { // clang-format off - auto evt = common::CreateStaticByteBuffer( + auto evt = CreateStaticByteBuffer( // Event header 0x05, 0x03, // (event_code is DisconnectionComplete) @@ -189,13 +187,13 @@ TEST(HCI_PacketTest, EventPacketMalformed) { Status status = packet->ToStatus(); EXPECT_FALSE(status.is_protocol_error()); - EXPECT_EQ(common::HostError::kPacketMalformed, status.error()); + EXPECT_EQ(HostError::kPacketMalformed, status.error()); } TEST(HCI_PacketTest, LEEventParams) { // clang-format off - auto correct_size_bad_event_code = common::CreateStaticByteBuffer( + auto correct_size_bad_event_code = CreateStaticByteBuffer( // Event header 0xFF, 0x02, // (event_code is not LEMetaEventCode) @@ -204,12 +202,12 @@ TEST(HCI_PacketTest, LEEventParams) { // Subevent payload 0x7F); - auto payload_too_small = common::CreateStaticByteBuffer( + auto payload_too_small = CreateStaticByteBuffer( 0x3E, 0x01, // Subevent code 0xFF); - auto valid = common::CreateStaticByteBuffer( + auto valid = CreateStaticByteBuffer( // Event header 0x3E, 0x02, @@ -290,7 +288,7 @@ TEST(HCI_PacketTest, ACLDataPacketFromBuffer) { // First 12-bits: 0x07F // Upper 4-bits: 0b0101 - auto bytes = common::CreateStaticByteBuffer(0x7F, 0x50, 0x01, 0x00, 0x00); + auto bytes = CreateStaticByteBuffer(0x7F, 0x50, 0x01, 0x00, 0x00); auto packet = ACLDataPacket::New(kSmallDataLength); packet->mutable_view()->mutable_data().Write(bytes); packet->InitializeFromBuffer(); @@ -303,7 +301,7 @@ TEST(HCI_PacketTest, ACLDataPacketFromBuffer) { // First 12-bits: 0xFFF // Upper 4-bits: 0b0111 - bytes = common::CreateStaticByteBuffer(0xFF, 0x7F, 0x01, 0x00, 0x00); + bytes = CreateStaticByteBuffer(0xFF, 0x7F, 0x01, 0x00, 0x00); packet->mutable_view()->mutable_data().Write(bytes); packet->InitializeFromBuffer(); @@ -315,7 +313,7 @@ TEST(HCI_PacketTest, ACLDataPacketFromBuffer) { packet = ACLDataPacket::New(kLargeDataLength); packet->mutable_view()->mutable_data().Write( - common::CreateStaticByteBuffer(0xFF, 0x0F, 0x00, 0x01)); + CreateStaticByteBuffer(0xFF, 0x0F, 0x00, 0x01)); packet->InitializeFromBuffer(); EXPECT_EQ(0x0FFF, packet->connection_handle()); diff --git a/src/connectivity/bluetooth/core/bt-host/hci/sequential_command_runner.cc b/src/connectivity/bluetooth/core/bt-host/hci/sequential_command_runner.cc index ded343824c47c75751e56a2f7041a51a94f8b8a8..c32b8a33907bd23fdb06715dee78d0261f67f87f 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/sequential_command_runner.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/sequential_command_runner.cc @@ -11,8 +11,6 @@ namespace bt { namespace hci { -using common::HostError; - SequentialCommandRunner::SequentialCommandRunner( async_dispatcher_t* dispatcher, fxl::RefPtr<Transport> transport) : dispatcher_(dispatcher), @@ -59,7 +57,7 @@ bool SequentialCommandRunner::IsReady() const { void SequentialCommandRunner::Cancel() { ZX_DEBUG_ASSERT(status_callback_); - status_callback_(Status(common::HostError::kCanceled)); + status_callback_(Status(HostError::kCanceled)); Reset(); } diff --git a/src/connectivity/bluetooth/core/bt-host/hci/sequential_command_runner_unittest.cc b/src/connectivity/bluetooth/core/bt-host/hci/sequential_command_runner_unittest.cc index d14c7810117b56bbf48bfde2cfaf4b1956953798..3702b547fc60f62055871a6708280e1bc6592e0a 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/sequential_command_runner_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/sequential_command_runner_unittest.cc @@ -31,22 +31,22 @@ using HCI_SequentialCommandRunnerTest = SequentialCommandRunnerTest; TEST_F(HCI_SequentialCommandRunnerTest, SequentialCommandRunner) { // HCI command with custom opcode FFFF. - auto command_bytes = common::CreateStaticByteBuffer(0xFF, 0xFF, 0x00); + auto command_bytes = CreateStaticByteBuffer(0xFF, 0xFF, 0x00); - auto command_status_error_bytes = common::CreateStaticByteBuffer( - kCommandStatusEventCode, - 0x04, // parameter_total_size (4 byte payload) - StatusCode::kHardwareFailure, 1, 0xFF, 0xFF); + auto command_status_error_bytes = + CreateStaticByteBuffer(kCommandStatusEventCode, + 0x04, // parameter_total_size (4 byte payload) + StatusCode::kHardwareFailure, 1, 0xFF, 0xFF); - auto command_cmpl_error_bytes = common::CreateStaticByteBuffer( - kCommandCompleteEventCode, - 0x04, // parameter_total_size (4 byte payload) - 1, 0xFF, 0xFF, StatusCode::kReserved0); + auto command_cmpl_error_bytes = + CreateStaticByteBuffer(kCommandCompleteEventCode, + 0x04, // parameter_total_size (4 byte payload) + 1, 0xFF, 0xFF, StatusCode::kReserved0); - auto command_cmpl_success_bytes = common::CreateStaticByteBuffer( - kCommandCompleteEventCode, - 0x04, // parameter_total_size (4 byte payload) - 1, 0xFF, 0xFF, StatusCode::kSuccess); + auto command_cmpl_success_bytes = + CreateStaticByteBuffer(kCommandCompleteEventCode, + 0x04, // parameter_total_size (4 byte payload) + 1, 0xFF, 0xFF, StatusCode::kSuccess); // Here we perform multiple test sequences where we queue up several commands // in each sequence. We expect each sequence to terminate differently after @@ -193,17 +193,17 @@ TEST_F(HCI_SequentialCommandRunnerTest, SequentialCommandRunner) { } TEST_F(HCI_SequentialCommandRunnerTest, SequentialCommandRunnerCancel) { - auto command_bytes = common::CreateStaticByteBuffer(0xFF, 0xFF, 0x00); + auto command_bytes = CreateStaticByteBuffer(0xFF, 0xFF, 0x00); - auto command_cmpl_error_bytes = common::CreateStaticByteBuffer( - kCommandCompleteEventCode, - 0x04, // parameter_total_size (4 byte payload) - 1, 0xFF, 0xFF, StatusCode::kHardwareFailure); + auto command_cmpl_error_bytes = + CreateStaticByteBuffer(kCommandCompleteEventCode, + 0x04, // parameter_total_size (4 byte payload) + 1, 0xFF, 0xFF, StatusCode::kHardwareFailure); - auto command_cmpl_success_bytes = common::CreateStaticByteBuffer( - kCommandCompleteEventCode, - 0x04, // parameter_total_size (4 byte payload) - 1, 0xFF, 0xFF, StatusCode::kSuccess); + auto command_cmpl_success_bytes = + CreateStaticByteBuffer(kCommandCompleteEventCode, + 0x04, // parameter_total_size (4 byte payload) + 1, 0xFF, 0xFF, StatusCode::kSuccess); // Sequence 1 // -> Command; <- success complete @@ -260,7 +260,7 @@ TEST_F(HCI_SequentialCommandRunnerTest, SequentialCommandRunnerCancel) { EXPECT_EQ(1, cb_called); EXPECT_EQ(1, status_cb_called); - EXPECT_EQ(common::HostError::kCanceled, status.error()); + EXPECT_EQ(HostError::kCanceled, status.error()); cb_called = 0; status_cb_called = 0; status = Status(); @@ -289,7 +289,7 @@ TEST_F(HCI_SequentialCommandRunnerTest, SequentialCommandRunnerCancel) { EXPECT_EQ(0, cb_called); EXPECT_EQ(1, status_cb_called); - EXPECT_EQ(common::HostError::kCanceled, status.error()); + EXPECT_EQ(HostError::kCanceled, status.error()); // Sequence 3: Sequence will be cancelled after first command and immediately // followed by a second command which will fail. This tests canceling a @@ -301,7 +301,7 @@ TEST_F(HCI_SequentialCommandRunnerTest, SequentialCommandRunnerCancel) { EXPECT_FALSE(cmd_runner.HasQueuedCommands()); EXPECT_EQ(2, status_cb_called); - EXPECT_EQ(common::HostError::kCanceled, status.error()); + EXPECT_EQ(HostError::kCanceled, status.error()); // Queue multiple commands (only one will execute since TestController // will send back an error status. @@ -332,43 +332,43 @@ TEST_F(HCI_SequentialCommandRunnerTest, SequentialCommandRunnerCancel) { TEST_F(HCI_SequentialCommandRunnerTest, ParallelCommands) { // Need to signal to the queue that we can run more than one command at once. - auto command_status_queue_increase = common::CreateStaticByteBuffer( - kCommandStatusEventCode, - 0x04, // parameter_total_size (4 byte payload) - StatusCode::kSuccess, 250, 0x00, 0x00); + auto command_status_queue_increase = + CreateStaticByteBuffer(kCommandStatusEventCode, + 0x04, // parameter_total_size (4 byte payload) + StatusCode::kSuccess, 250, 0x00, 0x00); // HCI command with custom opcode FFFF. - auto command_bytes = common::CreateStaticByteBuffer(0xFF, 0xFF, 0x00); - auto command_status_error_bytes = common::CreateStaticByteBuffer( - kCommandStatusEventCode, - 0x04, // parameter_total_size (4 byte payload) - StatusCode::kHardwareFailure, 2, 0xFF, 0xFF); - - auto command_cmpl_error_bytes = common::CreateStaticByteBuffer( - kCommandCompleteEventCode, - 0x04, // parameter_total_size (4 byte payload) - 2, 0xFF, 0xFF, StatusCode::kReserved0); - - auto command_cmpl_success_bytes = common::CreateStaticByteBuffer( - kCommandCompleteEventCode, - 0x04, // parameter_total_size (4 byte payload) - 2, 0xFF, 0xFF, StatusCode::kSuccess); + auto command_bytes = CreateStaticByteBuffer(0xFF, 0xFF, 0x00); + auto command_status_error_bytes = + CreateStaticByteBuffer(kCommandStatusEventCode, + 0x04, // parameter_total_size (4 byte payload) + StatusCode::kHardwareFailure, 2, 0xFF, 0xFF); + + auto command_cmpl_error_bytes = + CreateStaticByteBuffer(kCommandCompleteEventCode, + 0x04, // parameter_total_size (4 byte payload) + 2, 0xFF, 0xFF, StatusCode::kReserved0); + + auto command_cmpl_success_bytes = + CreateStaticByteBuffer(kCommandCompleteEventCode, + 0x04, // parameter_total_size (4 byte payload) + 2, 0xFF, 0xFF, StatusCode::kSuccess); // HCI command with custom opcode F00F. - auto command2_bytes = common::CreateStaticByteBuffer(0x0F, 0xF0, 0x00); - auto command2_status_error_bytes = common::CreateStaticByteBuffer( - kCommandStatusEventCode, - 0x04, // parameter_total_size (4 byte payload) - StatusCode::kHardwareFailure, 2, 0x0F, 0xF0); - - auto command2_cmpl_error_bytes = common::CreateStaticByteBuffer( - kCommandCompleteEventCode, - 0x04, // parameter_total_size (4 byte payload) - 2, 0x0F, 0xF0, StatusCode::kReserved0); - - auto command2_cmpl_success_bytes = common::CreateStaticByteBuffer( - kCommandCompleteEventCode, - 0x04, // parameter_total_size (4 byte payload) - 2, 0x0F, 0xF0, StatusCode::kSuccess); + auto command2_bytes = CreateStaticByteBuffer(0x0F, 0xF0, 0x00); + auto command2_status_error_bytes = + CreateStaticByteBuffer(kCommandStatusEventCode, + 0x04, // parameter_total_size (4 byte payload) + StatusCode::kHardwareFailure, 2, 0x0F, 0xF0); + + auto command2_cmpl_error_bytes = + CreateStaticByteBuffer(kCommandCompleteEventCode, + 0x04, // parameter_total_size (4 byte payload) + 2, 0x0F, 0xF0, StatusCode::kReserved0); + + auto command2_cmpl_success_bytes = + CreateStaticByteBuffer(kCommandCompleteEventCode, + 0x04, // parameter_total_size (4 byte payload) + 2, 0x0F, 0xF0, StatusCode::kSuccess); test_device()->StartCmdChannel(test_cmd_chan()); test_device()->StartAclChannel(test_acl_chan()); @@ -391,7 +391,7 @@ TEST_F(HCI_SequentialCommandRunnerTest, ParallelCommands) { auto cb = [&](const auto&) { cb_called++; }; int status_cb_called = 0; - Status status(common::HostError::kFailed); + Status status(HostError::kFailed); auto status_cb = [&](Status cb_status) { status = cb_status; status_cb_called++; @@ -401,12 +401,13 @@ TEST_F(HCI_SequentialCommandRunnerTest, ParallelCommands) { cmd_runner.QueueCommand(CommandPacket::New(kTestOpCode), cb, false); cmd_runner.QueueCommand(CommandPacket::New(kTestOpCode2), cb, false); - cmd_runner.QueueCommand(CommandPacket::New(kTestOpCode), - [&](const auto&) { - EXPECT_EQ(2, cb_called); - cb_called++; - }, - true); + cmd_runner.QueueCommand( + CommandPacket::New(kTestOpCode), + [&](const auto&) { + EXPECT_EQ(2, cb_called); + cb_called++; + }, + true); // We can also queue to the end of the queue without the last one being a // wait. cmd_runner.QueueCommand(CommandPacket::New(kTestOpCode), cb, false); diff --git a/src/connectivity/bluetooth/core/bt-host/hci/slab_allocators.h b/src/connectivity/bluetooth/core/bt-host/hci/slab_allocators.h index 2dee3021583da939b3de5cb89b082b295ed41013..d3065e03905430868e10f4290993b2c28c329d82 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/slab_allocators.h +++ b/src/connectivity/bluetooth/core/bt-host/hci/slab_allocators.h @@ -104,14 +104,13 @@ template <typename HeaderType, size_t BufferSize> class FixedSizePacket : public Packet<HeaderType> { public: explicit FixedSizePacket(size_t payload_size = 0u) : Packet<HeaderType>() { - this->init_view( - common::MutablePacketView<HeaderType>(&buffer_, payload_size)); + this->init_view(MutablePacketView<HeaderType>(&buffer_, payload_size)); } ~FixedSizePacket() override = default; private: - common::StaticByteBuffer<BufferSize> buffer_; + StaticByteBuffer<BufferSize> buffer_; DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(FixedSizePacket); }; @@ -122,7 +121,7 @@ class SlabPacket; } // namespace internal template <typename HeaderType, size_t BufferSize, size_t NumBuffers> -using PacketTraits = common::SlabAllocatorTraits< +using PacketTraits = SlabAllocatorTraits< internal::SlabPacket<HeaderType, BufferSize, NumBuffers>, sizeof(internal::FixedSizePacket<HeaderType, BufferSize>), NumBuffers>; diff --git a/src/connectivity/bluetooth/core/bt-host/hci/slab_allocators_unittest.cc b/src/connectivity/bluetooth/core/bt-host/hci/slab_allocators_unittest.cc index abf8cbbe4ce86bfe60927e8a1b4e595d182bb83a..ce16a68bd517c7d42f9eb258e8a4ebd5f2b765b8 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/slab_allocators_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/slab_allocators_unittest.cc @@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include <forward_list> +#include "slab_allocators.h" -#include "gtest/gtest.h" +#include <forward_list> #include "acl_data_packet.h" #include "control_packets.h" -#include "slab_allocators.h" +#include "gtest/gtest.h" namespace bt { namespace hci { @@ -33,7 +33,7 @@ TEST(HCI_SlabAllocatorsTest, CommandPacket) { TEST(HCI_SlabAllocatorsTest, CommandPacketFallBack) { size_t num_packets = 0; - common::LinkedList<Packet<CommandHeader>> packets; + LinkedList<Packet<CommandHeader>> packets; // Allocate a lot of small packets. We should be able to allocate two // allocators' worth of packets until we fail. @@ -66,7 +66,7 @@ TEST(HCI_SlabAllocatorsTest, ACLDataPacket) { TEST(HCI_SlabAllocatorsTest, ACLDataPacketFallBack) { size_t num_packets = 0; - common::LinkedList<Packet<ACLDataHeader>> packets; + LinkedList<Packet<ACLDataHeader>> packets; // Allocate a lot of small packets. We should be able to allocate three // allocators' worth of packets until we fail. diff --git a/src/connectivity/bluetooth/core/bt-host/hci/status.cc b/src/connectivity/bluetooth/core/bt-host/hci/status.cc index eb1f73f3e3bc787ac6c52c215e37c17bcb1386ef..05e29b9e88e82ce57541ebff4d3ce4cc4f8d65d9 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/status.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/status.cc @@ -7,7 +7,6 @@ #include "util.h" namespace bt { -namespace common { // static std::string ProtocolErrorTraits<hci::StatusCode>::ToString( @@ -16,13 +15,11 @@ std::string ProtocolErrorTraits<hci::StatusCode>::ToString( static_cast<unsigned int>(ecode)); } -} // namespace common - namespace hci { -using Base = common::Status<StatusCode>; +using Base = bt::Status<StatusCode>; -Status::Status(common::HostError ecode) : Base(ecode) {} +Status::Status(HostError ecode) : Base(ecode) {} // HCI has a "success" status code which we specially handle while constructing // a success Status. diff --git a/src/connectivity/bluetooth/core/bt-host/hci/status.h b/src/connectivity/bluetooth/core/bt-host/hci/status.h index 536fb47ee68a9871d3e9c18db6bf1986c08e1818..3e2fe03cf93a43b0caa2367c1ae12849e4c03d6e 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/status.h +++ b/src/connectivity/bluetooth/core/bt-host/hci/status.h @@ -10,7 +10,7 @@ #include "src/connectivity/bluetooth/core/bt-host/common/status.h" #include "src/connectivity/bluetooth/core/bt-host/hci/hci_constants.h" -// This file provides a common::Status template specialization for hci::Status +// This file provides a Status template specialization for hci::Status // // EXAMPLES: // @@ -18,7 +18,7 @@ // hci::Status status; // // // 2. Status containing a host-internal error: -// hci::Status status(common::HostError::kTimedOut); +// hci::Status status(HostError::kTimedOut); // // // 3. Status containing HCI status code: // hci::Status status(hci::Status::kHardwareFailure); @@ -29,20 +29,17 @@ // status.is_protocol_error() -> false namespace bt { -namespace common { template <> struct ProtocolErrorTraits<hci::StatusCode> { static std::string ToString(hci::StatusCode ecode); }; -} // namespace common - namespace hci { -class Status : public common::Status<StatusCode> { +class Status : public bt::Status<StatusCode> { public: - explicit Status(common::HostError ecode = common::HostError::kNoError); + explicit Status(HostError ecode = HostError::kNoError); explicit Status(hci::StatusCode proto_code); }; diff --git a/src/connectivity/bluetooth/core/bt-host/hci/util.cc b/src/connectivity/bluetooth/core/bt-host/hci/util.cc index 77a730f420746d3aecaaf3efb32632c60117bd75..32366df5f2c107901e0e4514dce94b19d1f8e012 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/util.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/util.cc @@ -10,8 +10,6 @@ namespace bt { -using common::DeviceAddress; - namespace hci { std::string HCIVersionToString(HCIVersion version) { diff --git a/src/connectivity/bluetooth/core/bt-host/hci/util.h b/src/connectivity/bluetooth/core/bt-host/hci/util.h index 17d1fcd2fc5eb3a726e5231c7aa419ce42757d70..4336722b61ced3bb34426fc7bc0bc6625e757b48 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/util.h +++ b/src/connectivity/bluetooth/core/bt-host/hci/util.h @@ -22,21 +22,20 @@ std::string HCIVersionToString(hci::HCIVersion version); // Returns a user-friendly string representation of |status|. std::string StatusCodeToString(hci::StatusCode code); -// Constructs a common::DeviceAddress structure from the contents of the given +// Constructs a DeviceAddress structure from the contents of the given // advertising report. Returns false if the report contain an invalid value. // The address will be returned in the |out_address| parameter. The value of // |out_resolved| will indicate whether or not this address corresponds to a // resolved RPA (Vol 2, Part E, 7.7.65.2). bool DeviceAddressFromAdvReport(const hci::LEAdvertisingReportData& report, - common::DeviceAddress* out_address, - bool* out_resolved); + DeviceAddress* out_address, bool* out_resolved); // Convert HCI LE device address type to our stack type. -common::DeviceAddress::Type AddressTypeFromHCI(LEAddressType type); -common::DeviceAddress::Type AddressTypeFromHCI(LEPeerAddressType type); +DeviceAddress::Type AddressTypeFromHCI(LEAddressType type); +DeviceAddress::Type AddressTypeFromHCI(LEPeerAddressType type); // Convert our stack LE address type to HCI type. |type| cannot be kBREDR. -LEAddressType AddressTypeToHCI(common::DeviceAddress::Type type); +LEAddressType AddressTypeToHCI(DeviceAddress::Type type); } // namespace hci } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/hci/util_unittest.cc b/src/connectivity/bluetooth/core/bt-host/hci/util_unittest.cc index b5f0d8abfa1a4fff54b1846b0b5a9f56087c74b2..85fd38a77d00b58e4101d0695da420141da1551d 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/util_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/util_unittest.cc @@ -10,15 +10,11 @@ namespace bt { namespace hci { namespace { -using common::DeviceAddress; -using common::DeviceAddressBytes; -using common::StaticByteBuffer; - TEST(HCI_UtilTest, DeviceAddressFromAdvReportParsesAddress) { StaticByteBuffer<sizeof(LEAdvertisingReportData)> buffer; auto* report = reinterpret_cast<LEAdvertisingReportData*>(buffer.mutable_data()); - report->address = common::DeviceAddressBytes({0, 1, 2, 3, 4, 5}); + report->address = DeviceAddressBytes({0, 1, 2, 3, 4, 5}); report->address_type = LEAddressType::kPublicIdentity; DeviceAddress address; diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_rx_engine.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_rx_engine.cc index 126367c68d5c399700550b1a4310e01426f3e555..0ca3072497986ff53127236c036efb766028673c 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_rx_engine.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_rx_engine.cc @@ -10,9 +10,9 @@ namespace bt { namespace l2cap { namespace internal { -common::ByteBufferPtr BasicModeRxEngine::ProcessPdu(PDU pdu) { +ByteBufferPtr BasicModeRxEngine::ProcessPdu(PDU pdu) { ZX_ASSERT(pdu.is_valid()); - auto sdu = std::make_unique<common::DynamicByteBuffer>(pdu.length()); + auto sdu = std::make_unique<DynamicByteBuffer>(pdu.length()); pdu.Copy(sdu.get()); return sdu; } diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_rx_engine.h b/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_rx_engine.h index d5e81000f8b6ce270dc16119b41d739a45e243cc..2fc37ea062e4727fc55b3ad5f3dceaaa09027e5d 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_rx_engine.h +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_rx_engine.h @@ -18,7 +18,7 @@ class BasicModeRxEngine final : public RxEngine { BasicModeRxEngine() = default; virtual ~BasicModeRxEngine() = default; - common::ByteBufferPtr ProcessPdu(PDU) override; + ByteBufferPtr ProcessPdu(PDU) override; private: DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(BasicModeRxEngine); diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_rx_engine_unittest.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_rx_engine_unittest.cc index 6b53d0985126bc5d2563e0a67d2b818db6d7e8d2..2dc303a003445b08d2260b8d3a398f02275e9b84 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_rx_engine_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_rx_engine_unittest.cc @@ -4,12 +4,12 @@ #include "basic_mode_rx_engine.h" +#include "gtest/gtest.h" #include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" #include "src/connectivity/bluetooth/core/bt-host/hci/hci.h" #include "src/connectivity/bluetooth/core/bt-host/l2cap/fragmenter.h" #include "src/connectivity/bluetooth/core/bt-host/l2cap/recombiner.h" -#include "gtest/gtest.h" namespace bt { namespace l2cap { @@ -20,18 +20,18 @@ constexpr hci::ConnectionHandle kTestHandle = 0x0001; constexpr ChannelId kTestChannelId = 0x0001; TEST(L2CAP_BasicModeRxEngineTest, ProcessPduReturnsSdu) { - const auto payload = common::CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o'); + const auto payload = CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o'); const auto sdu = BasicModeRxEngine().ProcessPdu( Fragmenter(kTestHandle).BuildBasicFrame(kTestChannelId, payload)); ASSERT_TRUE(sdu); - EXPECT_TRUE(common::ContainersEqual(payload, *sdu)); + EXPECT_TRUE(ContainersEqual(payload, *sdu)); } TEST(L2CAP_BasicModeRxEngineTest, ProcessPduCanHandleZeroBytePayload) { - const auto byte_buf = common::CreateStaticByteBuffer( - 0x01, 0x00, 0x04, 0x00, // ACL data header - 0x00, 0x00, 0xFF, 0xFF // Basic L2CAP header - ); + const auto byte_buf = + CreateStaticByteBuffer(0x01, 0x00, 0x04, 0x00, // ACL data header + 0x00, 0x00, 0xFF, 0xFF // Basic L2CAP header + ); auto hci_packet = hci::ACLDataPacket::New(byte_buf.size() - sizeof(hci::ACLDataHeader)); hci_packet->mutable_view()->mutable_data().Write(byte_buf); @@ -46,8 +46,7 @@ TEST(L2CAP_BasicModeRxEngineTest, ProcessPduCanHandleZeroBytePayload) { ASSERT_EQ(1u, pdu.fragment_count()); ASSERT_EQ(0u, pdu.length()); - const common::ByteBufferPtr sdu = - BasicModeRxEngine().ProcessPdu(std::move(pdu)); + const ByteBufferPtr sdu = BasicModeRxEngine().ProcessPdu(std::move(pdu)); ASSERT_TRUE(sdu); EXPECT_EQ(0u, sdu->size()); } diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_tx_engine.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_tx_engine.cc index 39ff81e5af43d105d554476a2006f481022f7a29..bc0cf977864d8aaa10bcf3306c9eb8df471f1c38 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_tx_engine.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_tx_engine.cc @@ -12,7 +12,7 @@ namespace bt { namespace l2cap { namespace internal { -bool BasicModeTxEngine::QueueSdu(common::ByteBufferPtr sdu) { +bool BasicModeTxEngine::QueueSdu(ByteBufferPtr sdu) { ZX_ASSERT(sdu); if (sdu->size() > tx_mtu_) { bt_log(TRACE, "l2cap", "SDU size exceeds channel TxMTU (channel-id: %#.4x)", diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_tx_engine.h b/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_tx_engine.h index 19a738239a494192246b191f43f65b40ff7d5411..7886e927c407dca2fdd8c0f06df0c6a4c83e1274 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_tx_engine.h +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_tx_engine.h @@ -26,7 +26,7 @@ class BasicModeTxEngine final : public TxEngine { // Queues |sdu| for transmission, returning true on success. This may fail, // e.g., if the |sdu| is larger than |tx_mtu_|. - bool QueueSdu(common::ByteBufferPtr sdu) override; + bool QueueSdu(ByteBufferPtr sdu) override; private: DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(BasicModeTxEngine); diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_tx_engine_unittest.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_tx_engine_unittest.cc index 25a9f097d40a4600a190a142faa40d3e2b2c12e0..820a62449b7dab585f155b9cbf2a9e0706ebe0c2 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_tx_engine_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_tx_engine_unittest.cc @@ -4,9 +4,9 @@ #include "basic_mode_tx_engine.h" +#include "gtest/gtest.h" #include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" -#include "gtest/gtest.h" namespace bt { namespace l2cap { @@ -16,7 +16,7 @@ namespace { constexpr ChannelId kTestChannelId = 0x0001; TEST(L2CAP_BasicModeTxEngineTest, QueueSduTransmitsMinimalSizedSdu) { - common::ByteBufferPtr last_pdu; + ByteBufferPtr last_pdu; size_t n_pdus = 0; auto tx_callback = [&](auto pdu) { ++n_pdus; @@ -24,16 +24,16 @@ TEST(L2CAP_BasicModeTxEngineTest, QueueSduTransmitsMinimalSizedSdu) { }; constexpr size_t kMtu = 10; - const auto payload = common::CreateStaticByteBuffer(1); + const auto payload = CreateStaticByteBuffer(1); BasicModeTxEngine(kTestChannelId, kMtu, tx_callback) - .QueueSdu(std::make_unique<common::DynamicByteBuffer>(payload)); + .QueueSdu(std::make_unique<DynamicByteBuffer>(payload)); EXPECT_EQ(1u, n_pdus); ASSERT_TRUE(last_pdu); - EXPECT_TRUE(common::ContainersEqual(payload, *last_pdu)); + EXPECT_TRUE(ContainersEqual(payload, *last_pdu)); } TEST(L2CAP_BasicModeTxEngineTest, QueueSduTransmitsMaximalSizedSdu) { - common::ByteBufferPtr last_pdu; + ByteBufferPtr last_pdu; size_t n_pdus = 0; auto tx_callback = [&](auto pdu) { ++n_pdus; @@ -41,12 +41,12 @@ TEST(L2CAP_BasicModeTxEngineTest, QueueSduTransmitsMaximalSizedSdu) { }; constexpr size_t kMtu = 1; - const auto payload = common::CreateStaticByteBuffer(1); + const auto payload = CreateStaticByteBuffer(1); BasicModeTxEngine(kTestChannelId, kMtu, tx_callback) - .QueueSdu(std::make_unique<common::DynamicByteBuffer>(payload)); + .QueueSdu(std::make_unique<DynamicByteBuffer>(payload)); EXPECT_EQ(1u, n_pdus); ASSERT_TRUE(last_pdu); - EXPECT_TRUE(common::ContainersEqual(payload, *last_pdu)); + EXPECT_TRUE(ContainersEqual(payload, *last_pdu)); } TEST(L2CAP_BasicModeTxEngineTest, QueueSduDropsOversizedSdu) { @@ -55,15 +55,15 @@ TEST(L2CAP_BasicModeTxEngineTest, QueueSduDropsOversizedSdu) { constexpr size_t kMtu = 1; BasicModeTxEngine(kTestChannelId, kMtu, tx_callback) - .QueueSdu(std::make_unique<common::DynamicByteBuffer>( - common::CreateStaticByteBuffer(1, 2))); + .QueueSdu( + std::make_unique<DynamicByteBuffer>(CreateStaticByteBuffer(1, 2))); EXPECT_EQ(0u, n_pdus); } TEST(L2CAP_BasicModeTxEngineTest, QueueSduSurvivesZeroByteSdu) { constexpr size_t kMtu = 1; BasicModeTxEngine(kTestChannelId, kMtu, [](auto pdu) { - }).QueueSdu(std::make_unique<common::DynamicByteBuffer>()); + }).QueueSdu(std::make_unique<DynamicByteBuffer>()); } } // namespace diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_command_handler.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_command_handler.cc index cbe421f2a439afaa30c173a5669f6766ec527fd8..136eb42bdf8a7cadde4d424254b9bdfcaa4dd16c 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_command_handler.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_command_handler.cc @@ -13,9 +13,6 @@ namespace bt { namespace l2cap { namespace internal { -using common::BufferView; -using common::ByteBuffer; - bool BrEdrCommandHandler::Response::ParseReject( const ByteBuffer& rej_payload_buf) { auto& rej_payload = rej_payload_buf.As<CommandRejectPayload>(); @@ -47,8 +44,8 @@ void BrEdrCommandHandler::ConnectionResponse::Decode( void BrEdrCommandHandler::ConfigurationResponse::Decode( const ByteBuffer& payload_buf) { - common::PacketView<PayloadT> config_rsp( - &payload_buf, payload_buf.size() - sizeof(PayloadT)); + PacketView<PayloadT> config_rsp(&payload_buf, + payload_buf.size() - sizeof(PayloadT)); local_cid_ = letoh16(config_rsp.header().src_cid); flags_ = letoh16(config_rsp.header().flags); result_ = @@ -104,10 +101,10 @@ BrEdrCommandHandler::ConfigurationResponder::ConfigurationResponder( void BrEdrCommandHandler::ConfigurationResponder::Send( ChannelId remote_cid, uint16_t flags, ConfigurationResult result, const ByteBuffer& data) { - common::DynamicByteBuffer config_rsp_buf( - sizeof(ConfigurationResponsePayload) + data.size()); - common::MutablePacketView<ConfigurationResponsePayload> config_rsp( - &config_rsp_buf, data.size()); + DynamicByteBuffer config_rsp_buf(sizeof(ConfigurationResponsePayload) + + data.size()); + MutablePacketView<ConfigurationResponsePayload> config_rsp(&config_rsp_buf, + data.size()); config_rsp.mutable_header()->src_cid = htole16(remote_cid); config_rsp.mutable_header()->flags = htole16(flags); config_rsp.mutable_header()->result = @@ -159,9 +156,9 @@ void BrEdrCommandHandler::InformationResponder::Send(InformationResult result, const ByteBuffer& data) { constexpr size_t kMaxPayloadLength = sizeof(InformationResponsePayload) + sizeof(uint64_t); - common::StaticByteBuffer<kMaxPayloadLength> info_rsp_buf; - common::MutablePacketView<InformationResponsePayload> info_rsp_view( - &info_rsp_buf, data.size()); + StaticByteBuffer<kMaxPayloadLength> info_rsp_buf; + MutablePacketView<InformationResponsePayload> info_rsp_view(&info_rsp_buf, + data.size()); info_rsp_view.mutable_header()->type = static_cast<InformationType>(htole16(type_)); @@ -193,10 +190,10 @@ bool BrEdrCommandHandler::SendConfigurationRequest( auto on_config_rsp = BuildResponseHandler<ConfigurationResponse>(std::move(cb)); - common::DynamicByteBuffer config_req_buf(sizeof(ConfigurationRequestPayload) + - options.size()); - common::MutablePacketView<ConfigurationRequestPayload> config_req( - &config_req_buf, options.size()); + DynamicByteBuffer config_req_buf(sizeof(ConfigurationRequestPayload) + + options.size()); + MutablePacketView<ConfigurationRequestPayload> config_req(&config_req_buf, + options.size()); config_req.mutable_header()->dst_cid = htole16(remote_cid); config_req.mutable_header()->flags = htole16(flags); config_req.mutable_payload_data().Write(options); @@ -282,7 +279,7 @@ void BrEdrCommandHandler::ServeConfigurationRequest( return; } - common::PacketView<ConfigurationRequestPayload> config_req( + PacketView<ConfigurationRequestPayload> config_req( &request_payload, request_payload.size() - sizeof(ConfigurationRequestPayload)); const auto local_cid = diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_command_handler.h b/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_command_handler.h index 5d312ec67759e9a820374ddb29f1c3bb64e9f98d..3454e99b0619f7f095924bcec1a6bb6c310ea8f2 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_command_handler.h +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_command_handler.h @@ -99,7 +99,7 @@ class BrEdrCommandHandler final { friend class BrEdrCommandHandler; // Fills the reject fields of |rsp|. Returns true if successful. - bool ParseReject(const common::ByteBuffer& rej_payload_buf); + bool ParseReject(const ByteBuffer& rej_payload_buf); Status status_; ChannelId local_cid_ = kInvalidChannelId; @@ -113,7 +113,7 @@ class BrEdrCommandHandler final { static constexpr const char* kName = "Connection Response"; using Response::Response; // Inherit ctor - void Decode(const common::ByteBuffer& payload_buf); + void Decode(const ByteBuffer& payload_buf); ConnectionResult result() const { return result_; } ConnectionStatus conn_status() const { return conn_status_; } @@ -129,11 +129,11 @@ class BrEdrCommandHandler final { static constexpr const char* kName = "Configuration Response"; using Response::Response; // Inherit ctor - void Decode(const common::ByteBuffer& payload_buf); + void Decode(const ByteBuffer& payload_buf); uint16_t flags() const { return flags_; } ConfigurationResult result() const { return result_; } - const common::ByteBuffer& options() const { return options_; } + const ByteBuffer& options() const { return options_; } // TODO(BT-466): Replace raw option access with abstraction over parsed // options. @@ -146,7 +146,7 @@ class BrEdrCommandHandler final { // View into the raw options received from the peer. It is only valid for // the duration of the ConfigurationResponseCallback invocation. - common::BufferView options_; + BufferView options_; }; class DisconnectionResponse : public Response { @@ -155,7 +155,7 @@ class BrEdrCommandHandler final { static constexpr const char* kName = "Disconnection Response"; using Response::Response; // Inherit ctor - void Decode(const common::ByteBuffer& payload_buf); + void Decode(const ByteBuffer& payload_buf); }; class InformationResponse : public Response { @@ -164,7 +164,7 @@ class BrEdrCommandHandler final { static constexpr const char* kName = "Information Response"; using Response::Response; // Inherit ctor - void Decode(const common::ByteBuffer& payload_buf); + void Decode(const ByteBuffer& payload_buf); InformationType type() const { return type_; } InformationResult result() const { return result_; } @@ -193,7 +193,7 @@ class BrEdrCommandHandler final { // View into the payload received from the peer in host endianness. It is // only valid for the duration of the InformationResponseCallback // invocation. - common::BufferView data_; + BufferView data_; }; using ConnectionResponseCallback = @@ -248,7 +248,7 @@ class BrEdrCommandHandler final { ChannelId local_cid); void Send(ChannelId remote_cid, uint16_t flags, ConfigurationResult result, - const common::ByteBuffer& data); + const ByteBuffer& data); // TODO(NET-1084): Add builder abstraction for configuration options }; @@ -275,14 +275,14 @@ class BrEdrCommandHandler final { void SendFixedChannelsSupported(FixedChannelsSupported channels_supported); private: - void Send(InformationResult result, const common::ByteBuffer& data); + void Send(InformationResult result, const ByteBuffer& data); InformationType type_; }; using ConnectionRequestCallback = fit::function<void( PSM psm, ChannelId remote_cid, ConnectionResponder* responder)>; using ConfigurationRequestCallback = fit::function<void( - ChannelId local_cid, uint16_t flags, const common::ByteBuffer& options, + ChannelId local_cid, uint16_t flags, const ByteBuffer& options, ConfigurationResponder* responder)>; using DisconnectionRequestCallback = fit::function<void(ChannelId local_cid, ChannelId remote_cid, @@ -305,7 +305,7 @@ class BrEdrCommandHandler final { bool SendConnectionRequest(uint16_t psm, ChannelId local_cid, ConnectionResponseCallback cb); bool SendConfigurationRequest(ChannelId remote_cid, uint16_t flags, - const common::ByteBuffer& options, + const ByteBuffer& options, ConfigurationResponseCallback cb); bool SendDisconnectionRequest(ChannelId remote_cid, ChannelId local_cid, DisconnectionResponseCallback cb); diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_command_handler_unittest.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_command_handler_unittest.cc index 733a2e50737721d2c1812ec2794ac1df54219461..6d3517326d7175c5bfd1e6c805cb01a57bdce747 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_command_handler_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_command_handler_unittest.cc @@ -19,12 +19,6 @@ namespace l2cap { namespace internal { namespace { -using common::BufferView; -using common::ByteBuffer; -using common::CreateStaticByteBuffer; -using common::LowerBits; -using common::UpperBits; - constexpr uint16_t kPsm = 0x0001; constexpr ChannelId kLocalCId = 0x0040; constexpr ChannelId kRemoteCId = 0x60a3; @@ -392,7 +386,7 @@ TEST_F(L2CAP_BrEdrCommandHandlerTest, OutboundConfigReqRspPendingEmpty) { EXPECT_EQ(kLocalCId, rsp.local_cid()); EXPECT_EQ(0x0004, rsp.flags()); EXPECT_EQ(ConfigurationResult::kPending, rsp.result()); - EXPECT_TRUE(common::ContainersEqual(rsp_options, rsp.options())); + EXPECT_TRUE(ContainersEqual(rsp_options, rsp.options())); return false; }; diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_dynamic_channel.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_dynamic_channel.cc index ecc783ca170f4e6cc218ede13bc29f3b0411b227..fab86ef57bfcc97ee25e4167b99b04602a1dd75d 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_dynamic_channel.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_dynamic_channel.cc @@ -5,7 +5,6 @@ #include "bredr_dynamic_channel.h" #include <endian.h> - #include <zircon/assert.h> #include "src/connectivity/bluetooth/core/bt-host/common/log.h" @@ -78,7 +77,7 @@ void BrEdrDynamicChannelRegistry::OnRxConnReq( } void BrEdrDynamicChannelRegistry::OnRxConfigReq( - ChannelId local_cid, uint16_t flags, const common::ByteBuffer& options, + ChannelId local_cid, uint16_t flags, const ByteBuffer& options, BrEdrCommandHandler::ConfigurationResponder* responder) { auto channel = static_cast<BrEdrDynamicChannel*>(FindChannel(local_cid)); if (channel == nullptr) { @@ -243,7 +242,7 @@ bool BrEdrDynamicChannel::IsOpen() const { } void BrEdrDynamicChannel::OnRxConfigReq( - uint16_t flags, const common::ByteBuffer& options, + uint16_t flags, const ByteBuffer& options, BrEdrCommandHandler::ConfigurationResponder* responder) { bt_log(SPEW, "l2cap-bredr", "Channel %#.4x: Got Configuration Request", local_cid()); @@ -265,7 +264,7 @@ void BrEdrDynamicChannel::OnRxConfigReq( // TODO(NET-1084): Defer accepting config req using a Pending response state_ |= kRemoteConfigAccepted; responder->Send(remote_cid(), 0x0000, ConfigurationResult::kSuccess, - common::BufferView()); + BufferView()); bt_log(SPEW, "l2cap-bredr", "Channel %#.4x: Sent Configuration Response", local_cid()); @@ -349,7 +348,7 @@ void BrEdrDynamicChannel::TrySendLocalConfig() { BrEdrCommandHandler cmd_handler(signaling_channel_); if (!cmd_handler.SendConfigurationRequest( - remote_cid(), 0, common::BufferView(), + remote_cid(), 0, BufferView(), [self = weak_ptr_factory_.GetWeakPtr()](auto& rsp) { if (self) { return self->OnRxConfigRsp(rsp); diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_dynamic_channel.h b/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_dynamic_channel.h index 4851f5d513a125eaf3286985a21ca1569f4bb6d6..3ef326da0114ef7ce50f0916b393e594c21b8cf7 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_dynamic_channel.h +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_dynamic_channel.h @@ -5,10 +5,10 @@ #ifndef SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_L2CAP_BREDR_DYNAMIC_CHANNEL_H_ #define SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_L2CAP_BREDR_DYNAMIC_CHANNEL_H_ -#include <unordered_map> - #include <lib/fit/function.h> +#include <unordered_map> + #include "src/connectivity/bluetooth/core/bt-host/l2cap/bredr_command_handler.h" #include "src/connectivity/bluetooth/core/bt-host/l2cap/dynamic_channel_registry.h" #include "src/connectivity/bluetooth/core/bt-host/l2cap/l2cap.h" @@ -39,7 +39,7 @@ class BrEdrDynamicChannelRegistry final : public DynamicChannelRegistry { void OnRxConnReq(PSM psm, ChannelId remote_cid, BrEdrCommandHandler::ConnectionResponder* responder); void OnRxConfigReq(ChannelId local_cid, uint16_t flags, - const common::ByteBuffer& options, + const ByteBuffer& options, BrEdrCommandHandler::ConfigurationResponder* responder); void OnRxDisconReq(ChannelId local_cid, ChannelId remote_cid, BrEdrCommandHandler::DisconnectionResponder* responder); @@ -92,7 +92,7 @@ class BrEdrDynamicChannel final : public DynamicChannel { // Inbound request handlers. Request must have a destination channel ID that // matches this instance's |local_cid|. - void OnRxConfigReq(uint16_t flags, const common::ByteBuffer& options, + void OnRxConfigReq(uint16_t flags, const ByteBuffer& options, BrEdrCommandHandler::ConfigurationResponder* responder); void OnRxDisconReq(BrEdrCommandHandler::DisconnectionResponder* responder); diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_dynamic_channel_unittest.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_dynamic_channel_unittest.cc index 79141440225308616f19d5e77f6680adfdc4dad9..298224f819dc4d87757aed76f9be2c661fd7897b 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_dynamic_channel_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_dynamic_channel_unittest.cc @@ -17,9 +17,6 @@ namespace l2cap { namespace internal { namespace { -using common::LowerBits; -using common::UpperBits; - // TODO(NET-1093): Add integration test with FakeChannelTest and // BrEdrSignalingChannel using snooped connection data to verify signaling // channel traffic. @@ -32,45 +29,43 @@ constexpr ChannelId kBadCId = 0x003f; // Not a dynamic channel. // Commands Reject -const common::ByteBuffer& kRejNotUnderstood = common::CreateStaticByteBuffer( +const ByteBuffer& kRejNotUnderstood = CreateStaticByteBuffer( // Reject Reason (Not Understood) 0x00, 0x00); // Connection Requests -const common::ByteBuffer& kConnReq = common::CreateStaticByteBuffer( +const ByteBuffer& kConnReq = CreateStaticByteBuffer( // PSM LowerBits(kPsm), UpperBits(kPsm), // Source CID LowerBits(kLocalCId), UpperBits(kLocalCId)); -const common::ByteBuffer& kInboundConnReq = common::CreateStaticByteBuffer( +const ByteBuffer& kInboundConnReq = CreateStaticByteBuffer( // PSM LowerBits(kPsm), UpperBits(kPsm), // Source CID LowerBits(kRemoteCId), UpperBits(kRemoteCId)); -const common::ByteBuffer& kInboundInvalidPsmConnReq = - common::CreateStaticByteBuffer( - // PSM - LowerBits(kInvalidPsm), UpperBits(kInvalidPsm), +const ByteBuffer& kInboundInvalidPsmConnReq = CreateStaticByteBuffer( + // PSM + LowerBits(kInvalidPsm), UpperBits(kInvalidPsm), - // Source CID - LowerBits(kRemoteCId), UpperBits(kRemoteCId)); + // Source CID + LowerBits(kRemoteCId), UpperBits(kRemoteCId)); -const common::ByteBuffer& kInboundBadCIdConnReq = - common::CreateStaticByteBuffer( - // PSM - LowerBits(kPsm), UpperBits(kPsm), +const ByteBuffer& kInboundBadCIdConnReq = CreateStaticByteBuffer( + // PSM + LowerBits(kPsm), UpperBits(kPsm), - // Source CID - LowerBits(kBadCId), UpperBits(kBadCId)); + // Source CID + LowerBits(kBadCId), UpperBits(kBadCId)); // Connection Responses -const common::ByteBuffer& kPendingConnRsp = common::CreateStaticByteBuffer( +const ByteBuffer& kPendingConnRsp = CreateStaticByteBuffer( // Destination CID 0x00, 0x00, @@ -83,21 +78,20 @@ const common::ByteBuffer& kPendingConnRsp = common::CreateStaticByteBuffer( // Status (Authorization Pending) 0x02, 0x00); -const common::ByteBuffer& kPendingConnRspWithId = - common::CreateStaticByteBuffer( - // Destination CID (Wrong endianness but valid) - UpperBits(kRemoteCId), LowerBits(kRemoteCId), +const ByteBuffer& kPendingConnRspWithId = CreateStaticByteBuffer( + // Destination CID (Wrong endianness but valid) + UpperBits(kRemoteCId), LowerBits(kRemoteCId), - // Source CID - LowerBits(kLocalCId), UpperBits(kLocalCId), + // Source CID + LowerBits(kLocalCId), UpperBits(kLocalCId), - // Result (Pending) - 0x01, 0x00, + // Result (Pending) + 0x01, 0x00, - // Status (Authorization Pending) - 0x02, 0x00); + // Status (Authorization Pending) + 0x02, 0x00); -const common::ByteBuffer& kOkConnRsp = common::CreateStaticByteBuffer( +const ByteBuffer& kOkConnRsp = CreateStaticByteBuffer( // Destination CID LowerBits(kRemoteCId), UpperBits(kRemoteCId), @@ -110,7 +104,7 @@ const common::ByteBuffer& kOkConnRsp = common::CreateStaticByteBuffer( // Status (No further information available) 0x00, 0x00); -const common::ByteBuffer& kInvalidConnRsp = common::CreateStaticByteBuffer( +const ByteBuffer& kInvalidConnRsp = CreateStaticByteBuffer( // Destination CID (Not a dynamic channel ID) LowerBits(kBadCId), UpperBits(kBadCId), @@ -123,7 +117,7 @@ const common::ByteBuffer& kInvalidConnRsp = common::CreateStaticByteBuffer( // Status (No further information available) 0x00, 0x00); -const common::ByteBuffer& kRejectConnRsp = common::CreateStaticByteBuffer( +const ByteBuffer& kRejectConnRsp = CreateStaticByteBuffer( // Destination CID (Invalid) LowerBits(kInvalidChannelId), UpperBits(kInvalidChannelId), @@ -136,7 +130,7 @@ const common::ByteBuffer& kRejectConnRsp = common::CreateStaticByteBuffer( // Status (No further information available) 0x00, 0x00); -const common::ByteBuffer& kInboundOkConnRsp = common::CreateStaticByteBuffer( +const ByteBuffer& kInboundOkConnRsp = CreateStaticByteBuffer( // Destination CID LowerBits(kLocalCId), UpperBits(kLocalCId), @@ -149,44 +143,42 @@ const common::ByteBuffer& kInboundOkConnRsp = common::CreateStaticByteBuffer( // Status (No further information available) 0x00, 0x00); -const common::ByteBuffer& kInboundBadPsmConnRsp = - common::CreateStaticByteBuffer( - // Destination CID (Invalid) - 0x00, 0x00, +const ByteBuffer& kInboundBadPsmConnRsp = CreateStaticByteBuffer( + // Destination CID (Invalid) + 0x00, 0x00, - // Source CID - LowerBits(kRemoteCId), UpperBits(kRemoteCId), + // Source CID + LowerBits(kRemoteCId), UpperBits(kRemoteCId), - // Result (PSM Not Supported) - 0x02, 0x00, + // Result (PSM Not Supported) + 0x02, 0x00, - // Status (No further information available) - 0x00, 0x00); + // Status (No further information available) + 0x00, 0x00); -const common::ByteBuffer& kInboundBadCIdConnRsp = - common::CreateStaticByteBuffer( - // Destination CID (Invalid) - 0x00, 0x00, +const ByteBuffer& kInboundBadCIdConnRsp = CreateStaticByteBuffer( + // Destination CID (Invalid) + 0x00, 0x00, - // Source CID - LowerBits(kBadCId), UpperBits(kBadCId), + // Source CID + LowerBits(kBadCId), UpperBits(kBadCId), - // Result (Invalid Source CID) - 0x06, 0x00, + // Result (Invalid Source CID) + 0x06, 0x00, - // Status (No further information available) - 0x00, 0x00); + // Status (No further information available) + 0x00, 0x00); // Disconnection Requests -const common::ByteBuffer& kDisconReq = common::CreateStaticByteBuffer( +const ByteBuffer& kDisconReq = CreateStaticByteBuffer( // Destination CID LowerBits(kRemoteCId), UpperBits(kRemoteCId), // Source CID LowerBits(kLocalCId), UpperBits(kLocalCId)); -const common::ByteBuffer& kInboundDisconReq = common::CreateStaticByteBuffer( +const ByteBuffer& kInboundDisconReq = CreateStaticByteBuffer( // Destination CID LowerBits(kLocalCId), UpperBits(kLocalCId), @@ -195,20 +187,20 @@ const common::ByteBuffer& kInboundDisconReq = common::CreateStaticByteBuffer( // Disconnection Responses -const common::ByteBuffer& kInboundDisconRsp = kInboundDisconReq; +const ByteBuffer& kInboundDisconRsp = kInboundDisconReq; -const common::ByteBuffer& kDisconRsp = kDisconReq; +const ByteBuffer& kDisconRsp = kDisconReq; // Configuration Requests -const common::ByteBuffer& kConfigReq = common::CreateStaticByteBuffer( +const ByteBuffer& kConfigReq = CreateStaticByteBuffer( // Destination CID LowerBits(kRemoteCId), UpperBits(kRemoteCId), // Flags 0x00, 0x00); -const common::ByteBuffer& kInboundConfigReq = common::CreateStaticByteBuffer( +const ByteBuffer& kInboundConfigReq = CreateStaticByteBuffer( // Destination CID LowerBits(kLocalCId), UpperBits(kLocalCId), @@ -217,7 +209,7 @@ const common::ByteBuffer& kInboundConfigReq = common::CreateStaticByteBuffer( // Configuration Responses -const common::ByteBuffer& kOkConfigRsp = common::CreateStaticByteBuffer( +const ByteBuffer& kOkConfigRsp = CreateStaticByteBuffer( // Source CID LowerBits(kLocalCId), UpperBits(kLocalCId), @@ -227,7 +219,7 @@ const common::ByteBuffer& kOkConfigRsp = common::CreateStaticByteBuffer( // Result (Successful) 0x00, 0x00); -const common::ByteBuffer& kUnknownIdConfigRsp = common::CreateStaticByteBuffer( +const ByteBuffer& kUnknownIdConfigRsp = CreateStaticByteBuffer( // Source CID (Invalid) LowerBits(kBadCId), UpperBits(kBadCId), @@ -237,7 +229,7 @@ const common::ByteBuffer& kUnknownIdConfigRsp = common::CreateStaticByteBuffer( // Result (Successful) 0x00, 0x00); -const common::ByteBuffer& kPendingConfigRsp = common::CreateStaticByteBuffer( +const ByteBuffer& kPendingConfigRsp = CreateStaticByteBuffer( // Source CID LowerBits(kRemoteCId), UpperBits(kRemoteCId), @@ -247,7 +239,7 @@ const common::ByteBuffer& kPendingConfigRsp = common::CreateStaticByteBuffer( // Result (Pending) 0x04, 0x00); -const common::ByteBuffer& kInboundOkConfigRsp = common::CreateStaticByteBuffer( +const ByteBuffer& kInboundOkConfigRsp = CreateStaticByteBuffer( // Source CID LowerBits(kRemoteCId), UpperBits(kRemoteCId), diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_signaling_channel.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_signaling_channel.cc index c5d07c65df7760a7ea2477c9cc8484da533b4e28..d52eaccc14048e6fb8160c2c1bb8dac277d69656 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_signaling_channel.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_signaling_channel.cc @@ -4,10 +4,10 @@ #include "src/connectivity/bluetooth/core/bt-host/l2cap/bredr_signaling_channel.h" -#include "src/connectivity/bluetooth/core/bt-host/common/log.h" - #include <zircon/compiler.h> +#include "src/connectivity/bluetooth/core/bt-host/common/log.h" + namespace bt { namespace l2cap { namespace internal { @@ -19,13 +19,13 @@ BrEdrSignalingChannel::BrEdrSignalingChannel(fbl::RefPtr<Channel> chan, // Add default handler for incoming Echo Request commands. ServeRequest(kEchoRequest, - [](const common::ByteBuffer& req_payload, Responder* responder) { + [](const ByteBuffer& req_payload, Responder* responder) { responder->Send(req_payload); }); } bool BrEdrSignalingChannel::SendRequest(CommandCode req_code, - const common::ByteBuffer& payload, + const ByteBuffer& payload, ResponseHandler cb) { ZX_DEBUG_ASSERT(cb); const CommandId id = EnqueueResponse(req_code + 1, std::move(cb)); @@ -46,21 +46,20 @@ void BrEdrSignalingChannel::ServeRequest(CommandCode req_code, // This is implemented as v5.0 Vol 3, Part A Section 4.8: "These requests may be // used for testing the link or for passing vendor specific information using // the optional data field." -bool BrEdrSignalingChannel::TestLink(const common::ByteBuffer& data, - DataCallback cb) { - return SendRequest(kEchoRequest, data, - [cb = std::move(cb)]( - Status status, const common::ByteBuffer& rsp_payload) { - if (status == Status::kSuccess) { - cb(rsp_payload); - } else { - cb(common::BufferView()); - } - return false; - }); +bool BrEdrSignalingChannel::TestLink(const ByteBuffer& data, DataCallback cb) { + return SendRequest( + kEchoRequest, data, + [cb = std::move(cb)](Status status, const ByteBuffer& rsp_payload) { + if (status == Status::kSuccess) { + cb(rsp_payload); + } else { + cb(BufferView()); + } + return false; + }); } -void BrEdrSignalingChannel::DecodeRxUnit(common::ByteBufferPtr sdu, +void BrEdrSignalingChannel::DecodeRxUnit(ByteBufferPtr sdu, const SignalingPacketHandler& cb) { // "Multiple commands may be sent in a single C-frame over Fixed Channel CID // 0x0001 (ACL-U) (v5.0, Vol 3, Part A, Section 4)" @@ -82,7 +81,7 @@ void BrEdrSignalingChannel::DecodeRxUnit(common::ByteBufferPtr sdu, bt_log(TRACE, "l2cap-bredr", "sig: expected more bytes (%zu < %u); drop", remaining_sdu_length, expected_payload_length); SendCommandReject(packet.header().id, RejectReason::kNotUnderstood, - common::BufferView()); + BufferView()); return; } @@ -176,7 +175,7 @@ void BrEdrSignalingChannel::OnRxResponse(const SignalingPacket& packet) { bt_log(SPEW, "l2cap-bredr", "sig: ignoring unexpected response, id %#.2x", packet.header().id); SendCommandReject(packet.header().id, RejectReason::kNotUnderstood, - common::BufferView()); + BufferView()); return; } @@ -190,7 +189,7 @@ void BrEdrSignalingChannel::OnRxResponse(const SignalingPacket& packet) { "sig: response (id %#.2x) has unexpected code %#.2x", packet.header().id, packet.header().code); SendCommandReject(packet.header().id, RejectReason::kNotUnderstood, - common::BufferView()); + BufferView()); return; } diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_signaling_channel.h b/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_signaling_channel.h index cc2bdb0716a358395a04046fa4886d44568a5ec7..1137301c69b24c5d1812d275405b7e430ecab516 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_signaling_channel.h +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_signaling_channel.h @@ -24,7 +24,7 @@ class BrEdrSignalingChannel final : public SignalingChannel { // SignalingChannelInterface overrides // TODO(NET-1093): Refactor implementation into SignalingChannel so it's // shared with LESignalingChannel. - bool SendRequest(CommandCode req_code, const common::ByteBuffer& payload, + bool SendRequest(CommandCode req_code, const ByteBuffer& payload, ResponseHandler cb) override; void ServeRequest(CommandCode req_code, RequestDelegate cb) override; @@ -33,11 +33,11 @@ class BrEdrSignalingChannel final : public SignalingChannel { // payload (if any) on the L2CAP thread, or with an empty buffer if the // remote responded with a rejection. Returns false if the request failed to // send. - bool TestLink(const common::ByteBuffer& data, DataCallback cb); + bool TestLink(const ByteBuffer& data, DataCallback cb); private: // SignalingChannel overrides - void DecodeRxUnit(common::ByteBufferPtr sdu, + void DecodeRxUnit(ByteBufferPtr sdu, const SignalingPacketHandler& cb) override; bool HandlePacket(const SignalingPacket& packet) override; diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_signaling_channel_unittest.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_signaling_channel_unittest.cc index a5c03b413428fe9e8c3700126767c60219358423..665dbe0247c7f24f666517c364ca39ad6011a563 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_signaling_channel_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/bredr_signaling_channel_unittest.cc @@ -4,9 +4,8 @@ #include "bredr_signaling_channel.h" -#include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" - #include "fake_channel_test.h" +#include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" namespace bt { namespace l2cap { @@ -46,15 +45,15 @@ class L2CAP_BrEdrSignalingChannelTest : public testing::FakeChannelTest { }; TEST_F(L2CAP_BrEdrSignalingChannelTest, RegisterRequestResponder) { - const common::ByteBuffer& remote_req = common::CreateStaticByteBuffer( + const ByteBuffer& remote_req = CreateStaticByteBuffer( // Disconnection Request. 0x06, 0x01, 0x04, 0x00, // Payload 0x0A, 0x00, 0x08, 0x00); - const common::BufferView& expected_payload = remote_req.view(4, 4); + const BufferView& expected_payload = remote_req.view(4, 4); - auto expected_rej = common::CreateStaticByteBuffer( + auto expected_rej = CreateStaticByteBuffer( // Command header (Command rejected, length 2) 0x01, 0x01, 0x02, 0x00, @@ -69,14 +68,14 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, RegisterRequestResponder) { bool cb_called = false; sig()->ServeRequest( kDisconnectionRequest, - [&cb_called, &expected_payload](const common::ByteBuffer& req_payload, + [&cb_called, &expected_payload](const ByteBuffer& req_payload, SignalingChannel::Responder* responder) { cb_called = true; - EXPECT_TRUE(common::ContainersEqual(expected_payload, req_payload)); + EXPECT_TRUE(ContainersEqual(expected_payload, req_payload)); responder->Send(req_payload); }); - const common::ByteBuffer& local_rsp = common::CreateStaticByteBuffer( + const ByteBuffer& local_rsp = CreateStaticByteBuffer( // Disconnection Response. 0x07, 0x01, 0x04, 0x00, @@ -89,7 +88,7 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, RegisterRequestResponder) { } TEST_F(L2CAP_BrEdrSignalingChannelTest, RespondsToEchoRequest) { - auto cmd = common::CreateStaticByteBuffer( + auto cmd = CreateStaticByteBuffer( // Command header (Echo Request, length 1) 0x08, kTestCmdId, 0x01, 0x00, @@ -112,14 +111,14 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, RespondsToEchoRequest) { } TEST_F(L2CAP_BrEdrSignalingChannelTest, RejectUnsolicitedEchoResponse) { - auto cmd = common::CreateStaticByteBuffer( + auto cmd = CreateStaticByteBuffer( // Command header (Echo Response, length 1) 0x09, kTestCmdId, 0x01, 0x00, // Payload 0x23); - auto expected = common::CreateStaticByteBuffer( + auto expected = CreateStaticByteBuffer( // Command header (Command rejected, length 2) 0x01, kTestCmdId, 0x02, 0x00, @@ -134,7 +133,7 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, IgnoreEmptyFrame) { auto send_cb = [&send_cb_called](auto) { send_cb_called = true; }; fake_chan()->SetSendCallback(std::move(send_cb), dispatcher()); - fake_chan()->Receive(common::BufferView()); + fake_chan()->Receive(BufferView()); RunLoopUntilIdle(); EXPECT_FALSE(send_cb_called); @@ -146,7 +145,7 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, RejectMalformedAdditionalCommand) { // Echo Request (see other test for command support), followed by an // incomplete command packet - auto cmd = common::CreateStaticByteBuffer( + auto cmd = CreateStaticByteBuffer( // Command header (length 3) 0x08, kTestId0, 0x03, 0x00, @@ -157,7 +156,7 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, RejectMalformedAdditionalCommand) { 0x08, kTestId1, 0x01, 0x00); // Echo Response packet - auto rsp0 = common::CreateStaticByteBuffer( + auto rsp0 = CreateStaticByteBuffer( // Command header (length 3) 0x09, kTestId0, 0x03, 0x00, @@ -165,7 +164,7 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, RejectMalformedAdditionalCommand) { 'L', 'O', 'L'); // Command Reject packet - auto rsp1 = common::CreateStaticByteBuffer( + auto rsp1 = CreateStaticByteBuffer( // Command header 0x01, kTestId1, 0x02, 0x00, @@ -175,9 +174,9 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, RejectMalformedAdditionalCommand) { int cb_times_called = 0; auto send_cb = [&rsp0, &rsp1, &cb_times_called](auto packet) { if (cb_times_called == 0) { - EXPECT_TRUE(common::ContainersEqual(rsp0, *packet)); + EXPECT_TRUE(ContainersEqual(rsp0, *packet)); } else if (cb_times_called == 1) { - EXPECT_TRUE(common::ContainersEqual(rsp1, *packet)); + EXPECT_TRUE(ContainersEqual(rsp1, *packet)); } cb_times_called++; @@ -195,7 +194,7 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, HandleMultipleCommands) { constexpr uint8_t kTestId1 = 15; constexpr uint8_t kTestId2 = 16; - auto cmd = common::CreateStaticByteBuffer( + auto cmd = CreateStaticByteBuffer( // Command header (Echo Request) 0x08, kTestId0, 0x04, 0x00, @@ -214,21 +213,21 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, HandleMultipleCommands) { // Additional command fragment to be dropped 0xFF, 0x00); - auto echo_rsp0 = common::CreateStaticByteBuffer( + auto echo_rsp0 = CreateStaticByteBuffer( // Command header (Echo Response) 0x09, kTestId0, 0x04, 0x00, // Payload data 'L', 'O', 'L', 'Z'); - auto reject_rsp1 = common::CreateStaticByteBuffer( + auto reject_rsp1 = CreateStaticByteBuffer( // Command header (Command Rejected) 0x01, kTestId1, 0x02, 0x00, // Reason (Command not understood) 0x00, 0x00); - auto echo_rsp2 = common::CreateStaticByteBuffer( + auto echo_rsp2 = CreateStaticByteBuffer( // Command header (Echo Response) 0x09, kTestId2, 0x00, 0x00); @@ -236,11 +235,11 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, HandleMultipleCommands) { auto send_cb = [&echo_rsp0, &reject_rsp1, &echo_rsp2, &cb_times_called](auto packet) { if (cb_times_called == 0) { - EXPECT_TRUE(common::ContainersEqual(echo_rsp0, *packet)); + EXPECT_TRUE(ContainersEqual(echo_rsp0, *packet)); } else if (cb_times_called == 1) { - EXPECT_TRUE(common::ContainersEqual(reject_rsp1, *packet)); + EXPECT_TRUE(ContainersEqual(reject_rsp1, *packet)); } else if (cb_times_called == 2) { - EXPECT_TRUE(common::ContainersEqual(echo_rsp2, *packet)); + EXPECT_TRUE(ContainersEqual(echo_rsp2, *packet)); } cb_times_called++; @@ -254,34 +253,34 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, HandleMultipleCommands) { } TEST_F(L2CAP_BrEdrSignalingChannelTest, SendAndReceiveEcho) { - const common::ByteBuffer& expected_req = common::CreateStaticByteBuffer( + const ByteBuffer& expected_req = CreateStaticByteBuffer( // Echo request with 3-byte payload. 0x08, 0x01, 0x03, 0x00, // Payload 'P', 'W', 'N'); - const common::BufferView req_data = expected_req.view(4, 3); + const BufferView req_data = expected_req.view(4, 3); // Check the request sent. bool tx_success = false; fake_chan()->SetSendCallback( [&expected_req, &tx_success](auto cb_packet) { - tx_success = common::ContainersEqual(expected_req, *cb_packet); + tx_success = ContainersEqual(expected_req, *cb_packet); }, dispatcher()); - const common::ByteBuffer& expected_rsp = common::CreateStaticByteBuffer( + const ByteBuffer& expected_rsp = CreateStaticByteBuffer( // Echo response with 4-byte payload. 0x09, 0x01, 0x04, 0x00, // Payload 'L', '3', '3', 'T'); - const common::BufferView rsp_data = expected_rsp.view(4, 4); + const BufferView rsp_data = expected_rsp.view(4, 4); bool rx_success = false; EXPECT_TRUE( sig()->TestLink(req_data, [&rx_success, &rsp_data](const auto& data) { - rx_success = common::ContainersEqual(rsp_data, data); + rx_success = ContainersEqual(rsp_data, data); })); RunLoopUntilIdle(); @@ -298,7 +297,7 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, SendAndReceiveEcho) { } TEST_F(L2CAP_BrEdrSignalingChannelTest, RejectUnhandledResponseCommand) { - auto cmd = common::CreateStaticByteBuffer( + auto cmd = CreateStaticByteBuffer( // Command header (Information Response, length 4) 0x0B, kTestCmdId, 0x04, 0x00, @@ -308,7 +307,7 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, RejectUnhandledResponseCommand) { // Result (Not supported) 0x01, 0x00); - auto expected = common::CreateStaticByteBuffer( + auto expected = CreateStaticByteBuffer( // Command header (Command rejected, length 2) 0x01, kTestCmdId, 0x02, 0x00, @@ -321,13 +320,13 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, RejectUnhandledResponseCommand) { TEST_F(L2CAP_BrEdrSignalingChannelTest, RejectRemoteResponseInvalidId) { // Remote's echo response that has a different ID to what will be in the // request header (see SendAndReceiveEcho). - const common::ByteBuffer& rsp_invalid_id = common::CreateStaticByteBuffer( + const ByteBuffer& rsp_invalid_id = CreateStaticByteBuffer( // Echo response with 4-byte payload. 0x09, 0x02, 0x04, 0x00, // Payload 'L', '3', '3', 'T'); - const common::BufferView req_data = rsp_invalid_id.view(4, 4); + const BufferView req_data = rsp_invalid_id.view(4, 4); bool tx_success = false; fake_chan()->SetSendCallback([&tx_success](auto) { tx_success = true; }, @@ -340,7 +339,7 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, RejectRemoteResponseInvalidId) { RunLoopUntilIdle(); EXPECT_TRUE(tx_success); - const common::ByteBuffer& reject_rsp = common::CreateStaticByteBuffer( + const ByteBuffer& reject_rsp = CreateStaticByteBuffer( // Command header (Command Rejected) 0x01, 0x02, 0x02, 0x00, @@ -349,7 +348,7 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, RejectRemoteResponseInvalidId) { bool reject_sent = false; fake_chan()->SetSendCallback( [&reject_rsp, &reject_sent](auto cb_packet) { - reject_sent = common::ContainersEqual(reject_rsp, *cb_packet); + reject_sent = ContainersEqual(reject_rsp, *cb_packet); }, dispatcher()); @@ -362,14 +361,13 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, RejectRemoteResponseInvalidId) { TEST_F(L2CAP_BrEdrSignalingChannelTest, RejectRemoteResponseWrongType) { // Remote's response with the correct ID but wrong type of response. - const common::ByteBuffer& rsp_invalid_id = common::CreateStaticByteBuffer( + const ByteBuffer& rsp_invalid_id = CreateStaticByteBuffer( // Disconnection Response with plausible 4-byte payload. 0x07, 0x01, 0x04, 0x00, // Payload 0x0A, 0x00, 0x08, 0x00); - const common::ByteBuffer& req_data = - common::CreateStaticByteBuffer('P', 'W', 'N'); + const ByteBuffer& req_data = CreateStaticByteBuffer('P', 'W', 'N'); bool tx_success = false; fake_chan()->SetSendCallback([&tx_success](auto) { tx_success = true; }, @@ -382,7 +380,7 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, RejectRemoteResponseWrongType) { RunLoopUntilIdle(); EXPECT_TRUE(tx_success); - const common::ByteBuffer& reject_rsp = common::CreateStaticByteBuffer( + const ByteBuffer& reject_rsp = CreateStaticByteBuffer( // Command header (Command Rejected) 0x01, 0x01, 0x02, 0x00, @@ -391,7 +389,7 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, RejectRemoteResponseWrongType) { bool reject_sent = false; fake_chan()->SetSendCallback( [&reject_rsp, &reject_sent](auto cb_packet) { - reject_sent = common::ContainersEqual(reject_rsp, *cb_packet); + reject_sent = ContainersEqual(reject_rsp, *cb_packet); }, dispatcher()); @@ -418,8 +416,8 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, ReuseCommandIds) { }; fake_chan()->SetSendCallback(std::move(check_header_id), dispatcher()); - const common::ByteBuffer& req_data = - common::CreateStaticByteBuffer('y', 'o', 'o', 'o', 'o', '\0'); + const ByteBuffer& req_data = + CreateStaticByteBuffer('y', 'o', 'o', 'o', 'o', '\0'); for (int i = 0; i < 255; i++) { EXPECT_TRUE(sig()->TestLink(req_data, [](auto&) {})); @@ -433,7 +431,7 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, ReuseCommandIds) { EXPECT_EQ(255, req_count); // Remote finally responds to a request, but not in order requests were sent. - const common::ByteBuffer& echo_rsp = common::CreateStaticByteBuffer( + const ByteBuffer& echo_rsp = CreateStaticByteBuffer( // Echo response with no payload. 0x09, 0x0c, 0x00, 0x00); fake_chan()->Receive(echo_rsp); @@ -449,7 +447,7 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, ReuseCommandIds) { // Ensure that the signaling channel plumbs a rejection command from remote to // the appropriate response handler. TEST_F(L2CAP_BrEdrSignalingChannelTest, EchoRemoteRejection) { - const common::ByteBuffer& reject_rsp = common::CreateStaticByteBuffer( + const ByteBuffer& reject_rsp = CreateStaticByteBuffer( // Command header (Command Rejected) 0x01, 0x01, 0x02, 0x00, @@ -460,13 +458,12 @@ TEST_F(L2CAP_BrEdrSignalingChannelTest, EchoRemoteRejection) { fake_chan()->SetSendCallback([&tx_success](auto) { tx_success = true; }, dispatcher()); - const common::ByteBuffer& req_data = common::CreateStaticByteBuffer('h', 'i'); + const ByteBuffer& req_data = CreateStaticByteBuffer('h', 'i'); bool rx_success = false; - EXPECT_TRUE( - sig()->TestLink(req_data, [&rx_success](const common::ByteBuffer& data) { - rx_success = true; - EXPECT_EQ(0U, data.size()); - })); + EXPECT_TRUE(sig()->TestLink(req_data, [&rx_success](const ByteBuffer& data) { + rx_success = true; + EXPECT_EQ(0U, data.size()); + })); RunLoopUntilIdle(); EXPECT_TRUE(tx_success); diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/channel.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/channel.cc index eaabfc1bf3f51e4c635f386d169bd819a8f45ec9..bbed2aecf00bc04c07cba3c7579b2d20d2c0758f 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/channel.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/channel.cc @@ -6,19 +6,16 @@ #include <zircon/assert.h> +#include "logical_link.h" #include "src/connectivity/bluetooth/core/bt-host/common/log.h" #include "src/connectivity/bluetooth/core/bt-host/common/run_or_post.h" #include "src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_rx_engine.h" #include "src/connectivity/bluetooth/core/bt-host/l2cap/basic_mode_tx_engine.h" #include "src/lib/fxl/strings/string_printf.h" -#include "logical_link.h" - namespace bt { namespace l2cap { -using common::RunOrPost; - Channel::Channel(ChannelId id, ChannelId remote_id, hci::Connection::LinkType link_type, hci::ConnectionHandle link_handle) @@ -56,7 +53,7 @@ ChannelImpl::ChannelImpl(ChannelId id, ChannelId remote_id, })) { ZX_DEBUG_ASSERT(link_); for (const auto& pdu : buffered_pdus) { - auto sdu = std::make_unique<common::DynamicByteBuffer>(pdu.length()); + auto sdu = std::make_unique<DynamicByteBuffer>(pdu.length()); pdu.Copy(sdu.get()); pending_rx_sdus_.push(std::move(sdu)); } @@ -154,7 +151,7 @@ void ChannelImpl::SignalLinkError() { }); } -bool ChannelImpl::Send(common::ByteBufferPtr sdu) { +bool ChannelImpl::Send(ByteBufferPtr sdu) { ZX_DEBUG_ASSERT(sdu); std::lock_guard<std::mutex> lock(mtx_); @@ -224,7 +221,7 @@ void ChannelImpl::HandleRxPdu(PDU&& pdu) { ZX_DEBUG_ASSERT(link_); ZX_DEBUG_ASSERT(rx_engine_); - common::ByteBufferPtr sdu = rx_engine_->ProcessPdu(std::move(pdu)); + ByteBufferPtr sdu = rx_engine_->ProcessPdu(std::move(pdu)); if (!sdu) { // The PDU may have been invalid, out-of-sequence, or part of a segmented // SDU. diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/channel.h b/src/connectivity/bluetooth/core/bt-host/l2cap/channel.h index dab6c0e6644eacac7489b3f1f2f677a1b1da30f1..618e7f18c0ee6c4f893e2583786f3b243d98c2d7 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/channel.h +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/channel.h @@ -104,7 +104,7 @@ class Channel : public fbl::RefCounted<Channel> { // Callback invoked when a new packet is received on this channel. Any // previously buffered packets will be sent to |rx_cb| right away, provided // that |rx_cb| is not empty and the underlying logical link is active. - using RxCallback = fit::function<void(common::ByteBufferPtr packet)>; + using RxCallback = fit::function<void(ByteBufferPtr packet)>; // Activates this channel assigning |dispatcher| to execute |rx_callback| and // |closed_callback|. @@ -150,7 +150,7 @@ class Channel : public fbl::RefCounted<Channel> { // TxEngine's QueueSdu() method. Note: a successfully enqueued SDU may still // fail to reach the receiver, due to asynchronous local errors, transmission // failure, or remote errors. - virtual bool Send(common::ByteBufferPtr sdu) = 0; + virtual bool Send(ByteBufferPtr sdu) = 0; protected: friend class fbl::RefPtr<Channel>; @@ -184,7 +184,7 @@ class ChannelImpl : public Channel { async_dispatcher_t* dispatcher) override; void Deactivate() override; void SignalLinkError() override; - bool Send(common::ByteBufferPtr sdu) override; + bool Send(ByteBufferPtr sdu) override; void UpgradeSecurity(sm::SecurityLevel level, sm::StatusCallback callback) override; @@ -236,8 +236,8 @@ class ChannelImpl : public Channel { // TODO(armansito): We should avoid STL containers for data packets as they // all implicitly allocate. This is a reminder to fix this elsewhere // (especially in the HCI layer). - std::queue<common::ByteBufferPtr, std::list<common::ByteBufferPtr>> - pending_rx_sdus_ __TA_GUARDED(mtx_); + std::queue<ByteBufferPtr, std::list<ByteBufferPtr>> pending_rx_sdus_ + __TA_GUARDED(mtx_); DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(ChannelImpl); }; diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/channel_manager.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/channel_manager.cc index c52f904bf75363456d0c9f32d0cee6856f5d68fa..1d78e2d417b122cbeb6fb8634ce6caedd2ede14e 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/channel_manager.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/channel_manager.cc @@ -6,11 +6,10 @@ #include <zircon/assert.h> +#include "logical_link.h" #include "src/connectivity/bluetooth/core/bt-host/common/log.h" #include "src/lib/fxl/strings/string_printf.h" -#include "logical_link.h" - namespace bt { namespace l2cap { @@ -186,8 +185,7 @@ void ChannelManager::OnACLDataReceived(hci::ACLDataPacketPtr packet) { // If a LogicalLink does not exist, we set up a queue for its packets to be // delivered when the LogicalLink gets created. if (iter == ll_map_.end()) { - pp_iter = pending_packets_ - .emplace(handle, common::LinkedList<hci::ACLDataPacket>()) + pp_iter = pending_packets_.emplace(handle, LinkedList<hci::ACLDataPacket>()) .first; } else { // A logical link exists. |pp_iter| will be valid only if the drain task has diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/channel_manager.h b/src/connectivity/bluetooth/core/bt-host/l2cap/channel_manager.h index 183994d2b03759b59227bb854ac8cebd3e0a75f2..f4395fd8fb34c3291d7b162ec26a3463a7df325a 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/channel_manager.h +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/channel_manager.h @@ -160,8 +160,7 @@ class ChannelManager final { // Stores packets received on a connection handle before a link for it has // been created. using PendingPacketMap = - std::unordered_map<hci::ConnectionHandle, - common::LinkedList<hci::ACLDataPacket>>; + std::unordered_map<hci::ConnectionHandle, LinkedList<hci::ACLDataPacket>>; PendingPacketMap pending_packets_; // Store information required to create and forward channels for locally- diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/channel_manager_unittest.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/channel_manager_unittest.cc index a139d7e651c0560a9d49e1ae25a24f3133c11886..c7a9b5eccfe107a33b3fc3fc01473a9852dd39af 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/channel_manager_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/channel_manager_unittest.cc @@ -20,14 +20,12 @@ namespace { using bt::testing::TestController; using TestingBase = bt::testing::FakeControllerTest<TestController>; -using common::HostError; - constexpr hci::ConnectionHandle kTestHandle1 = 0x0001; constexpr hci::ConnectionHandle kTestHandle2 = 0x0002; constexpr PSM kTestPsm = 0x0001; void DoNothing() {} -void NopRxCallback(common::ByteBufferPtr) {} +void NopRxCallback(ByteBufferPtr) {} void NopLeConnParamCallback(const hci::LEPreferredConnectionParameters&) {} void NopSecurityCallback(hci::ConnectionHandle, sm::SecurityLevel, sm::StatusCallback) {} @@ -240,7 +238,7 @@ TEST_F(L2CAP_ChannelManagerTest, SendingPacketDuringCleanUpHasNoEffect) { // Send a packet. This should be posted on the L2CAP dispatcher but not // processed yet. - EXPECT_TRUE(chan->Send(common::NewBuffer('h', 'i'))); + EXPECT_TRUE(chan->Send(NewBuffer('h', 'i'))); ASSERT_FALSE(data_sent); chanmgr()->Unregister(kTestHandle1); @@ -268,7 +266,7 @@ TEST_F(L2CAP_ChannelManagerTest, DestroyingChannelManagerCleansUpChannels) { // Send a packet. This should be posted on the L2CAP dispatcher but not // processed yet. - EXPECT_TRUE(chan->Send(common::NewBuffer('h', 'i'))); + EXPECT_TRUE(chan->Send(NewBuffer('h', 'i'))); ASSERT_FALSE(data_sent); TearDown(); @@ -310,13 +308,13 @@ TEST_F(L2CAP_ChannelManagerTest, ReceiveData) { // We use the ATT channel to control incoming packets and the SMP channel to // quit the message loop. std::vector<std::string> sdus; - auto att_rx_cb = [&sdus](common::ByteBufferPtr sdu) { + auto att_rx_cb = [&sdus](ByteBufferPtr sdu) { ZX_DEBUG_ASSERT(sdu); sdus.push_back(sdu->ToString()); }; bool smp_cb_called = false; - auto smp_rx_cb = [&smp_cb_called, this](common::ByteBufferPtr sdu) { + auto smp_rx_cb = [&smp_cb_called, this](ByteBufferPtr sdu) { ZX_DEBUG_ASSERT(sdu); EXPECT_EQ(0u, sdu->size()); smp_cb_called = true; @@ -330,19 +328,19 @@ TEST_F(L2CAP_ChannelManagerTest, ReceiveData) { ASSERT_TRUE(smp_chan); // ATT channel - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (starting fragment) 0x01, 0x00, 0x09, 0x00, // L2CAP B-frame 0x05, 0x00, 0x04, 0x00, 'h', 'e', 'l', 'l', 'o')); - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (starting fragment) 0x01, 0x00, 0x09, 0x00, // L2CAP B-frame (partial) 0x0C, 0x00, 0x04, 0x00, 'h', 'o', 'w', ' ', 'a')); - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (continuing fragment) 0x01, 0x10, 0x07, 0x00, @@ -350,7 +348,7 @@ TEST_F(L2CAP_ChannelManagerTest, ReceiveData) { 'r', 'e', ' ', 'y', 'o', 'u', '?')); // SMP channel - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (starting fragment) 0x01, 0x00, 0x04, 0x00, @@ -368,17 +366,15 @@ TEST_F(L2CAP_ChannelManagerTest, ReceiveData) { TEST_F(L2CAP_ChannelManagerTest, ReceiveDataBeforeRegisteringLink) { constexpr size_t kPacketCount = 10; - common::StaticByteBuffer<255> buffer; + StaticByteBuffer<255> buffer; // We use the ATT channel to control incoming packets and the SMP channel to // quit the message loop. size_t packet_count = 0; - auto att_rx_cb = [&packet_count](common::ByteBufferPtr sdu) { - packet_count++; - }; + auto att_rx_cb = [&packet_count](ByteBufferPtr sdu) { packet_count++; }; bool smp_cb_called = false; - auto smp_rx_cb = [&smp_cb_called, this](common::ByteBufferPtr sdu) { + auto smp_rx_cb = [&smp_cb_called, this](ByteBufferPtr sdu) { ZX_DEBUG_ASSERT(sdu); EXPECT_EQ(0u, sdu->size()); smp_cb_called = true; @@ -386,7 +382,7 @@ TEST_F(L2CAP_ChannelManagerTest, ReceiveDataBeforeRegisteringLink) { // ATT channel for (size_t i = 0u; i < kPacketCount; i++) { - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (starting fragment) 0x01, 0x00, 0x04, 0x00, @@ -395,7 +391,7 @@ TEST_F(L2CAP_ChannelManagerTest, ReceiveDataBeforeRegisteringLink) { } // SMP channel - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (starting fragment) 0x01, 0x00, 0x04, 0x00, @@ -428,17 +424,15 @@ TEST_F(L2CAP_ChannelManagerTest, ReceiveDataBeforeCreatingChannel) { RegisterLE(kTestHandle1, hci::Connection::Role::kMaster); - common::StaticByteBuffer<255> buffer; + StaticByteBuffer<255> buffer; // We use the ATT channel to control incoming packets and the SMP channel to // quit the message loop. size_t packet_count = 0; - auto att_rx_cb = [&packet_count](common::ByteBufferPtr sdu) { - packet_count++; - }; + auto att_rx_cb = [&packet_count](ByteBufferPtr sdu) { packet_count++; }; bool smp_cb_called = false; - auto smp_rx_cb = [&smp_cb_called, this](common::ByteBufferPtr sdu) { + auto smp_rx_cb = [&smp_cb_called, this](ByteBufferPtr sdu) { ZX_DEBUG_ASSERT(sdu); EXPECT_EQ(0u, sdu->size()); smp_cb_called = true; @@ -446,7 +440,7 @@ TEST_F(L2CAP_ChannelManagerTest, ReceiveDataBeforeCreatingChannel) { // ATT channel for (size_t i = 0u; i < kPacketCount; i++) { - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (starting fragment) 0x01, 0x00, 0x04, 0x00, @@ -455,7 +449,7 @@ TEST_F(L2CAP_ChannelManagerTest, ReceiveDataBeforeCreatingChannel) { } // SMP channel - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (starting fragment) 0x01, 0x00, 0x04, 0x00, @@ -493,17 +487,15 @@ TEST_F(L2CAP_ChannelManagerTest, ReceiveDataBeforeSettingRxHandler) { auto smp_chan = chanmgr()->OpenFixedChannel(kTestHandle1, kLESMPChannelId); ZX_DEBUG_ASSERT(smp_chan); - common::StaticByteBuffer<255> buffer; + StaticByteBuffer<255> buffer; // We use the ATT channel to control incoming packets and the SMP channel to // quit the message loop. size_t packet_count = 0; - auto att_rx_cb = [&packet_count](common::ByteBufferPtr sdu) { - packet_count++; - }; + auto att_rx_cb = [&packet_count](ByteBufferPtr sdu) { packet_count++; }; bool smp_cb_called = false; - auto smp_rx_cb = [&smp_cb_called, this](common::ByteBufferPtr sdu) { + auto smp_rx_cb = [&smp_cb_called, this](ByteBufferPtr sdu) { ZX_DEBUG_ASSERT(sdu); EXPECT_EQ(0u, sdu->size()); smp_cb_called = true; @@ -511,7 +503,7 @@ TEST_F(L2CAP_ChannelManagerTest, ReceiveDataBeforeSettingRxHandler) { // ATT channel for (size_t i = 0u; i < kPacketCount; i++) { - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (starting fragment) 0x01, 0x00, 0x04, 0x00, @@ -520,7 +512,7 @@ TEST_F(L2CAP_ChannelManagerTest, ReceiveDataBeforeSettingRxHandler) { } // SMP channel - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (starting fragment) 0x01, 0x00, 0x04, 0x00, @@ -546,7 +538,7 @@ TEST_F(L2CAP_ChannelManagerTest, SendOnClosedLink) { chanmgr()->Unregister(kTestHandle1); - EXPECT_FALSE(att_chan->Send(common::NewBuffer('T', 'e', 's', 't'))); + EXPECT_FALSE(att_chan->Send(NewBuffer('T', 'e', 's', 't'))); } TEST_F(L2CAP_ChannelManagerTest, SendBasicSdu) { @@ -554,25 +546,25 @@ TEST_F(L2CAP_ChannelManagerTest, SendBasicSdu) { auto att_chan = ActivateNewFixedChannel(kATTChannelId, kTestHandle1); ZX_DEBUG_ASSERT(att_chan); - std::unique_ptr<common::ByteBuffer> received; - auto data_cb = [&received](const common::ByteBuffer& bytes) { - received = std::make_unique<common::DynamicByteBuffer>(bytes); + std::unique_ptr<ByteBuffer> received; + auto data_cb = [&received](const ByteBuffer& bytes) { + received = std::make_unique<DynamicByteBuffer>(bytes); }; test_device()->SetDataCallback(data_cb, dispatcher()); - EXPECT_TRUE(att_chan->Send(common::NewBuffer('T', 'e', 's', 't'))); + EXPECT_TRUE(att_chan->Send(NewBuffer('T', 'e', 's', 't'))); RunLoopUntilIdle(); ASSERT_TRUE(received); - auto expected = common::CreateStaticByteBuffer( + auto expected = CreateStaticByteBuffer( // ACL data header (handle: 1, length 7) 0x01, 0x00, 0x08, 0x00, // L2CAP B-frame: (length: 3, channel-id: 4) 0x04, 0x00, 0x04, 0x00, 'T', 'e', 's', 't'); - EXPECT_TRUE(common::ContainersEqual(expected, *received)); + EXPECT_TRUE(ContainersEqual(expected, *received)); } // Tests that fragmentation of LE vs BR/EDR packets is based on the same @@ -588,22 +580,19 @@ TEST_F(L2CAP_ChannelManagerTest, SendFragmentedSdus) { SetUp(hci::DataBufferInfo(kMaxDataSize, kMaxNumPackets), hci::DataBufferInfo()); - std::vector<std::unique_ptr<common::ByteBuffer>> le_fragments, acl_fragments; - auto data_cb = [&le_fragments, - &acl_fragments](const common::ByteBuffer& bytes) { + std::vector<std::unique_ptr<ByteBuffer>> le_fragments, acl_fragments; + auto data_cb = [&le_fragments, &acl_fragments](const ByteBuffer& bytes) { ZX_DEBUG_ASSERT(bytes.size() >= sizeof(hci::ACLDataHeader)); - common::PacketView<hci::ACLDataHeader> packet( + PacketView<hci::ACLDataHeader> packet( &bytes, bytes.size() - sizeof(hci::ACLDataHeader)); hci::ConnectionHandle handle = le16toh(packet.header().handle_and_flags) & 0xFFF; if (handle == kTestHandle1) - le_fragments.push_back( - std::make_unique<common::DynamicByteBuffer>(bytes)); + le_fragments.push_back(std::make_unique<DynamicByteBuffer>(bytes)); else if (handle == kTestHandle2) - acl_fragments.push_back( - std::make_unique<common::DynamicByteBuffer>(bytes)); + acl_fragments.push_back(std::make_unique<DynamicByteBuffer>(bytes)); }; test_device()->SetDataCallback(data_cb, dispatcher()); @@ -618,59 +607,58 @@ TEST_F(L2CAP_ChannelManagerTest, SendFragmentedSdus) { // SDU of length 5 corresponds to a 9-octet B-frame which should be sent over // 2 fragments. - EXPECT_TRUE(att_chan->Send(common::NewBuffer('H', 'e', 'l', 'l', 'o'))); + EXPECT_TRUE(att_chan->Send(NewBuffer('H', 'e', 'l', 'l', 'o'))); // SDU of length 7 corresponds to a 11-octet B-frame which should be sent over // 3 fragments. - EXPECT_TRUE( - sm_chan->Send(common::NewBuffer('G', 'o', 'o', 'd', 'b', 'y', 'e'))); + EXPECT_TRUE(sm_chan->Send(NewBuffer('G', 'o', 'o', 'd', 'b', 'y', 'e'))); RunLoopUntilIdle(); EXPECT_EQ(2u, le_fragments.size()); ASSERT_EQ(3u, acl_fragments.size()); - auto expected_le_0 = common::CreateStaticByteBuffer( + auto expected_le_0 = CreateStaticByteBuffer( // ACL data header (handle: 1, length: 5) 0x01, 0x00, 0x05, 0x00, // L2CAP B-frame: (length: 5, channel-id: 4, partial payload) 0x05, 0x00, 0x04, 0x00, 'H'); - auto expected_le_1 = common::CreateStaticByteBuffer( + auto expected_le_1 = CreateStaticByteBuffer( // ACL data header (handle: 1, pbf: continuing fr., length: 4) 0x01, 0x10, 0x04, 0x00, // Continuing payload 'e', 'l', 'l', 'o'); - auto expected_acl_0 = common::CreateStaticByteBuffer( + auto expected_acl_0 = CreateStaticByteBuffer( // ACL data header (handle: 2, length: 5) 0x02, 0x00, 0x05, 0x00, // l2cap b-frame: (length: 7, channel-id: 7, partial payload) 0x07, 0x00, 0x07, 0x00, 'G'); - auto expected_acl_1 = common::CreateStaticByteBuffer( + auto expected_acl_1 = CreateStaticByteBuffer( // ACL data header (handle: 2, pbf: continuing fr., length: 5) 0x02, 0x10, 0x05, 0x00, // continuing payload 'o', 'o', 'd', 'b', 'y'); - auto expected_acl_2 = common::CreateStaticByteBuffer( + auto expected_acl_2 = CreateStaticByteBuffer( // ACL data header (handle: 2, pbf: continuing fr., length: 1) 0x02, 0x10, 0x01, 0x00, // Continuing payload 'e'); - EXPECT_TRUE(common::ContainersEqual(expected_le_0, *le_fragments[0])); - EXPECT_TRUE(common::ContainersEqual(expected_le_1, *le_fragments[1])); + EXPECT_TRUE(ContainersEqual(expected_le_0, *le_fragments[0])); + EXPECT_TRUE(ContainersEqual(expected_le_1, *le_fragments[1])); - EXPECT_TRUE(common::ContainersEqual(expected_acl_0, *acl_fragments[0])); - EXPECT_TRUE(common::ContainersEqual(expected_acl_1, *acl_fragments[1])); - EXPECT_TRUE(common::ContainersEqual(expected_acl_2, *acl_fragments[2])); + EXPECT_TRUE(ContainersEqual(expected_acl_0, *acl_fragments[0])); + EXPECT_TRUE(ContainersEqual(expected_acl_1, *acl_fragments[1])); + EXPECT_TRUE(ContainersEqual(expected_acl_2, *acl_fragments[2])); } // Tests that fragmentation of LE and BR/EDR packets use the corresponding @@ -686,22 +674,19 @@ TEST_F(L2CAP_ChannelManagerTest, SendFragmentedSdusDifferentBuffers) { SetUp(hci::DataBufferInfo(kMaxACLDataSize, kMaxNumPackets), hci::DataBufferInfo(kMaxLEDataSize, kMaxNumPackets)); - std::vector<std::unique_ptr<common::ByteBuffer>> le_fragments, acl_fragments; - auto data_cb = [&le_fragments, - &acl_fragments](const common::ByteBuffer& bytes) { + std::vector<std::unique_ptr<ByteBuffer>> le_fragments, acl_fragments; + auto data_cb = [&le_fragments, &acl_fragments](const ByteBuffer& bytes) { ZX_DEBUG_ASSERT(bytes.size() >= sizeof(hci::ACLDataHeader)); - common::PacketView<hci::ACLDataHeader> packet( + PacketView<hci::ACLDataHeader> packet( &bytes, bytes.size() - sizeof(hci::ACLDataHeader)); hci::ConnectionHandle handle = le16toh(packet.header().handle_and_flags) & 0xFFF; if (handle == kTestHandle1) - le_fragments.push_back( - std::make_unique<common::DynamicByteBuffer>(bytes)); + le_fragments.push_back(std::make_unique<DynamicByteBuffer>(bytes)); else if (handle == kTestHandle2) - acl_fragments.push_back( - std::make_unique<common::DynamicByteBuffer>(bytes)); + acl_fragments.push_back(std::make_unique<DynamicByteBuffer>(bytes)); }; test_device()->SetDataCallback(data_cb, dispatcher()); @@ -716,43 +701,42 @@ TEST_F(L2CAP_ChannelManagerTest, SendFragmentedSdusDifferentBuffers) { // SDU of length 5 corresponds to a 9-octet B-frame. The LE buffer size is // large enough for this to be sent over a single fragment. - EXPECT_TRUE(att_chan->Send(common::NewBuffer('H', 'e', 'l', 'l', 'o'))); + EXPECT_TRUE(att_chan->Send(NewBuffer('H', 'e', 'l', 'l', 'o'))); // SDU of length 7 corresponds to a 11-octet B-frame. Due to the BR/EDR buffer // size, this should be sent over 2 fragments. - EXPECT_TRUE( - sm_chan->Send(common::NewBuffer('G', 'o', 'o', 'd', 'b', 'y', 'e'))); + EXPECT_TRUE(sm_chan->Send(NewBuffer('G', 'o', 'o', 'd', 'b', 'y', 'e'))); RunLoopUntilIdle(); EXPECT_EQ(1u, le_fragments.size()); ASSERT_EQ(2u, acl_fragments.size()); - auto expected_le = common::CreateStaticByteBuffer( + auto expected_le = CreateStaticByteBuffer( // ACL data header (handle: 1, length: 9) 0x01, 0x00, 0x09, 0x00, // L2CAP B-frame: (length: 5, channel-id: 4) 0x05, 0x00, 0x04, 0x00, 'H', 'e', 'l', 'l', 'o'); - auto expected_acl_0 = common::CreateStaticByteBuffer( + auto expected_acl_0 = CreateStaticByteBuffer( // ACL data header (handle: 2, length: 6) 0x02, 0x00, 0x06, 0x00, // l2cap b-frame: (length: 7, channel-id: 7, partial payload) 0x07, 0x00, 0x07, 0x00, 'G', 'o'); - auto expected_acl_1 = common::CreateStaticByteBuffer( + auto expected_acl_1 = CreateStaticByteBuffer( // ACL data header (handle: 2, pbf: continuing fr., length: 5) 0x02, 0x10, 0x05, 0x00, // continuing payload 'o', 'd', 'b', 'y', 'e'); - EXPECT_TRUE(common::ContainersEqual(expected_le, *le_fragments[0])); + EXPECT_TRUE(ContainersEqual(expected_le, *le_fragments[0])); - EXPECT_TRUE(common::ContainersEqual(expected_acl_0, *acl_fragments[0])); - EXPECT_TRUE(common::ContainersEqual(expected_acl_1, *acl_fragments[1])); + EXPECT_TRUE(ContainersEqual(expected_acl_0, *acl_fragments[0])); + EXPECT_TRUE(ContainersEqual(expected_acl_1, *acl_fragments[1])); } TEST_F(L2CAP_ChannelManagerTest, LEChannelSignalLinkError) { @@ -802,7 +786,7 @@ TEST_F(L2CAP_ChannelManagerTest, LEConnectionParameterUpdateRequest) { conn_param_cb); // clang-format off - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 0x0001, length: 16 bytes) 0x01, 0x00, 0x10, 0x00, @@ -844,7 +828,7 @@ TEST_F(L2CAP_ChannelManagerTest, ACLOutboundDynamicChannelLocalDisconnect) { RunLoopUntilIdle(); // clang-format off - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 0x0001, length: 16 bytes) 0x01, 0x00, 0x10, 0x00, @@ -857,7 +841,7 @@ TEST_F(L2CAP_ChannelManagerTest, ACLOutboundDynamicChannelLocalDisconnect) { 0x42, 0x90, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00)); - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 0x0001, length: 16 bytes) 0x01, 0x00, 0x10, 0x00, @@ -870,7 +854,7 @@ TEST_F(L2CAP_ChannelManagerTest, ACLOutboundDynamicChannelLocalDisconnect) { 0x40, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x04)); - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 0x0001, length: 14 bytes) 0x01, 0x00, 0x0e, 0x00, @@ -892,32 +876,32 @@ TEST_F(L2CAP_ChannelManagerTest, ACLOutboundDynamicChannelLocalDisconnect) { EXPECT_EQ(kRemoteId, channel->remote_id()); // Test SDU transmission. - std::unique_ptr<common::ByteBuffer> received; - auto data_cb = [&received](const common::ByteBuffer& bytes) { - received = std::make_unique<common::DynamicByteBuffer>(bytes); + std::unique_ptr<ByteBuffer> received; + auto data_cb = [&received](const ByteBuffer& bytes) { + received = std::make_unique<DynamicByteBuffer>(bytes); }; test_device()->SetDataCallback(std::move(data_cb), dispatcher()); - EXPECT_TRUE(channel->Send(common::NewBuffer('T', 'e', 's', 't'))); + EXPECT_TRUE(channel->Send(NewBuffer('T', 'e', 's', 't'))); RunLoopUntilIdle(); ASSERT_TRUE(received); // SDU must have remote channel ID (unlike for fixed channels). - auto expected = common::CreateStaticByteBuffer( + auto expected = CreateStaticByteBuffer( // ACL data header (handle: 1, length 8) 0x01, 0x00, 0x08, 0x00, // L2CAP B-frame: (length: 4, channel-id: 0x9042) 0x04, 0x00, 0x42, 0x90, 'T', 'e', 's', 't'); - EXPECT_TRUE(common::ContainersEqual(expected, *received)); + EXPECT_TRUE(ContainersEqual(expected, *received)); // Explicit deactivation should not result in |closed_cb| being called. channel->Deactivate(); // clang-format off - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 0x0001, length: 12 bytes) 0x01, 0x00, 0x0c, 0x00, @@ -947,7 +931,7 @@ TEST_F(L2CAP_ChannelManagerTest, ACLOutboundDynamicChannelRemoteDisconnect) { auto closed_cb = [&channel_closed] { channel_closed = true; }; bool sdu_received = false; - auto data_rx_cb = [&sdu_received](common::ByteBufferPtr sdu) { + auto data_rx_cb = [&sdu_received](ByteBufferPtr sdu) { sdu_received = true; ZX_DEBUG_ASSERT(sdu); EXPECT_EQ("Test", sdu->AsString()); @@ -958,7 +942,7 @@ TEST_F(L2CAP_ChannelManagerTest, ACLOutboundDynamicChannelRemoteDisconnect) { RunLoopUntilIdle(); // clang-format off - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 0x0001, length: 16 bytes) 0x01, 0x00, 0x10, 0x00, @@ -971,7 +955,7 @@ TEST_F(L2CAP_ChannelManagerTest, ACLOutboundDynamicChannelRemoteDisconnect) { 0x47, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00)); - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 0x0001, length: 16 bytes) 0x01, 0x00, 0x10, 0x00, @@ -984,7 +968,7 @@ TEST_F(L2CAP_ChannelManagerTest, ACLOutboundDynamicChannelRemoteDisconnect) { 0x40, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x04)); - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 0x0001, length: 14 bytes) 0x01, 0x00, 0x0e, 0x00, @@ -1004,7 +988,7 @@ TEST_F(L2CAP_ChannelManagerTest, ACLOutboundDynamicChannelRemoteDisconnect) { EXPECT_FALSE(channel_closed); // Test SDU reception. - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 1, length 8) 0x01, 0x00, 0x08, 0x00, @@ -1015,7 +999,7 @@ TEST_F(L2CAP_ChannelManagerTest, ACLOutboundDynamicChannelRemoteDisconnect) { EXPECT_TRUE(sdu_received); // clang-format off - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 0x0001, length: 12 bytes) 0x01, 0x00, 0x0c, 0x00, @@ -1044,12 +1028,12 @@ TEST_F(L2CAP_ChannelManagerTest, ACLOutboundDynamicChannelDataNotBuffered) { bool channel_closed = false; auto closed_cb = [&channel_closed] { channel_closed = true; }; - auto data_rx_cb = [](common::ByteBufferPtr sdu) { + auto data_rx_cb = [](ByteBufferPtr sdu) { FAIL() << "Unexpected data reception"; }; // Receive SDU for the channel about to be opened. It should be ignored. - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 1, length 8) 0x01, 0x00, 0x08, 0x00, @@ -1061,7 +1045,7 @@ TEST_F(L2CAP_ChannelManagerTest, ACLOutboundDynamicChannelDataNotBuffered) { RunLoopUntilIdle(); // clang-format off - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 0x0001, length: 16 bytes) 0x01, 0x00, 0x10, 0x00, @@ -1076,14 +1060,14 @@ TEST_F(L2CAP_ChannelManagerTest, ACLOutboundDynamicChannelDataNotBuffered) { // The channel is connected but not configured, so no data should flow on the // channel. Test that this received data is also ignored. - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 1, length 8) 0x01, 0x00, 0x08, 0x00, // L2CAP B-frame: (length: 4, channel-id: 0x0040) 0x04, 0x00, 0x40, 0x00, 'T', 'e', 's', 't')); - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 0x0001, length: 16 bytes) 0x01, 0x00, 0x10, 0x00, @@ -1096,7 +1080,7 @@ TEST_F(L2CAP_ChannelManagerTest, ACLOutboundDynamicChannelDataNotBuffered) { 0x40, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x04)); - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 0x0001, length: 14 bytes) 0x01, 0x00, 0x0e, 0x00, @@ -1116,7 +1100,7 @@ TEST_F(L2CAP_ChannelManagerTest, ACLOutboundDynamicChannelDataNotBuffered) { EXPECT_FALSE(channel_closed); // clang-format off - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 0x0001, length: 12 bytes) 0x01, 0x00, 0x0c, 0x00, @@ -1145,7 +1129,7 @@ TEST_F(L2CAP_ChannelManagerTest, ACLOutboundDynamicChannelRemoteRefused) { RunLoopUntilIdle(); // clang-format off - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 0x0001, length: 16 bytes) 0x01, 0x00, 0x10, 0x00, @@ -1177,7 +1161,7 @@ TEST_F(L2CAP_ChannelManagerTest, ACLOutboundDynamicChannelFailedConfiguration) { RunLoopUntilIdle(); // clang-format off - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 0x0001, length: 16 bytes) 0x01, 0x00, 0x10, 0x00, @@ -1190,7 +1174,7 @@ TEST_F(L2CAP_ChannelManagerTest, ACLOutboundDynamicChannelFailedConfiguration) { 0x47, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00)); - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 0x0001, length: 16 bytes) 0x01, 0x00, 0x10, 0x00, @@ -1203,7 +1187,7 @@ TEST_F(L2CAP_ChannelManagerTest, ACLOutboundDynamicChannelFailedConfiguration) { 0x40, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x04)); - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 0x0001, length: 14 bytes) 0x01, 0x00, 0x0e, 0x00, @@ -1216,7 +1200,7 @@ TEST_F(L2CAP_ChannelManagerTest, ACLOutboundDynamicChannelFailedConfiguration) { 0x40, 0x00, 0x00, 0x00, 0x02, 0x00)); - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 0x0001, length: 12 bytes) 0x01, 0x00, 0x0c, 0x00, @@ -1257,7 +1241,7 @@ TEST_F(L2CAP_ChannelManagerTest, ACLInboundDynamicChannelLocalDisconnect) { dispatcher())); // clang-format off - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 0x0001, length: 12 bytes) 0x01, 0x00, 0x0c, 0x00, @@ -1270,7 +1254,7 @@ TEST_F(L2CAP_ChannelManagerTest, ACLInboundDynamicChannelLocalDisconnect) { RunLoopUntilIdle(); - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 0x0001, length: 16 bytes) 0x01, 0x00, 0x10, 0x00, @@ -1283,7 +1267,7 @@ TEST_F(L2CAP_ChannelManagerTest, ACLInboundDynamicChannelLocalDisconnect) { 0x40, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x04)); - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 0x0001, length: 14 bytes) 0x01, 0x00, 0x0e, 0x00, @@ -1305,32 +1289,32 @@ TEST_F(L2CAP_ChannelManagerTest, ACLInboundDynamicChannelLocalDisconnect) { EXPECT_EQ(kRemoteId, channel->remote_id()); // Test SDU transmission. - std::unique_ptr<common::ByteBuffer> received; - auto data_cb = [&received](const common::ByteBuffer& bytes) { - received = std::make_unique<common::DynamicByteBuffer>(bytes); + std::unique_ptr<ByteBuffer> received; + auto data_cb = [&received](const ByteBuffer& bytes) { + received = std::make_unique<DynamicByteBuffer>(bytes); }; test_device()->SetDataCallback(std::move(data_cb), dispatcher()); - EXPECT_TRUE(channel->Send(common::NewBuffer('T', 'e', 's', 't'))); + EXPECT_TRUE(channel->Send(NewBuffer('T', 'e', 's', 't'))); RunLoopUntilIdle(); ASSERT_TRUE(received); // SDU must have remote channel ID (unlike for fixed channels). - auto expected = common::CreateStaticByteBuffer( + auto expected = CreateStaticByteBuffer( // ACL data header (handle: 1, length 7) 0x01, 0x00, 0x08, 0x00, // L2CAP B-frame: (length: 3, channel-id: 0x9042) 0x04, 0x00, 0x42, 0x90, 'T', 'e', 's', 't'); - EXPECT_TRUE(common::ContainersEqual(expected, *received)); + EXPECT_TRUE(ContainersEqual(expected, *received)); // Explicit deactivation should not result in |closed_cb| being called. channel->Deactivate(); // clang-format off - test_device()->SendACLDataChannelPacket(common::CreateStaticByteBuffer( + test_device()->SendACLDataChannelPacket(CreateStaticByteBuffer( // ACL data header (handle: 0x0001, length: 12 bytes) 0x01, 0x00, 0x0c, 0x00, diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_rx_engine.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_rx_engine.cc index 1ff82eeeeeb0fdfc18d3aa226a2171e830787fa9..7d785fc504ca27ed65bfe37a10c2bf4e76d40423 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_rx_engine.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_rx_engine.cc @@ -15,7 +15,7 @@ std::optional<T> TryCopyFromPdu(const PDU& pdu) { if (pdu.length() < sizeof(T)) return std::nullopt; - common::StaticByteBuffer<sizeof(T)> buf; + StaticByteBuffer<sizeof(T)> buf; pdu.Copy(&buf, 0, sizeof(T)); return buf.template As<T>(); } @@ -70,7 +70,7 @@ Engine::EnhancedRetransmissionModeRxEngine( : next_seqnum_(0), send_basic_frame_callback_(std::move(send_basic_frame_callback)) {} -common::ByteBufferPtr Engine::ProcessPdu(PDU pdu) { +ByteBufferPtr Engine::ProcessPdu(PDU pdu) { // A note on validation (see Vol 3, Part A, 3.3.7): // // We skip step 1 (validation of the Channel ID), as a frame with an @@ -100,8 +100,8 @@ common::ByteBufferPtr Engine::ProcessPdu(PDU pdu) { header); } -common::ByteBufferPtr Engine::ProcessFrame( - const SimpleInformationFrameHeader header, PDU pdu) { +ByteBufferPtr Engine::ProcessFrame(const SimpleInformationFrameHeader header, + PDU pdu) { if (header.tx_seq() != next_seqnum_) { // TODO(quiche): Send REJ frame. // TODO(quiche): Add histogram for |header.tx_seq() - next_seqnum_|. This @@ -121,24 +121,23 @@ common::ByteBufferPtr Engine::ProcessFrame( SimpleReceiverReadyFrame ack_frame; ack_frame.set_request_seq_num(next_seqnum_); - send_basic_frame_callback_(std::make_unique<common::DynamicByteBuffer>( - common::BufferView(&ack_frame, sizeof(ack_frame)))); + send_basic_frame_callback_(std::make_unique<DynamicByteBuffer>( + BufferView(&ack_frame, sizeof(ack_frame)))); const auto header_len = sizeof(header); const auto payload_len = pdu.length() - header_len; - auto sdu = std::make_unique<common::DynamicByteBuffer>(payload_len); + auto sdu = std::make_unique<DynamicByteBuffer>(payload_len); pdu.Copy(sdu.get(), header_len, payload_len); return sdu; } -common::ByteBufferPtr Engine::ProcessFrame(const SimpleStartOfSduFrameHeader, - PDU pdu) { +ByteBufferPtr Engine::ProcessFrame(const SimpleStartOfSduFrameHeader, PDU pdu) { // TODO(quiche): Implement validation and handling of Start-of-SDU frames. return nullptr; } -common::ByteBufferPtr Engine::ProcessFrame(const SimpleSupervisoryFrame sframe, - PDU pdu) { +ByteBufferPtr Engine::ProcessFrame(const SimpleSupervisoryFrame sframe, + PDU pdu) { if (sframe.function() == SupervisoryFunction::ReceiverReady && sframe.is_poll_request()) { // TODO(quiche): Propagate ReqSeq to the transmit engine. @@ -150,8 +149,8 @@ common::ByteBufferPtr Engine::ProcessFrame(const SimpleSupervisoryFrame sframe, SimpleReceiverReadyFrame poll_response; poll_response.set_is_poll_response(); poll_response.set_request_seq_num(next_seqnum_); - send_basic_frame_callback_(std::make_unique<common::DynamicByteBuffer>( - common::BufferView(&poll_response, sizeof(poll_response)))); + send_basic_frame_callback_(std::make_unique<DynamicByteBuffer>( + BufferView(&poll_response, sizeof(poll_response)))); return nullptr; } @@ -159,7 +158,7 @@ common::ByteBufferPtr Engine::ProcessFrame(const SimpleSupervisoryFrame sframe, return nullptr; } -common::ByteBufferPtr Engine::ProcessFrame(std::monostate, PDU pdu) { +ByteBufferPtr Engine::ProcessFrame(std::monostate, PDU pdu) { // TODO(quiche): Close connection. return nullptr; } diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_rx_engine.h b/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_rx_engine.h index 3d50df8b4541ebf5ab577745c68ee83007479a2f..f5e7213c5f258e83efafe38744460a720f0f6279 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_rx_engine.h +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_rx_engine.h @@ -21,19 +21,19 @@ namespace internal { // THREAD-SAFETY: This class is not thread-safe. class EnhancedRetransmissionModeRxEngine final : public RxEngine { public: - using SendBasicFrameCallback = fit::function<void(common::ByteBufferPtr pdu)>; + using SendBasicFrameCallback = fit::function<void(ByteBufferPtr pdu)>; EnhancedRetransmissionModeRxEngine( SendBasicFrameCallback send_basic_frame_callback); virtual ~EnhancedRetransmissionModeRxEngine() = default; - common::ByteBufferPtr ProcessPdu(PDU) override; + ByteBufferPtr ProcessPdu(PDU) override; private: - common::ByteBufferPtr ProcessFrame(const SimpleInformationFrameHeader, PDU); - common::ByteBufferPtr ProcessFrame(const SimpleStartOfSduFrameHeader, PDU); - common::ByteBufferPtr ProcessFrame(const SimpleSupervisoryFrame, PDU); - common::ByteBufferPtr ProcessFrame(std::monostate, PDU); + ByteBufferPtr ProcessFrame(const SimpleInformationFrameHeader, PDU); + ByteBufferPtr ProcessFrame(const SimpleStartOfSduFrameHeader, PDU); + ByteBufferPtr ProcessFrame(const SimpleSupervisoryFrame, PDU); + ByteBufferPtr ProcessFrame(std::monostate, PDU); void AdvanceSeqNum(); // We assume that the Extended Window Size option is _not_ enabled. In such diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_rx_engine_unittest.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_rx_engine_unittest.cc index 3c9b44da34e0a9927e85ef22f86ca839314d64c9..ce542aef2fef5150256fa0d96cdea0c21e27659b 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_rx_engine_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_rx_engine_unittest.cc @@ -4,9 +4,9 @@ #include "enhanced_retransmission_mode_rx_engine.h" +#include "gtest/gtest.h" #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" #include "src/connectivity/bluetooth/core/bt-host/l2cap/fragmenter.h" -#include "gtest/gtest.h" namespace bt { namespace l2cap { @@ -18,27 +18,26 @@ constexpr ChannelId kTestChannelId = 0x0001; using Engine = EnhancedRetransmissionModeRxEngine; -void NopTxCallback(common::ByteBufferPtr) {} +void NopTxCallback(ByteBufferPtr) {} TEST(L2CAP_EnhancedRetransmissionModeRxEngineTest, ProcessPduImmediatelyReturnsDataForUnsegmentedSdu) { // See Core Spec, v5, Vol 3, Part A, Table 3.2 for the first two bytes. - const auto payload = - common::CreateStaticByteBuffer(0, 0, 'h', 'e', 'l', 'l', 'o'); - const common::ByteBufferPtr sdu = + const auto payload = CreateStaticByteBuffer(0, 0, 'h', 'e', 'l', 'l', 'o'); + const ByteBufferPtr sdu = Engine(NopTxCallback) .ProcessPdu( Fragmenter(kTestHandle).BuildBasicFrame(kTestChannelId, payload)); ASSERT_TRUE(sdu); - EXPECT_TRUE(common::ContainersEqual( - common::CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o'), *sdu)); + EXPECT_TRUE( + ContainersEqual(CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o'), *sdu)); } TEST(L2CAP_EnhancedRetransmissionModeRxEngineTest, ProcessPduCanHandleZeroBytePayload) { // See Core Spec, v5, Vol 3, Part A, Table 3.2 for the first two bytes. - const auto payload = common::CreateStaticByteBuffer(0, 0); - const common::ByteBufferPtr sdu = + const auto payload = CreateStaticByteBuffer(0, 0); + const ByteBufferPtr sdu = Engine(NopTxCallback) .ProcessPdu( Fragmenter(kTestHandle).BuildBasicFrame(kTestChannelId, payload)); @@ -49,9 +48,9 @@ TEST(L2CAP_EnhancedRetransmissionModeRxEngineTest, TEST(L2CAP_EnhancedRetransmissionModeRxEngineTest, ProcessPduDoesNotGenerateSduForOutOfSequencePdu) { // See Core Spec, v5, Vol 3, Part A, Table 3.2 for the first two bytes. - const auto payload = common::CreateStaticByteBuffer( // - 1 << 1, // TxSeq = 1, R=0 - 0, // SAR and ReqSeq + const auto payload = CreateStaticByteBuffer( // + 1 << 1, // TxSeq = 1, R=0 + 0, // SAR and ReqSeq 'h', 'e', 'l', 'l', 'o'); EXPECT_FALSE(Engine(NopTxCallback) .ProcessPdu(Fragmenter(kTestHandle) @@ -64,9 +63,9 @@ TEST(L2CAP_EnhancedRetransmissionModeRxEngineTest, // Send with sequence 0. { - const auto payload = common::CreateStaticByteBuffer( // - 0 << 1, // TxSeq=0, R=0 - 0, // SAR and ReqSeq + const auto payload = CreateStaticByteBuffer( // + 0 << 1, // TxSeq=0, R=0 + 0, // SAR and ReqSeq 'h', 'e', 'l', 'l', 'o'); ASSERT_TRUE(rx_engine.ProcessPdu( Fragmenter(kTestHandle).BuildBasicFrame(kTestChannelId, payload))); @@ -74,9 +73,9 @@ TEST(L2CAP_EnhancedRetransmissionModeRxEngineTest, // Send with sequence 1. { - const auto payload = common::CreateStaticByteBuffer( // - 1 << 1, // TxSeq=1, R=0 - 0, // SAR and ReqSeq + const auto payload = CreateStaticByteBuffer( // + 1 << 1, // TxSeq=1, R=0 + 0, // SAR and ReqSeq 'h', 'e', 'l', 'l', 'o'); ASSERT_TRUE(rx_engine.ProcessPdu( Fragmenter(kTestHandle).BuildBasicFrame(kTestChannelId, payload))); @@ -84,9 +83,9 @@ TEST(L2CAP_EnhancedRetransmissionModeRxEngineTest, // Send with sequence 2. { - const auto payload = common::CreateStaticByteBuffer( // - 2 << 1, // TxSeq=2, R=0 - 0, // SAR and ReqSeq + const auto payload = CreateStaticByteBuffer( // + 2 << 1, // TxSeq=2, R=0 + 0, // SAR and ReqSeq 'h', 'e', 'l', 'l', 'o'); EXPECT_TRUE(rx_engine.ProcessPdu( Fragmenter(kTestHandle).BuildBasicFrame(kTestChannelId, payload))); @@ -96,9 +95,9 @@ TEST(L2CAP_EnhancedRetransmissionModeRxEngineTest, TEST(L2CAP_EnhancedRetransmissionModeRxEngineTest, ProcessPduRollsOverSequenceNumber) { Engine rx_engine(NopTxCallback); - auto payload = common::CreateStaticByteBuffer( // - 0 << 1, // TxSeq=0, R=0 - 0, // SAR and ReqSeq + auto payload = CreateStaticByteBuffer( // + 0 << 1, // TxSeq=0, R=0 + 0, // SAR and ReqSeq 'h', 'e', 'l', 'l', 'o'); for (size_t i = 0; i < 64; ++i) { payload[0] = i << 1; // Set TxSeq @@ -117,16 +116,16 @@ TEST(L2CAP_EnhancedRetransmissionModeRxEngineTest, TEST(L2CAP_EnhancedRetransmissionModeRxEngineTest, ProcessPduDoesNotAdvanceSequenceNumberForOutOfSequencePdu) { Engine rx_engine(NopTxCallback); - const auto out_of_seq = common::CreateStaticByteBuffer( // - 1 << 1, // TxSeq=1, R=0 - 0, // SAR and ReqSeq + const auto out_of_seq = CreateStaticByteBuffer( // + 1 << 1, // TxSeq=1, R=0 + 0, // SAR and ReqSeq 'h', 'e', 'l', 'l', 'o'); ASSERT_FALSE(rx_engine.ProcessPdu( Fragmenter(kTestHandle).BuildBasicFrame(kTestChannelId, out_of_seq))); - const auto in_seq = common::CreateStaticByteBuffer( // - 0 << 1, // TxSeq=0, R=0 - 0, // SAR and ReqSeq + const auto in_seq = CreateStaticByteBuffer( // + 0 << 1, // TxSeq=0, R=0 + 0, // SAR and ReqSeq 'h', 'e', 'l', 'l', 'o'); EXPECT_TRUE(rx_engine.ProcessPdu( Fragmenter(kTestHandle).BuildBasicFrame(kTestChannelId, in_seq))); @@ -135,15 +134,14 @@ TEST(L2CAP_EnhancedRetransmissionModeRxEngineTest, TEST(L2CAP_EnhancedRetransmissionModeRxEngineTest, ProcessPduImmediatelyAcksUnsegmentedSdu) { size_t n_acks = 0; - common::ByteBufferPtr outbound_ack; + ByteBufferPtr outbound_ack; auto tx_callback = [&](auto pdu) { outbound_ack = std::move(pdu); ++n_acks; }; // See Core Spec, v5, Vol 3, Part A, Table 3.2 for the first two bytes. - const auto payload = - common::CreateStaticByteBuffer(0, 0, 'h', 'e', 'l', 'l', 'o'); + const auto payload = CreateStaticByteBuffer(0, 0, 'h', 'e', 'l', 'l', 'o'); ASSERT_TRUE(Engine(tx_callback) .ProcessPdu(Fragmenter(kTestHandle) .BuildBasicFrame(kTestChannelId, payload))); @@ -160,7 +158,7 @@ TEST(L2CAP_EnhancedRetransmissionModeRxEngineTest, TEST(L2CAP_EnhancedRetransmissionModeRxEngineTest, ProcessPduSendsCorrectReqSeqOnRollover) { size_t n_acks = 0; - common::ByteBufferPtr last_ack; + ByteBufferPtr last_ack; auto tx_callback = [&](auto pdu) { last_ack = std::move(pdu); ++n_acks; @@ -170,7 +168,7 @@ TEST(L2CAP_EnhancedRetransmissionModeRxEngineTest, // See Core Spec, v5, Vol 3, Part A, Table 3.2 for the first two bytes. for (size_t i = 0; i < 64; ++i) { const auto payload = - common::CreateStaticByteBuffer(i << 1, 0, 'h', 'e', 'l', 'l', 'o'); + CreateStaticByteBuffer(i << 1, 0, 'h', 'e', 'l', 'l', 'o'); ASSERT_TRUE(rx_engine.ProcessPdu( Fragmenter(kTestHandle).BuildBasicFrame(kTestChannelId, payload))) << " (i=" << i << ")"; @@ -188,15 +186,14 @@ TEST(L2CAP_EnhancedRetransmissionModeRxEngineTest, TEST(L2CAP_EnhancedRetransmissionModeRxEngineTest, ProcessPduDoesNotAckOutOfSequenceFrame) { size_t n_acks = 0; - common::ByteBufferPtr outbound_ack; + ByteBufferPtr outbound_ack; auto tx_callback = [&](auto pdu) { outbound_ack = std::move(pdu); ++n_acks; }; // See Core Spec, v5, Vol 3, Part A, Table 3.2 for the first two bytes. - const auto payload = - common::CreateStaticByteBuffer(1, 0, 'h', 'e', 'l', 'l', 'o'); + const auto payload = CreateStaticByteBuffer(1, 0, 'h', 'e', 'l', 'l', 'o'); // Per Core Spec, v5, Vol 3, Part A, Sec 8.4.7.1, receipt of an // out-of-sequence frame should cause us to transmit a Reject frame. We assume @@ -212,7 +209,7 @@ TEST(L2CAP_EnhancedRetransmissionModeRxEngineTest, TEST(L2CAP_EnhancedRetransmissionModeRxEngineTest, ProcessPduRespondsToReceiverReadyPollRequest) { size_t n_outbound_frames = 0; - common::ByteBufferPtr last_outbound_frame; + ByteBufferPtr last_outbound_frame; auto tx_callback = [&](auto pdu) { last_outbound_frame = std::move(pdu); ++n_outbound_frames; @@ -221,16 +218,14 @@ TEST(L2CAP_EnhancedRetransmissionModeRxEngineTest, Engine rx_engine(tx_callback); // Send an I-frame to advance the receiver's sequence number. // See Core Spec, v5, Vol 3, Part A, Table 3.2 for the first two bytes. - const auto info_frame = - common::CreateStaticByteBuffer(0, 0, 'h', 'e', 'l', 'l', 'o'); + const auto info_frame = CreateStaticByteBuffer(0, 0, 'h', 'e', 'l', 'l', 'o'); rx_engine.ProcessPdu( Fragmenter(kTestHandle).BuildBasicFrame(kTestChannelId, info_frame)); ASSERT_EQ(1u, n_outbound_frames); // Now send a ReceiverReady poll request. See Core Spec, v5, Vol 3, Part A, // Table 3.2 and Table 3.5 for frame format. - const auto receiver_ready_poll_request = - common::CreateStaticByteBuffer(0b1'0001, 0); + const auto receiver_ready_poll_request = CreateStaticByteBuffer(0b1'0001, 0); auto local_sdu = rx_engine.ProcessPdu( Fragmenter(kTestHandle) .BuildBasicFrame(kTestChannelId, receiver_ready_poll_request)); diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_tx_engine.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_tx_engine.cc index ca71b4500c40765cf24eb2669c483f1e69d28ae4..9f3dd9976e0238ef94631ea838b65042e3ce4061 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_tx_engine.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_tx_engine.cc @@ -55,7 +55,7 @@ Engine::EnhancedRetransmissionModeTxEngine( }); } -bool Engine::QueueSdu(common::ByteBufferPtr sdu) { +bool Engine::QueueSdu(ByteBufferPtr sdu) { ZX_ASSERT(sdu); // TODO(BT-440): Add support for segmentation if (sdu->size() > tx_mtu_) { @@ -66,7 +66,7 @@ bool Engine::QueueSdu(common::ByteBufferPtr sdu) { SimpleInformationFrameHeader header(GetNextSeqnum()); auto frame = - std::make_unique<common::DynamicByteBuffer>(sizeof(header) + sdu->size()); + std::make_unique<DynamicByteBuffer>(sizeof(header) + sdu->size()); auto body = frame->mutable_view(sizeof(header)); frame->WriteObj(header); sdu->Copy(&body); @@ -117,8 +117,8 @@ void Engine::SendReceiverReadyPoll() { "(n_receiver_ready_polls_sent_ = %u, " "max_transmissions = %u)", n_receiver_ready_polls_sent_, max_transmissions_); - send_basic_frame_callback_(std::make_unique<common::DynamicByteBuffer>( - common::BufferView(&frame, sizeof(frame)))); + send_basic_frame_callback_( + std::make_unique<DynamicByteBuffer>(BufferView(&frame, sizeof(frame)))); } uint8_t Engine::GetNextSeqnum() { diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_tx_engine.h b/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_tx_engine.h index 27d13c77ba5bafc5351ea2f720b9cd3f1e36d4a5..1ec2b8949a848cda65cab775d0806d03a18cd3b3 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_tx_engine.h +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_tx_engine.h @@ -42,7 +42,7 @@ class EnhancedRetransmissionModeTxEngine final : public TxEngine { ConnectionFailureCallback connection_failure_callback); ~EnhancedRetransmissionModeTxEngine() override = default; - bool QueueSdu(common::ByteBufferPtr sdu) override; + bool QueueSdu(ByteBufferPtr sdu) override; // Updates the Engine's knowledge of the last frame acknowledged by our peer. // The value of |is_final| should reflect the 'F' bit in header of the frame diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_tx_engine_unittest.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_tx_engine_unittest.cc index 29f1bcb60b9ad901a351bfad794360acf9f2b032..cac2454cab91b917b6cbd6f8690c5fe52fdf00d4 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_tx_engine_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_tx_engine_unittest.cc @@ -34,9 +34,9 @@ class L2CAP_EnhancedRetransmissionModeTxEngineTest static constexpr size_t kDefaultMaxTransmissions = 1; static constexpr size_t kDefaultTxWindow = 63; - const common::StaticByteBuffer<5> kDefaultPayload; + const StaticByteBuffer<5> kDefaultPayload; - void VerifyIsReceiverReadyPollFrame(common::ByteBuffer* buf) { + void VerifyIsReceiverReadyPollFrame(ByteBuffer* buf) { ASSERT_TRUE(buf); ASSERT_EQ(sizeof(SimpleSupervisoryFrame), buf->size()); @@ -50,7 +50,7 @@ void NoOpFailureCallback(){}; TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, QueueSduTransmitsMinimalSizedSdu) { - common::ByteBufferPtr last_pdu; + ByteBufferPtr last_pdu; size_t n_pdus = 0; auto tx_callback = [&](auto pdu) { ++n_pdus; @@ -58,24 +58,24 @@ TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, }; constexpr size_t kMtu = 10; - const auto payload = common::CreateStaticByteBuffer(1); + const auto payload = CreateStaticByteBuffer(1); TxEngine(kTestChannelId, kMtu, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback) - .QueueSdu(std::make_unique<common::DynamicByteBuffer>(payload)); + .QueueSdu(std::make_unique<DynamicByteBuffer>(payload)); EXPECT_EQ(1u, n_pdus); ASSERT_TRUE(last_pdu); // See Core Spec v5.0, Volume 3, Part A, Table 3.2. const auto expected_pdu = - common::CreateStaticByteBuffer(0, // Final Bit, TxSeq, MustBeZeroBit - 0, // SAR bits, ReqSeq - 1); // Payload - EXPECT_TRUE(common::ContainersEqual(expected_pdu, *last_pdu)); + CreateStaticByteBuffer(0, // Final Bit, TxSeq, MustBeZeroBit + 0, // SAR bits, ReqSeq + 1); // Payload + EXPECT_TRUE(ContainersEqual(expected_pdu, *last_pdu)); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, QueueSduTransmitsMaximalSizedSdu) { - common::ByteBufferPtr last_pdu; + ByteBufferPtr last_pdu; size_t n_pdus = 0; auto tx_callback = [&](auto pdu) { ++n_pdus; @@ -83,19 +83,19 @@ TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, }; constexpr size_t kMtu = 1; - const auto payload = common::CreateStaticByteBuffer(1); + const auto payload = CreateStaticByteBuffer(1); TxEngine(kTestChannelId, kMtu, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback) - .QueueSdu(std::make_unique<common::DynamicByteBuffer>(payload)); + .QueueSdu(std::make_unique<DynamicByteBuffer>(payload)); EXPECT_EQ(1u, n_pdus); ASSERT_TRUE(last_pdu); // See Core Spec v5.0, Volume 3, Part A, Table 3.2. const auto expected_pdu = - common::CreateStaticByteBuffer(0, // Final Bit, TxSeq, MustBeZeroBit - 0, // SAR bits, ReqSeq - 1); // Payload - EXPECT_TRUE(common::ContainersEqual(expected_pdu, *last_pdu)); + CreateStaticByteBuffer(0, // Final Bit, TxSeq, MustBeZeroBit + 0, // SAR bits, ReqSeq + 1); // Payload + EXPECT_TRUE(ContainersEqual(expected_pdu, *last_pdu)); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, @@ -105,8 +105,8 @@ TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, TxEngine( kTestChannelId, kMtu, kDefaultMaxTransmissions, kDefaultTxWindow, [](auto pdu) {}, NoOpFailureCallback) - .QueueSdu(std::make_unique<common::DynamicByteBuffer>( - common::CreateStaticByteBuffer(1, 2))); + .QueueSdu( + std::make_unique<DynamicByteBuffer>(CreateStaticByteBuffer(1, 2))); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, @@ -114,13 +114,13 @@ TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, TxEngine( kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, [](auto pdu) {}, NoOpFailureCallback) - .QueueSdu(std::make_unique<common::DynamicByteBuffer>()); + .QueueSdu(std::make_unique<DynamicByteBuffer>()); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, QueueSduAdvancesSequenceNumber) { - const auto payload = common::CreateStaticByteBuffer(1); - common::ByteBufferPtr last_pdu; + const auto payload = CreateStaticByteBuffer(1); + ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); @@ -128,71 +128,70 @@ TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, { // See Core Spec v5.0, Volume 3, Part A, Table 3.2. const auto expected_pdu = - common::CreateStaticByteBuffer(0, // Final Bit, TxSeq, MustBeZeroBit - 0, // SAR bits, ReqSeq - 1); // Payload + CreateStaticByteBuffer(0, // Final Bit, TxSeq, MustBeZeroBit + 0, // SAR bits, ReqSeq + 1); // Payload - tx_engine.QueueSdu(std::make_unique<common::DynamicByteBuffer>(payload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(payload)); ASSERT_TRUE(last_pdu); - EXPECT_TRUE(common::ContainersEqual(expected_pdu, *last_pdu)); + EXPECT_TRUE(ContainersEqual(expected_pdu, *last_pdu)); } { // See Core Spec v5.0, Volume 3, Part A, Table 3.2. - const auto expected_pdu = common::CreateStaticByteBuffer( - 1 << 1, // Final Bit, TxSeq=1, MustBeZeroBit - 0, // SAR bits, ReqSeq - 1); // Payload - tx_engine.QueueSdu(std::make_unique<common::DynamicByteBuffer>(payload)); + const auto expected_pdu = + CreateStaticByteBuffer(1 << 1, // Final Bit, TxSeq=1, MustBeZeroBit + 0, // SAR bits, ReqSeq + 1); // Payload + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(payload)); ASSERT_TRUE(last_pdu); - EXPECT_TRUE(common::ContainersEqual(expected_pdu, *last_pdu)); + EXPECT_TRUE(ContainersEqual(expected_pdu, *last_pdu)); } { // See Core Spec v5.0, Volume 3, Part A, Table 3.2. - const auto expected_pdu = common::CreateStaticByteBuffer( - 2 << 1, // Final Bit, TxSeq=2, MustBeZeroBit - 0, // SAR bits, ReqSeq - 1); // Payload - tx_engine.QueueSdu(std::make_unique<common::DynamicByteBuffer>(payload)); + const auto expected_pdu = + CreateStaticByteBuffer(2 << 1, // Final Bit, TxSeq=2, MustBeZeroBit + 0, // SAR bits, ReqSeq + 1); // Payload + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(payload)); ASSERT_TRUE(last_pdu); - EXPECT_TRUE(common::ContainersEqual(expected_pdu, *last_pdu)); + EXPECT_TRUE(ContainersEqual(expected_pdu, *last_pdu)); } } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, QueueSduRollsOverSequenceNumber) { - const auto payload = common::CreateStaticByteBuffer(1); - common::ByteBufferPtr last_pdu; + const auto payload = CreateStaticByteBuffer(1); + ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); constexpr size_t kMaxSeq = 64; for (size_t i = 0; i < kMaxSeq; ++i) { - tx_engine.QueueSdu(std::make_unique<common::DynamicByteBuffer>(payload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(payload)); } // See Core Spec v5.0, Volume 3, Part A, Table 3.2. - const auto expected_pdu = common::CreateStaticByteBuffer( + const auto expected_pdu = CreateStaticByteBuffer( 0, // Final Bit, TxSeq (rolls over from 63 to 0), MustBeZeroBit 0, // SAR bits, ReqSeq 1); // Payload last_pdu = nullptr; - tx_engine.QueueSdu(std::make_unique<common::DynamicByteBuffer>(payload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(payload)); ASSERT_TRUE(last_pdu); - EXPECT_TRUE(common::ContainersEqual(expected_pdu, *last_pdu)); + EXPECT_TRUE(ContainersEqual(expected_pdu, *last_pdu)); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineTransmitsReceiverReadyPollAfterTimeout) { - common::ByteBufferPtr last_pdu; + ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(last_pdu); last_pdu = nullptr; @@ -204,13 +203,12 @@ TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineTransmitsReceiverReadyPollOnlyOnceAfterTimeout) { - common::ByteBufferPtr last_pdu; + ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(last_pdu); last_pdu = nullptr; @@ -228,20 +226,18 @@ TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineAdvancesReceiverReadyPollTimeoutOnNewTransmission) { - common::ByteBufferPtr last_pdu; + ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(last_pdu); last_pdu = nullptr; ASSERT_FALSE(RunLoopFor(zx::sec(1))); // No events should fire. - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); last_pdu = nullptr; @@ -253,18 +249,16 @@ TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, ReceiverReadyPollIncludesRequestSequenceNumber) { - common::ByteBufferPtr last_pdu; + ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); tx_engine.UpdateReqSeq(1); RunLoopUntilIdle(); - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); last_pdu = nullptr; SCOPED_TRACE(""); @@ -275,13 +269,12 @@ TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, AckOfOnlyOutstandingFrameCancelsReceiverReadyPollTimeout) { - common::ByteBufferPtr last_pdu; + ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(last_pdu); last_pdu = nullptr; @@ -295,17 +288,14 @@ TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, AckOfAllOutstandingFramesCancelsReceiverReadyPollTimeout) { - common::ByteBufferPtr last_pdu; + ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(last_pdu); last_pdu = nullptr; @@ -319,17 +309,14 @@ TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, PartialAckDoesNotCancelReceiverReadyPollTimeout) { - common::ByteBufferPtr last_pdu; + ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(last_pdu); last_pdu = nullptr; @@ -346,21 +333,19 @@ TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, NewTransmissionAfterAckedFrameReArmsReceiverReadyPollTimeout) { - common::ByteBufferPtr last_pdu; + ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); // Send a frame, and get the ACK. - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); tx_engine.UpdateAckSeq(1, false); RunLoopUntilIdle(); // Send a new frame. - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); last_pdu = nullptr; // Having earlier received an ACK for the previous frame should not have left @@ -374,13 +359,12 @@ TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineRetransmitsReceiverReadyPollAfterMonitorTimeout) { constexpr size_t kMaxTransmissions = 2; // Allow retransmission - common::ByteBufferPtr last_pdu; + ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); // First the receiver_ready_poll_task_ fires. @@ -397,13 +381,12 @@ TEST_F( L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineDoesNotRetransmitReceiverReadyPollAfterMonitorTimeoutWhenRetransmissionsAreDisabled) { constexpr size_t kMaxTransmissions = 1; - common::ByteBufferPtr last_pdu; + ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); // First the receiver_ready_poll_task_ fires. @@ -423,13 +406,12 @@ TEST_F( L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineStopsPollingReceiverReadyFromMonitorTaskAfterReceivingFinalUpdateForAckSeq) { constexpr size_t kMaxTransmissions = 3; // Allow multiple retransmissions - common::ByteBufferPtr last_pdu; + ByteBufferPtr last_pdu; TxEngine tx_engine( kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, [](auto) {}, NoOpFailureCallback); - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(RunLoopFor(zx::sec(2))); // receiver_ready_poll_task_ @@ -444,13 +426,12 @@ TEST_F( L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineContinuesPollingReceiverReadyFromMonitorTaskAfterReceivingNonFinalUpdateForAckSeq) { constexpr size_t kMaxTransmissions = 2; // Allow retransmissions - common::ByteBufferPtr last_pdu; + ByteBufferPtr last_pdu; TxEngine tx_engine( kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, [&](auto pdu) { last_pdu = std::move(pdu); }, NoOpFailureCallback); - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(RunLoopFor(zx::sec(2))); // receiver_ready_poll_task_ @@ -463,13 +444,12 @@ TEST_F( TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineRetransmitsReceiverReadyPollAfterMultipleMonitorTimeouts) { constexpr size_t kMaxTransmissions = 3; // Allow multiple retransmissions - common::ByteBufferPtr last_pdu; + ByteBufferPtr last_pdu; TxEngine tx_engine( kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, [&](auto pdu) { last_pdu = std::move(pdu); }, NoOpFailureCallback); - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(RunLoopFor(zx::sec(2))); // receiver_ready_poll_task_ @@ -485,13 +465,12 @@ TEST_F( L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineRetransmitsReceiverReadyPollIndefinitelyAfterMonitorTimeoutWhenMaxTransmitsIsZero) { constexpr size_t kMaxTransmissions = 0; - common::ByteBufferPtr last_pdu; + ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); // First the receiver_ready_poll_task_ fires. @@ -517,13 +496,12 @@ TEST_F( TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineStopsTransmittingReceiverReadyPollAfterMaxTransmits) { constexpr size_t kMaxTransmissions = 2; - common::ByteBufferPtr last_pdu; + ByteBufferPtr last_pdu; TxEngine tx_engine( kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, [&](auto pdu) { last_pdu = std::move(pdu); }, NoOpFailureCallback); - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(RunLoopFor(zx::sec(2))); // receiver_ready_poll_task_ @@ -543,8 +521,7 @@ TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, [](auto) {}, [&] { connection_failed = true; }); - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(RunLoopFor(zx::sec(2))); // receiver_ready_poll_task_ @@ -562,8 +539,7 @@ TEST_F( kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, [](auto) {}, [&] { connection_failed = true; }); - tx_engine.QueueSdu( - std::make_unique<common::DynamicByteBuffer>(kDefaultPayload)); + tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(RunLoopFor(zx::sec(2))); // receiver_ready_poll_task_ diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/fake_channel.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/fake_channel.cc index 54def5f84288d693ecfa5ee6164fab015bd0d0e4..482c9ad23017d282083a56a0d8e2dacc94db08c9 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/fake_channel.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/fake_channel.cc @@ -27,11 +27,11 @@ FakeChannel::FakeChannel(ChannelId id, ChannelId remote_id, ZX_DEBUG_ASSERT(handle_); } -void FakeChannel::Receive(const common::ByteBuffer& data) { +void FakeChannel::Receive(const ByteBuffer& data) { ZX_DEBUG_ASSERT(!!rx_cb_ == !!dispatcher_); auto pdu = fragmenter_.BuildBasicFrame(id(), data); - auto sdu = std::make_unique<common::DynamicByteBuffer>(pdu.length()); + auto sdu = std::make_unique<DynamicByteBuffer>(pdu.length()); pdu.Copy(sdu.get()); if (dispatcher_) { async::PostTask(dispatcher_, @@ -109,7 +109,7 @@ void FakeChannel::SignalLinkError() { } } -bool FakeChannel::Send(common::ByteBufferPtr sdu) { +bool FakeChannel::Send(ByteBufferPtr sdu) { ZX_DEBUG_ASSERT(sdu); if (!send_cb_) diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/fake_channel.h b/src/connectivity/bluetooth/core/bt-host/l2cap/fake_channel.h index fa87caedfb7cae13310bde54771c2535408a0253..975a77ed4b94668e641a9241cc2cc640c344a562 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/fake_channel.h +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/fake_channel.h @@ -31,10 +31,10 @@ class FakeChannel : public Channel { // Routes the given data over to the rx handler as if it were received from // the controller. - void Receive(const common::ByteBuffer& data); + void Receive(const ByteBuffer& data); // Sets a delegate to notify when a frame was sent over the channel. - using SendCallback = fit::function<void(common::ByteBufferPtr)>; + using SendCallback = fit::function<void(ByteBufferPtr)>; void SetSendCallback(SendCallback callback, async_dispatcher_t* dispatcher); // Sets a callback to emulate the result of "SignalLinkError()". In @@ -73,7 +73,7 @@ class FakeChannel : public Channel { async_dispatcher_t* dispatcher) override; void Deactivate() override; void SignalLinkError() override; - bool Send(common::ByteBufferPtr sdu) override; + bool Send(ByteBufferPtr sdu) override; void UpgradeSecurity(sm::SecurityLevel level, sm::StatusCallback callback) override; @@ -100,7 +100,7 @@ class FakeChannel : public Channel { // The pending SDUs on this channel. Received PDUs are buffered if |rx_cb_| is // currently not set. - std::queue<common::ByteBufferPtr> pending_rx_sdus_; + std::queue<ByteBufferPtr> pending_rx_sdus_; fxl::WeakPtrFactory<FakeChannel> weak_ptr_factory_; diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/fake_channel_test.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/fake_channel_test.cc index 64f8a3638bf8c6664710db03396077815959229b..994d40f4eb564da5787b1c47cc512f167df0aae2 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/fake_channel_test.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/fake_channel_test.cc @@ -19,7 +19,7 @@ fbl::RefPtr<FakeChannel> FakeChannelTest::CreateFakeChannel( return fake_chan; } -bool FakeChannelTest::Expect(const common::ByteBuffer& expected) { +bool FakeChannelTest::Expect(const ByteBuffer& expected) { if (!fake_chan()) { bt_log(ERROR, "testing", "no channel, failing!"); return false; @@ -27,7 +27,7 @@ bool FakeChannelTest::Expect(const common::ByteBuffer& expected) { bool success = false; auto cb = [&expected, &success, this](auto cb_packet) { - success = common::ContainersEqual(expected, *cb_packet); + success = ContainersEqual(expected, *cb_packet); }; fake_chan()->SetSendCallback(cb, dispatcher()); @@ -36,9 +36,8 @@ bool FakeChannelTest::Expect(const common::ByteBuffer& expected) { return success; } -bool FakeChannelTest::ReceiveAndExpect( - const common::ByteBuffer& packet, - const common::ByteBuffer& expected_response) { +bool FakeChannelTest::ReceiveAndExpect(const ByteBuffer& packet, + const ByteBuffer& expected_response) { if (!fake_chan()) { bt_log(ERROR, "testing", "no channel, failing!"); return false; diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/fake_channel_test.h b/src/connectivity/bluetooth/core/bt-host/l2cap/fake_channel_test.h index 545460f4297a1fea42b5ce1cb6213befa43606c9..8cde5baed9e057bbbb8b40268057b7986687ed7c 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/fake_channel_test.h +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/fake_channel_test.h @@ -55,7 +55,7 @@ class FakeChannelTest : public ::gtest::TestLoopFixture { // // NOTE: This overwrites the underlying FakeChannel's "send callback" by // calling FakeChannel::SetSendCallback(). - bool Expect(const common::ByteBuffer& expected); + bool Expect(const ByteBuffer& expected); // Emulates the receipt of |packet| and returns true if a response that // matches |expected_response| is sent back over the underlying FakeChannel. @@ -64,8 +64,8 @@ class FakeChannelTest : public ::gtest::TestLoopFixture { // // NOTE: This overwrites the underlying FakeChannel's "send callback" by // calling FakeChannel::SetSendCallback(). - bool ReceiveAndExpect(const common::ByteBuffer& packet, - const common::ByteBuffer& expected_response); + bool ReceiveAndExpect(const ByteBuffer& packet, + const ByteBuffer& expected_response); fxl::WeakPtr<FakeChannel> fake_chan() const { return fake_chan_; } diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/fake_signaling_channel.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/fake_signaling_channel.cc index b10cec059e9e61f586cab61cfb3f4713672596be..a31efc775ae5b6549462823b6654895043860772 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/fake_signaling_channel.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/fake_signaling_channel.cc @@ -4,8 +4,8 @@ #include "src/connectivity/bluetooth/core/bt-host/l2cap/fake_signaling_channel.h" -#include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" #include "gtest/gtest.h" +#include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" namespace bt { namespace l2cap { @@ -19,7 +19,7 @@ namespace { // request handlers have to be tested for multiple responses to each request. class Expecter : public SignalingChannel::Responder { public: - void Send(const common::ByteBuffer& rsp_payload) override { + void Send(const ByteBuffer& rsp_payload) override { ADD_FAILURE() << "Unexpected local response " << rsp_payload.AsString(); } @@ -46,16 +46,16 @@ class Expecter : public SignalingChannel::Responder { class ResponseExpecter : public Expecter { public: - explicit ResponseExpecter(const common::ByteBuffer& expected_rsp) + explicit ResponseExpecter(const ByteBuffer& expected_rsp) : expected_rsp_(expected_rsp) {} - void Send(const common::ByteBuffer& rsp_payload) override { + void Send(const ByteBuffer& rsp_payload) override { set_called(true); - EXPECT_TRUE(common::ContainersEqual(expected_rsp_, rsp_payload)); + EXPECT_TRUE(ContainersEqual(expected_rsp_, rsp_payload)); } private: - const common::ByteBuffer& expected_rsp_; + const ByteBuffer& expected_rsp_; }; class RejectNotUnderstoodExpecter : public Expecter { @@ -97,7 +97,7 @@ FakeSignalingChannel::~FakeSignalingChannel() { } bool FakeSignalingChannel::SendRequest(CommandCode req_code, - const common::ByteBuffer& payload, + const ByteBuffer& payload, SignalingChannel::ResponseHandler cb) { if (expected_transaction_index_ >= transactions_.size()) { ADD_FAILURE() << "Received unexpected outbound command after handling " @@ -109,7 +109,7 @@ bool FakeSignalingChannel::SendRequest(CommandCode req_code, ::testing::ScopedTrace trace(transaction.file, transaction.line, "Outbound request expected here"); EXPECT_EQ(transaction.request_code, req_code); - EXPECT_TRUE(common::ContainersEqual(transaction.req_payload, payload)); + EXPECT_TRUE(ContainersEqual(transaction.req_payload, payload)); EXPECT_TRUE(cb); transaction.response_callback = std::move(cb); @@ -149,8 +149,7 @@ void FakeSignalingChannel::ServeRequest(CommandCode req_code, } FakeSignalingChannel::TransactionId FakeSignalingChannel::AddOutbound( - const char* file, int line, CommandCode req_code, - common::BufferView req_payload, + const char* file, int line, CommandCode req_code, BufferView req_payload, std::vector<FakeSignalingChannel::Response> responses) { transactions_.push_back(Transaction{file, line, req_code, std::move(req_payload), @@ -158,22 +157,22 @@ FakeSignalingChannel::TransactionId FakeSignalingChannel::AddOutbound( return transactions_.size() - 1; } -void FakeSignalingChannel::ReceiveExpect( - CommandCode req_code, const common::ByteBuffer& req_payload, - const common::ByteBuffer& rsp_payload) { +void FakeSignalingChannel::ReceiveExpect(CommandCode req_code, + const ByteBuffer& req_payload, + const ByteBuffer& rsp_payload) { ResponseExpecter expecter(rsp_payload); ReceiveExpectInternal(req_code, req_payload, &expecter); } void FakeSignalingChannel::ReceiveExpectRejectNotUnderstood( - CommandCode req_code, const common::ByteBuffer& req_payload) { + CommandCode req_code, const ByteBuffer& req_payload) { RejectNotUnderstoodExpecter expecter; ReceiveExpectInternal(req_code, req_payload, &expecter); } void FakeSignalingChannel::ReceiveExpectRejectInvalidChannelId( - CommandCode req_code, const common::ByteBuffer& req_payload, - ChannelId local_cid, ChannelId remote_cid) { + CommandCode req_code, const ByteBuffer& req_payload, ChannelId local_cid, + ChannelId remote_cid) { RejectInvalidChannelIdExpecter expecter(local_cid, remote_cid); ReceiveExpectInternal(req_code, req_payload, &expecter); } @@ -201,9 +200,9 @@ size_t FakeSignalingChannel::TriggerResponses( } // Test evaluator for inbound requests with type-erased, bound expected requests -void FakeSignalingChannel::ReceiveExpectInternal( - CommandCode req_code, const common::ByteBuffer& req_payload, - Responder* fake_responder) { +void FakeSignalingChannel::ReceiveExpectInternal(CommandCode req_code, + const ByteBuffer& req_payload, + Responder* fake_responder) { auto iter = request_handlers_.find(req_code); ASSERT_NE(request_handlers_.end(), iter); diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/fake_signaling_channel.h b/src/connectivity/bluetooth/core/bt-host/l2cap/fake_signaling_channel.h index c718591ebdef61b26ee326041f9e3c262fc83c6e..f979cb2a6b92b38ec816504a7a8d1b6eb03337c8 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/fake_signaling_channel.h +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/fake_signaling_channel.h @@ -6,6 +6,7 @@ #define SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_L2CAP_FAKE_SIGNALING_CHANNEL_H_ #include <lib/async/cpp/task.h> + #include <unordered_map> #include <vector> @@ -31,14 +32,14 @@ class FakeSignalingChannel : public SignalingChannelInterface { using TransactionId = size_t; // Simulated response's command code and payload. - using Response = std::pair<Status, common::BufferView>; + using Response = std::pair<Status, BufferView>; // |dispatcher| is the test message loop's dispatcher explicit FakeSignalingChannel(async_dispatcher_t* dispatcher); ~FakeSignalingChannel() override; // SignalingChannelInterface overrides - bool SendRequest(CommandCode req_code, const common::ByteBuffer& payload, + bool SendRequest(CommandCode req_code, const ByteBuffer& payload, ResponseHandler cb) override; void ServeRequest(CommandCode req_code, RequestDelegate cb) override; @@ -49,7 +50,7 @@ class FakeSignalingChannel : public SignalingChannelInterface { // Returns a handle that can be used to provide additional responses with // |ReceiveResponses|. |file| and |line| will be used to trace test failures. TransactionId AddOutbound(const char* file, int line, CommandCode req_code, - common::BufferView req_payload, + BufferView req_payload, std::vector<Response> responses); // Receive additional responses to an already received request. @@ -58,21 +59,21 @@ class FakeSignalingChannel : public SignalingChannelInterface { // Simulate reception of an inbound request with |req_code| and |req_payload|, // then expect a corresponding outbound response with payload |rsp_payload|. - void ReceiveExpect(CommandCode req_code, - const common::ByteBuffer& req_payload, - const common::ByteBuffer& rsp_payload); + void ReceiveExpect(CommandCode req_code, const ByteBuffer& req_payload, + const ByteBuffer& rsp_payload); // Simulate reception of an inbound request with |req_code| and |req_payload|, // then expect a matching rejection with the Not Understood reason. void ReceiveExpectRejectNotUnderstood(CommandCode req_code, - const common::ByteBuffer& req_payload); + const ByteBuffer& req_payload); // Simulate reception of an inbound request with |req_code| and |req_payload|, // then expect a matching rejection with the Invalid Channel ID reason and the // rejected IDs |local_cid| and |remote_cid|. - void ReceiveExpectRejectInvalidChannelId( - CommandCode req_code, const common::ByteBuffer& req_payload, - ChannelId local_cid, ChannelId remote_cid); + void ReceiveExpectRejectInvalidChannelId(CommandCode req_code, + const ByteBuffer& req_payload, + ChannelId local_cid, + ChannelId remote_cid); private: // Expected outbound request and response(s) that this fake sends back @@ -80,8 +81,8 @@ class FakeSignalingChannel : public SignalingChannelInterface { const char* const file; const int line; const CommandCode request_code; - const common::BufferView req_payload; - const std::vector<std::pair<Status, common::BufferView>> responses; + const BufferView req_payload; + const std::vector<std::pair<Status, BufferView>> responses; // Assigned when the request is actually sent SignalingChannel::ResponseHandler response_callback = nullptr; @@ -102,7 +103,7 @@ class FakeSignalingChannel : public SignalingChannelInterface { // expected to send and is passed to the handler-under-test. The test will // fail if no reply at all is sent. void ReceiveExpectInternal(CommandCode req_code, - const common::ByteBuffer& req_payload, + const ByteBuffer& req_payload, Responder* fake_responder); // Test message loop dispatcher diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/fragmenter.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/fragmenter.cc index 944fd5373445eec03a7b8ee4bbce81e5ff6b38d5..baa22e5b59afa3a96d66e104f8a842650f8d803d 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/fragmenter.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/fragmenter.cc @@ -48,8 +48,7 @@ Fragmenter::Fragmenter(hci::ConnectionHandle connection_handle, // 2. channel -> fragmenter ->(move) HCI layer ->(move) bt-hci driver // if buffering is needed: // 3. bt-hci driver -> transport driver -PDU Fragmenter::BuildBasicFrame(ChannelId channel_id, - const common::ByteBuffer& data, +PDU Fragmenter::BuildBasicFrame(ChannelId channel_id, const ByteBuffer& data, bool flushable) { ZX_DEBUG_ASSERT(data.size() <= kMaxBasicFramePayloadSize); ZX_DEBUG_ASSERT(channel_id); diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/fragmenter.h b/src/connectivity/bluetooth/core/bt-host/l2cap/fragmenter.h index 16f2401c8cd26047d73f1412576123e1c8278902..6fbcff9385d314707d9c8f28dcab1f80ecae5eaa 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/fragmenter.h +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/fragmenter.h @@ -52,7 +52,7 @@ class Fragmenter final { // links based on the setting of an automatic flush timer. Only // non-automatically flushable PDUs can be sent over LE-U links (see Core Spec // v5.0, Vol 2, Part E, Section 5.4.2). - PDU BuildBasicFrame(ChannelId channel_id, const common::ByteBuffer& data, + PDU BuildBasicFrame(ChannelId channel_id, const ByteBuffer& data, bool flushable = false); private: diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/fragmenter_unittest.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/fragmenter_unittest.cc index 0081066a7196d5c6ce98fdfe23dd76b88d0619c1..05f16b7c87a982b54b652b4c97e66cc2729d92dc 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/fragmenter_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/fragmenter_unittest.cc @@ -3,10 +3,9 @@ // found in the LICENSE file. #include "fragmenter.h" -#include "pdu.h" #include "gtest/gtest.h" - +#include "pdu.h" #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" #include "src/connectivity/bluetooth/core/bt-host/hci/hci.h" @@ -18,9 +17,9 @@ constexpr hci::ConnectionHandle kTestHandle = 0x0001; constexpr ChannelId kTestChannelId = 0x0001; TEST(L2CAP_FragmenterTest, EmptyPayload) { - common::BufferView payload; + BufferView payload; - auto expected_fragment = common::CreateStaticByteBuffer( + auto expected_fragment = CreateStaticByteBuffer( // ACL data header 0x01, 0x00, 0x04, 0x00, @@ -35,14 +34,14 @@ TEST(L2CAP_FragmenterTest, EmptyPayload) { auto fragments = pdu.ReleaseFragments(); - EXPECT_TRUE(common::ContainersEqual(expected_fragment, - fragments.begin()->view().data())); + EXPECT_TRUE( + ContainersEqual(expected_fragment, fragments.begin()->view().data())); } TEST(L2CAP_FragmenterTest, SingleFragment) { - auto payload = common::CreateStaticByteBuffer('T', 'e', 's', 't'); + auto payload = CreateStaticByteBuffer('T', 'e', 's', 't'); - auto expected_fragment = common::CreateStaticByteBuffer( + auto expected_fragment = CreateStaticByteBuffer( // ACL data header 0x01, 0x00, 0x08, 0x00, @@ -57,14 +56,14 @@ TEST(L2CAP_FragmenterTest, SingleFragment) { auto fragments = pdu.ReleaseFragments(); - EXPECT_TRUE(common::ContainersEqual(expected_fragment, - fragments.begin()->view().data())); + EXPECT_TRUE( + ContainersEqual(expected_fragment, fragments.begin()->view().data())); } TEST(L2CAP_FragmenterTest, SingleFragmentExactFit) { - auto payload = common::CreateStaticByteBuffer('T', 'e', 's', 't'); + auto payload = CreateStaticByteBuffer('T', 'e', 's', 't'); - auto expected_fragment = common::CreateStaticByteBuffer( + auto expected_fragment = CreateStaticByteBuffer( // ACL data header 0x01, 0x00, 0x08, 0x00, @@ -80,21 +79,21 @@ TEST(L2CAP_FragmenterTest, SingleFragmentExactFit) { auto fragments = pdu.ReleaseFragments(); - EXPECT_TRUE(common::ContainersEqual(expected_fragment, - fragments.begin()->view().data())); + EXPECT_TRUE( + ContainersEqual(expected_fragment, fragments.begin()->view().data())); } TEST(L2CAP_FragmenterTest, TwoFragmentsOffByOne) { - auto payload = common::CreateStaticByteBuffer('T', 'e', 's', 't', '!'); + auto payload = CreateStaticByteBuffer('T', 'e', 's', 't', '!'); - auto expected_fragment0 = common::CreateStaticByteBuffer( + auto expected_fragment0 = CreateStaticByteBuffer( // ACL data header 0x01, 0x00, 0x08, 0x00, // Basic L2CAP header, contains the complete length but a partial payload 0x05, 0x00, 0x01, 0x00, 'T', 'e', 's', 't'); - auto expected_fragment1 = common::CreateStaticByteBuffer( + auto expected_fragment1 = CreateStaticByteBuffer( // ACL data header 0x01, 0x10, 0x01, 0x00, @@ -111,25 +110,25 @@ TEST(L2CAP_FragmenterTest, TwoFragmentsOffByOne) { auto fragments = pdu.ReleaseFragments(); - EXPECT_TRUE(common::ContainersEqual(expected_fragment0, - fragments.begin()->view().data())); - EXPECT_TRUE(common::ContainersEqual(expected_fragment1, - (++fragments.begin())->view().data())); + EXPECT_TRUE( + ContainersEqual(expected_fragment0, fragments.begin()->view().data())); + EXPECT_TRUE(ContainersEqual(expected_fragment1, + (++fragments.begin())->view().data())); } TEST(L2CAP_FragmenterTest, TwoFragmentsExact) { - auto payload = common::CreateStaticByteBuffer('T', 'e', 's', 't'); + auto payload = CreateStaticByteBuffer('T', 'e', 's', 't'); ZX_DEBUG_ASSERT_MSG(payload.size() % 2 == 0, "test payload size should be even"); - auto expected_fragment0 = common::CreateStaticByteBuffer( + auto expected_fragment0 = CreateStaticByteBuffer( // ACL data header 0x01, 0x00, 0x04, 0x00, // Basic L2CAP header, contains the complete length but a partial payload 0x04, 0x00, 0x01, 0x00); - auto expected_fragment1 = common::CreateStaticByteBuffer( + auto expected_fragment1 = CreateStaticByteBuffer( // ACL data header 0x01, 0x10, 0x04, 0x00, @@ -147,10 +146,10 @@ TEST(L2CAP_FragmenterTest, TwoFragmentsExact) { auto fragments = pdu.ReleaseFragments(); - EXPECT_TRUE(common::ContainersEqual(expected_fragment0, - fragments.begin()->view().data())); - EXPECT_TRUE(common::ContainersEqual(expected_fragment1, - (++fragments.begin())->view().data())); + EXPECT_TRUE( + ContainersEqual(expected_fragment0, fragments.begin()->view().data())); + EXPECT_TRUE(ContainersEqual(expected_fragment1, + (++fragments.begin())->view().data())); } TEST(L2CAP_FragmenterTest, ManyFragmentsOffByOne) { @@ -159,31 +158,31 @@ TEST(L2CAP_FragmenterTest, ManyFragmentsOffByOne) { constexpr size_t kFrameSize = (kExpectedFragmentCount - 1) * kMaxFragmentPayloadSize + 1; - common::StaticByteBuffer<kFrameSize - sizeof(BasicHeader)> payload; + StaticByteBuffer<kFrameSize - sizeof(BasicHeader)> payload; payload.Fill('X'); - auto expected_fragment0 = common::CreateStaticByteBuffer( + auto expected_fragment0 = CreateStaticByteBuffer( // ACL data header 0x01, 0x00, 0x05, 0x00, // Basic L2CAP header contains the complete length but partial payload 0x0C, 0x00, 0x01, 0x00, 'X'); - auto expected_fragment1 = common::CreateStaticByteBuffer( + auto expected_fragment1 = CreateStaticByteBuffer( // ACL data header 0x01, 0x10, 0x05, 0x00, // Continuing payload 'X', 'X', 'X', 'X', 'X'); - auto expected_fragment2 = common::CreateStaticByteBuffer( + auto expected_fragment2 = CreateStaticByteBuffer( // ACL data header 0x01, 0x10, 0x05, 0x00, // Continuing payload 'X', 'X', 'X', 'X', 'X'); - auto expected_fragment3 = common::CreateStaticByteBuffer( + auto expected_fragment3 = CreateStaticByteBuffer( // ACL data header 0x01, 0x10, 0x01, 0x00, @@ -197,17 +196,14 @@ TEST(L2CAP_FragmenterTest, ManyFragmentsOffByOne) { auto fragments = pdu.ReleaseFragments(); auto iter = fragments.begin(); - EXPECT_TRUE( - common::ContainersEqual(expected_fragment0, (iter++)->view().data())); - EXPECT_TRUE( - common::ContainersEqual(expected_fragment1, (iter++)->view().data())); - EXPECT_TRUE( - common::ContainersEqual(expected_fragment2, (iter++)->view().data())); - EXPECT_TRUE(common::ContainersEqual(expected_fragment3, iter->view().data())); + EXPECT_TRUE(ContainersEqual(expected_fragment0, (iter++)->view().data())); + EXPECT_TRUE(ContainersEqual(expected_fragment1, (iter++)->view().data())); + EXPECT_TRUE(ContainersEqual(expected_fragment2, (iter++)->view().data())); + EXPECT_TRUE(ContainersEqual(expected_fragment3, iter->view().data())); } TEST(L2CAP_FragmenterTest, MaximalSizedPayload) { - common::DynamicByteBuffer payload(65535); + DynamicByteBuffer payload(65535); Fragmenter fragmenter(kTestHandle, 1024); PDU pdu = fragmenter.BuildBasicFrame(kTestChannelId, payload); ASSERT_TRUE(pdu.is_valid()); diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/frame_headers_unittest.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/frame_headers_unittest.cc index e74da094c6e989d13a267be68cf8d59a81b0687e..8cb9631da9d94e4ff48fd15609065f24736a4bcd 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/frame_headers_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/frame_headers_unittest.cc @@ -14,9 +14,6 @@ namespace l2cap { namespace internal { namespace { -using common::BufferView; -using common::CreateStaticByteBuffer; - TEST(L2CAP_FrameHeaders_EnhancedControlFieldTest, IdentifiesInformationFrame) { // See Core Spec, v5, Vol 3, Part A, Table 3.2. EXPECT_TRUE(CreateStaticByteBuffer(0b0000'0000, 0) diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/le_signaling_channel.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/le_signaling_channel.cc index 4d2ddb7351418db1c067fb300bd06a2c8daf0c79..5020227ae320727c6edf2e5ff8aa03bdcb546def 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/le_signaling_channel.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/le_signaling_channel.cc @@ -4,10 +4,9 @@ #include "le_signaling_channel.h" -#include "src/connectivity/bluetooth/core/bt-host/common/log.h" - #include "channel.h" #include "logical_link.h" +#include "src/connectivity/bluetooth/core/bt-host/common/log.h" namespace bt { namespace l2cap { @@ -20,7 +19,7 @@ LESignalingChannel::LESignalingChannel(fbl::RefPtr<Channel> chan, } bool LESignalingChannel::SendRequest(CommandCode req_code, - const common::ByteBuffer& payload, + const ByteBuffer& payload, ResponseHandler cb) { // TODO(NET-1093): Reuse BrEdrSignalingChannel's implementation. bt_log(WARN, "l2cap-le", "sig: SendRequest not implemented yet"); @@ -41,7 +40,7 @@ void LESignalingChannel::OnConnParamUpdateReceived( bt_log(TRACE, "l2cap-le", "sig: rejecting conn. param. update request from master"); SendCommandReject(packet.header().id, RejectReason::kNotUnderstood, - common::BufferView()); + BufferView()); return; } @@ -49,7 +48,7 @@ void LESignalingChannel::OnConnParamUpdateReceived( sizeof(ConnectionParameterUpdateRequestPayload)) { bt_log(TRACE, "l2cap-le", "sig: malformed request received"); SendCommandReject(packet.header().id, RejectReason::kNotUnderstood, - common::BufferView()); + BufferView()); return; } @@ -97,7 +96,7 @@ void LESignalingChannel::OnConnParamUpdateReceived( ConnectionParameterUpdateResponsePayload rsp; rsp.result = static_cast<ConnectionParameterUpdateResult>(htole16(result)); SendPacket(kConnectionParameterUpdateResponse, packet.header().id, - common::BufferView(&rsp, sizeof(rsp))); + BufferView(&rsp, sizeof(rsp))); if (!reject && dispatcher_) { async::PostTask(dispatcher_, [cb = conn_param_update_cb_.share(), @@ -107,7 +106,7 @@ void LESignalingChannel::OnConnParamUpdateReceived( } } -void LESignalingChannel::DecodeRxUnit(common::ByteBufferPtr sdu, +void LESignalingChannel::DecodeRxUnit(ByteBufferPtr sdu, const SignalingPacketHandler& cb) { // "[O]nly one command per C-frame shall be sent over [the LE] Fixed Channel" // (v5.0, Vol 3, Part A, Section 4). @@ -124,7 +123,7 @@ void LESignalingChannel::DecodeRxUnit(common::ByteBufferPtr sdu, "sig: packet size mismatch (expected: %u, recv: %zu); drop", expected_payload_length, sdu->size() - sizeof(CommandHeader)); SendCommandReject(packet.header().id, RejectReason::kNotUnderstood, - common::BufferView()); + BufferView()); return; } diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/le_signaling_channel.h b/src/connectivity/bluetooth/core/bt-host/l2cap/le_signaling_channel.h index bf5903d892bb942d02239fda3ccba69f74d50c38..11a6605191037a7318b6b1a41a4651e194c73de7 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/le_signaling_channel.h +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/le_signaling_channel.h @@ -25,7 +25,7 @@ class LESignalingChannel final : public SignalingChannel { ~LESignalingChannel() override = default; // SignalingChannelInterface overrides - bool SendRequest(CommandCode req_code, const common::ByteBuffer& payload, + bool SendRequest(CommandCode req_code, const ByteBuffer& payload, ResponseHandler cb) override; void ServeRequest(CommandCode req_code, RequestDelegate cb) override; @@ -49,7 +49,7 @@ class LESignalingChannel final : public SignalingChannel { void OnConnParamUpdateReceived(const SignalingPacket& packet); // SignalingChannel override - void DecodeRxUnit(common::ByteBufferPtr sdu, + void DecodeRxUnit(ByteBufferPtr sdu, const SignalingPacketHandler& cb) override; bool HandlePacket(const SignalingPacket& packet) override; diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/le_signaling_channel_unittest.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/le_signaling_channel_unittest.cc index 65be74126f3aa09e4ef0721d95004affefc15b3b..5113b751501eaf170fc44d048629688cf73ef04d 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/le_signaling_channel_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/le_signaling_channel_unittest.cc @@ -51,7 +51,7 @@ TEST_F(L2CAP_LESignalingChannelTest, IgnoreEmptyFrame) { auto send_cb = [&send_cb_called](auto) { send_cb_called = true; }; fake_chan()->SetSendCallback(std::move(send_cb), dispatcher()); - fake_chan()->Receive(common::BufferView()); + fake_chan()->Receive(BufferView()); RunLoopUntilIdle(); EXPECT_FALSE(send_cb_called); @@ -60,7 +60,7 @@ TEST_F(L2CAP_LESignalingChannelTest, IgnoreEmptyFrame) { TEST_F(L2CAP_LESignalingChannelTest, RejectMalformedTooLarge) { // Command Reject packet. // clang-format off - auto expected = common::CreateStaticByteBuffer( + auto expected = CreateStaticByteBuffer( // Command header 0x01, kTestCmdId, 0x02, 0x00, @@ -69,7 +69,7 @@ TEST_F(L2CAP_LESignalingChannelTest, RejectMalformedTooLarge) { // Header-encoded length is less than the otherwise-valid Connection Parameter // Update packet's payload size. - auto cmd_with_oversize_payload = common::CreateStaticByteBuffer( + auto cmd_with_oversize_payload = CreateStaticByteBuffer( 0x12, kTestCmdId, 0x07, 0x00, // Valid connection parameters @@ -85,7 +85,7 @@ TEST_F(L2CAP_LESignalingChannelTest, RejectMalformedTooLarge) { TEST_F(L2CAP_LESignalingChannelTest, RejectMalformedTooSmall) { // Command Reject packet. // clang-format off - auto expected = common::CreateStaticByteBuffer( + auto expected = CreateStaticByteBuffer( // Command header 0x01, kTestCmdId, 0x02, 0x00, @@ -94,7 +94,7 @@ TEST_F(L2CAP_LESignalingChannelTest, RejectMalformedTooSmall) { // Header-encoded length is more than the otherwise-valid Connection Parameter // Update packet's payload size. - auto cmd_with_undersize_payload = common::CreateStaticByteBuffer( + auto cmd_with_undersize_payload = CreateStaticByteBuffer( 0x12, kTestCmdId, 0x09, 0x00, // Valid connection parameters @@ -112,7 +112,7 @@ TEST_F(L2CAP_LESignalingChannelTest, DefaultMTU) { // The channel should start out with the minimum MTU as the default (23 // octets). - common::StaticByteBuffer<kCommandSize> cmd; + StaticByteBuffer<kCommandSize> cmd; // Make sure that the packet is well formed (the command code does not // matter). @@ -122,7 +122,7 @@ TEST_F(L2CAP_LESignalingChannelTest, DefaultMTU) { // Command Reject packet. // clang-format off - auto expected = common::CreateStaticByteBuffer( + auto expected = CreateStaticByteBuffer( // Command header 0x01, kTestCmdId, 0x04, 0x00, @@ -146,11 +146,11 @@ TEST_F(L2CAP_LESignalingChannelTest, UnknownCommand) { continue; // Use command code as ID. - auto cmd = common::CreateStaticByteBuffer(code, code, 0x00, 0x00); + auto cmd = CreateStaticByteBuffer(code, code, 0x00, 0x00); // Expected // clang-format off - auto expected = common::CreateStaticByteBuffer( + auto expected = CreateStaticByteBuffer( // Command header 0x01, code, 0x02, 0x00, @@ -165,7 +165,7 @@ TEST_F(L2CAP_LESignalingChannelTest, UnknownCommand) { TEST_F(L2CAP_LESignalingChannelTest, ConnParamUpdateMalformedPayloadTooLarge) { // Packet size larger than conn. param. update payload. // clang-format off - auto cmd = common::CreateStaticByteBuffer( + auto cmd = CreateStaticByteBuffer( 0x12, kTestCmdId, 0x09, 0x00, // Valid conn. param. values: @@ -177,7 +177,7 @@ TEST_F(L2CAP_LESignalingChannelTest, ConnParamUpdateMalformedPayloadTooLarge) { // Extra byte 0x00); - auto expected = common::CreateStaticByteBuffer( + auto expected = CreateStaticByteBuffer( // Command header 0x01, kTestCmdId, 0x02, 0x00, @@ -191,7 +191,7 @@ TEST_F(L2CAP_LESignalingChannelTest, ConnParamUpdateMalformedPayloadTooLarge) { TEST_F(L2CAP_LESignalingChannelTest, ConnParamUpdateMalformedPayloadTooSmall) { // Packet size larger than conn. param. update payload. // clang-format off - auto cmd = common::CreateStaticByteBuffer( + auto cmd = CreateStaticByteBuffer( 0x12, kTestCmdId, 0x07, 0x00, // Valid conn. param. values: @@ -200,7 +200,7 @@ TEST_F(L2CAP_LESignalingChannelTest, ConnParamUpdateMalformedPayloadTooSmall) { 0xF3, 0x01, 0x0A/*0x00 // Missing a byte */); - auto expected = common::CreateStaticByteBuffer( + auto expected = CreateStaticByteBuffer( // Command header 0x01, kTestCmdId, 0x02, 0x00, @@ -213,43 +213,43 @@ TEST_F(L2CAP_LESignalingChannelTest, ConnParamUpdateMalformedPayloadTooSmall) { TEST_F(L2CAP_LESignalingChannelTest, ConnParamUpdateReject) { // clang-format off - common::StaticByteBuffer<12> commands[] = { - common::CreateStaticByteBuffer( + StaticByteBuffer<12> commands[] = { + CreateStaticByteBuffer( 0x12, kTestCmdId, 0x08, 0x00, 0x07, 0x00, // interval min larger than max (both within range) 0x06, 0x00, 0xF3, 0x01, 0x0A, 0x00), - common::CreateStaticByteBuffer( + CreateStaticByteBuffer( 0x12, kTestCmdId, 0x08, 0x00, 0x05, 0x00, // interval min too small 0x80, 0x0C, 0xF3, 0x01, 0x0A, 0x00), - common::CreateStaticByteBuffer( + CreateStaticByteBuffer( 0x12, kTestCmdId, 0x08, 0x00, 0x06, 0x00, 0x81, 0x0C, // interval max too large 0xF3, 0x01, 0x0A, 0x00), - common::CreateStaticByteBuffer( + CreateStaticByteBuffer( 0x12, kTestCmdId, 0x08, 0x00, 0x06, 0x00, 0x80, 0x0C, 0xF4, 0x01, // Latency too large 0x0A, 0x00), - common::CreateStaticByteBuffer( + CreateStaticByteBuffer( 0x12, kTestCmdId, 0x08, 0x00, 0x06, 0x00, 0x80, 0x0C, 0xF3, 0x01, 0x09, 0x00), // Supv. timeout too small - common::CreateStaticByteBuffer( + CreateStaticByteBuffer( 0x12, kTestCmdId, 0x08, 0x00, 0x06, 0x00, @@ -262,7 +262,7 @@ TEST_F(L2CAP_LESignalingChannelTest, ConnParamUpdateReject) { for (size_t i = 0; i < arraysize(commands); ++i) { // Conn. param. update response // clang-format off - auto expected = common::CreateStaticByteBuffer( + auto expected = CreateStaticByteBuffer( // Command header 0x13, kTestCmdId, 0x02, 0x00, @@ -276,7 +276,7 @@ TEST_F(L2CAP_LESignalingChannelTest, ConnParamUpdateReject) { TEST_F(L2CAP_LESignalingChannelTest, ConnParamUpdateAccept) { // clang-format off - auto cmd = common::CreateStaticByteBuffer( + auto cmd = CreateStaticByteBuffer( 0x12, kTestCmdId, 0x08, 0x00, // Valid connection parameters @@ -286,7 +286,7 @@ TEST_F(L2CAP_LESignalingChannelTest, ConnParamUpdateAccept) { 0x80, 0x0C); // Conn. param. update response - auto expected = common::CreateStaticByteBuffer( + auto expected = CreateStaticByteBuffer( // Command header 0x13, kTestCmdId, 0x02, 0x00, @@ -296,7 +296,7 @@ TEST_F(L2CAP_LESignalingChannelTest, ConnParamUpdateAccept) { bool fake_chan_cb_called = false; auto fake_chan_cb = [&expected, &fake_chan_cb_called, this](auto packet) { - EXPECT_TRUE(common::ContainersEqual(expected, *packet)); + EXPECT_TRUE(ContainersEqual(expected, *packet)); fake_chan_cb_called = true; }; @@ -322,7 +322,7 @@ TEST_F(L2CAP_LESignalingChannelTest, ConnParamUpdateAccept) { TEST_F(L2CAP_LESignalingChannelSlaveTest, ConnParamUpdateReject) { // clang-format off - auto cmd = common::CreateStaticByteBuffer( + auto cmd = CreateStaticByteBuffer( 0x12, kTestCmdId, 0x08, 0x00, // Valid connection parameters @@ -332,7 +332,7 @@ TEST_F(L2CAP_LESignalingChannelSlaveTest, ConnParamUpdateReject) { 0x80, 0x0C); // Command rejected - auto expected = common::CreateStaticByteBuffer( + auto expected = CreateStaticByteBuffer( // Command header 0x01, kTestCmdId, 0x02, 0x00, @@ -342,7 +342,7 @@ TEST_F(L2CAP_LESignalingChannelSlaveTest, ConnParamUpdateReject) { bool cb_called = false; auto cb = [&expected, &cb_called, this](auto packet) { - EXPECT_TRUE(common::ContainersEqual(expected, *packet)); + EXPECT_TRUE(ContainersEqual(expected, *packet)); cb_called = true; }; diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/logical_link.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/logical_link.cc index 5fdf89eda1c33a1542781a2a1f0bfc1ee7fdabca..e8cb551a1b0c9f327225b45f1961e61924ad0c9a 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/logical_link.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/logical_link.cc @@ -4,18 +4,17 @@ #include "logical_link.h" -#include <functional> - #include <zircon/assert.h> -#include "src/connectivity/bluetooth/core/bt-host/common/log.h" -#include "src/connectivity/bluetooth/core/bt-host/hci/transport.h" -#include "src/lib/fxl/strings/string_printf.h" +#include <functional> #include "bredr_dynamic_channel.h" #include "bredr_signaling_channel.h" #include "channel.h" #include "le_signaling_channel.h" +#include "src/connectivity/bluetooth/core/bt-host/common/log.h" +#include "src/connectivity/bluetooth/core/bt-host/hci/transport.h" +#include "src/lib/fxl/strings/string_printf.h" namespace bt { namespace l2cap { @@ -272,8 +271,7 @@ void LogicalLink::AssignSecurityProperties( security_ = security; } -void LogicalLink::SendBasicFrame(ChannelId id, - const common::ByteBuffer& payload) { +void LogicalLink::SendBasicFrame(ChannelId id, const ByteBuffer& payload) { ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); if (closed_) { diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/logical_link.h b/src/connectivity/bluetooth/core/bt-host/l2cap/logical_link.h index b8eec633f69289dd5dea079c7e571ab5f822e681..f0a9d4baf05b6ef8579f0fa243ea44b7bc1cbc7e 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/logical_link.h +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/logical_link.h @@ -87,7 +87,7 @@ class LogicalLink final : public fbl::RefCounted<LogicalLink> { // thread. // // It is safe to call this function on a closed link; it will have no effect. - void SendBasicFrame(ChannelId remote_id, const common::ByteBuffer& payload); + void SendBasicFrame(ChannelId remote_id, const ByteBuffer& payload); // Requests a security upgrade using the registered security upgrade callback. // Invokes the |callback| argument with the result of the operation. diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/pdu.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/pdu.cc index 9c8cbb2828b2e2e8be8592119294ca8f1d7f9aae..ac052bd8f038334aaf29aa4f2b1bf8b2831c6bc8 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/pdu.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/pdu.cc @@ -26,8 +26,7 @@ PDU& PDU::operator=(PDU&& other) { return *this; } -size_t PDU::Copy(common::MutableByteBuffer* out_buffer, size_t pos, - size_t size) const { +size_t PDU::Copy(MutableByteBuffer* out_buffer, size_t pos, size_t size) const { ZX_DEBUG_ASSERT(out_buffer); ZX_DEBUG_ASSERT(pos <= length()); ZX_DEBUG_ASSERT(is_valid()); diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/pdu.h b/src/connectivity/bluetooth/core/bt-host/l2cap/pdu.h index f3339dbaef3a92eec7785d26f5c30d734fe85ba5..48d401106ead8123d68f1c9292ff340b5f3c8e48 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/pdu.h +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/pdu.h @@ -25,7 +25,7 @@ namespace l2cap { // Recombiner or Fragmenter. // // A PDU instance is light-weight (it consists of a single unique_ptr via -// common::LinkedList and a size_t field) and can be passed around by value. +// LinkedList and a size_t field) and can be passed around by value. // As the PDU uniquely owns its chain of fragments, a PDU is move-only. // // THREAD-SAFETY: @@ -34,7 +34,7 @@ namespace l2cap { // instance will be accessed on multiple threads. class PDU final { public: - using FragmentList = common::LinkedList<hci::ACLDataPacket>; + using FragmentList = LinkedList<hci::ACLDataPacket>; PDU(); ~PDU() = default; @@ -80,7 +80,7 @@ class PDU final { // NOTE: Use this method wisely as it can be costly. In particular, large // values of |pos| will incur a cost (O(pos)) as the underlying fragments need // to be traversed to find the initial fragment. - size_t Copy(common::MutableByteBuffer* out_buffer, size_t pos = 0, + size_t Copy(MutableByteBuffer* out_buffer, size_t pos = 0, size_t size = std::numeric_limits<std::size_t>::max()) const; // Release ownership of the current fragments, moving them to the caller. Once diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/pdu_unittest.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/pdu_unittest.cc index ac1d754b8b3aed51205362d6260916cdde683e45..13dcde81974ac6f5988a546ccc8222e268ad58cc 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/pdu_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/pdu_unittest.cc @@ -3,11 +3,10 @@ // found in the LICENSE file. #include "pdu.h" -#include "fragmenter.h" -#include "recombiner.h" +#include "fragmenter.h" #include "gtest/gtest.h" - +#include "recombiner.h" #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" #include "src/connectivity/bluetooth/core/bt-host/hci/hci.h" #include "src/connectivity/bluetooth/core/bt-host/hci/packet.h" @@ -16,8 +15,6 @@ namespace bt { namespace l2cap { namespace { -using common::CreateStaticByteBuffer; - template <typename... T> hci::ACLDataPacketPtr PacketFromBytes(T... data) { auto bytes = CreateStaticByteBuffer(std::forward<T>(data)...); @@ -54,7 +51,7 @@ TEST(L2CAP_PduTest, CanCopyEmptyBody) { ASSERT_EQ(1u, pdu.fragment_count()); ASSERT_EQ(0u, pdu.length()); - common::DynamicByteBuffer buf(0); + DynamicByteBuffer buf(0); EXPECT_EQ(0u, pdu.Copy(&buf)); } @@ -80,7 +77,7 @@ TEST(L2CAP_PduTest, Move) { EXPECT_TRUE(pdu.is_valid()); EXPECT_EQ(1u, pdu.fragment_count()); - common::StaticByteBuffer<4> pdu_data; + StaticByteBuffer<4> pdu_data; // Read the entire PDU. EXPECT_EQ(4u, pdu.Copy(&pdu_data)); @@ -143,8 +140,7 @@ TEST(L2CAP_PduTest, ReleaseFragments) { EXPECT_EQ(1u, count); // Check that the fragment we got out is identical to the one we fed in. - EXPECT_TRUE( - common::ContainersEqual(common::CreateStaticByteBuffer( + EXPECT_TRUE(ContainersEqual(CreateStaticByteBuffer( // ACL data header 0x01, 0x00, 0x08, 0x00, @@ -174,7 +170,7 @@ TEST(L2CAP_PduTest, ReadSingleFragment) { EXPECT_TRUE(recombiner.Release(&pdu)); EXPECT_TRUE(pdu.is_valid()); - common::StaticByteBuffer<4> pdu_data; + StaticByteBuffer<4> pdu_data; // Read the entire PDU. EXPECT_EQ(4u, pdu.Copy(&pdu_data)); @@ -247,7 +243,7 @@ TEST(L2CAP_PduTest, ReadMultipleFragments) { EXPECT_TRUE(pdu.is_valid()); EXPECT_EQ(4u, pdu.fragment_count()); - common::StaticByteBuffer<15> pdu_data; + StaticByteBuffer<15> pdu_data; // Read the entire PDU. EXPECT_EQ(15u, pdu.Copy(&pdu_data)); diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/recombiner_unittest.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/recombiner_unittest.cc index 9f056be40954e69ad0d99c7895a54d0d47eb372e..aaf9520e40ce4f02893cdcaa0fbaf6ba53f58747 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/recombiner_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/recombiner_unittest.cc @@ -3,10 +3,9 @@ // found in the LICENSE file. #include "recombiner.h" -#include "pdu.h" #include "gtest/gtest.h" - +#include "pdu.h" #include "src/connectivity/bluetooth/core/bt-host/hci/hci.h" #include "src/connectivity/bluetooth/core/bt-host/hci/packet.h" @@ -16,7 +15,7 @@ namespace { template <typename... T> hci::ACLDataPacketPtr PacketFromBytes(T... data) { - auto bytes = common::CreateStaticByteBuffer(std::forward<T>(data)...); + auto bytes = CreateStaticByteBuffer(std::forward<T>(data)...); ZX_DEBUG_ASSERT(bytes.size() >= sizeof(hci::ACLDataHeader)); auto packet = @@ -178,7 +177,7 @@ TEST(L2CAP_RecombinerTest, CompleteFirstFragment) { ASSERT_EQ(4u, pdu.length()); - common::StaticByteBuffer<4> pdu_data; + StaticByteBuffer<4> pdu_data; pdu.Copy(&pdu_data); EXPECT_EQ("Test", pdu_data.AsString()); @@ -284,7 +283,7 @@ TEST(L2CAP_RecombinerTest, CompleteContinuationFragment) { ASSERT_EQ(4u, pdu.length()); - common::StaticByteBuffer<4> pdu_data; + StaticByteBuffer<4> pdu_data; pdu.Copy(&pdu_data); EXPECT_EQ("Test", pdu_data.AsString()); @@ -360,7 +359,7 @@ TEST(L2CAP_RecombinerTest, MultipleContinuationFragments) { ASSERT_EQ(15u, pdu.length()); - common::StaticByteBuffer<15u> pdu_data; + StaticByteBuffer<15u> pdu_data; pdu.Copy(&pdu_data); EXPECT_EQ("This is a test!", pdu_data.AsString()); diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/rx_engine.h b/src/connectivity/bluetooth/core/bt-host/l2cap/rx_engine.h index d79927d9cf73732029a9510dfe0f69ab7b64bce7..f4e9de148cb3ca2d44f6d88056ac06f34f6fddf2 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/rx_engine.h +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/rx_engine.h @@ -25,7 +25,7 @@ class RxEngine { // nullptr if no SDU was produced. Callers should not interpret a nullptr as // an error, as there are many valid conditions under which a PDU does not // yield an SDU. - virtual common::ByteBufferPtr ProcessPdu(PDU) = 0; + virtual ByteBufferPtr ProcessPdu(PDU) = 0; private: DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(RxEngine); diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/scoped_channel_unittest.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/scoped_channel_unittest.cc index da10fbdd77816023ad417d0b34ddd5d194795189..0920837ccaa10a6bdd6b63c2a859ee6b172c33ed 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/scoped_channel_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/scoped_channel_unittest.cc @@ -4,9 +4,8 @@ #include "scoped_channel.h" -#include "gtest/gtest.h" - #include "fake_channel.h" +#include "gtest/gtest.h" namespace bt { namespace l2cap { @@ -14,7 +13,7 @@ namespace testing { namespace { void DoNothing() {} -void NopRxCallback(common::ByteBufferPtr) {} +void NopRxCallback(ByteBufferPtr) {} } // namespace diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/signaling_channel.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/signaling_channel.cc index 0022c89cf1a245ed13ebaf3b56df76ae99ffd3d4..5cfc51400bea0b4a5b15e60acb5420965fbcc8c6 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/signaling_channel.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/signaling_channel.cc @@ -8,11 +8,10 @@ #include <lib/fit/function.h> #include <zircon/assert.h> +#include "channel.h" #include "src/connectivity/bluetooth/core/bt-host/common/log.h" #include "src/connectivity/bluetooth/core/bt-host/common/slab_allocator.h" -#include "channel.h" - namespace bt { namespace l2cap { namespace internal { @@ -32,7 +31,7 @@ SignalingChannel::SignalingChannel(fbl::RefPtr<Channel> chan, // called on the L2CAP thread. auto self = weak_ptr_factory_.GetWeakPtr(); chan_->Activate( - [self](common::ByteBufferPtr sdu) { + [self](ByteBufferPtr sdu) { if (self) self->OnRxBFrame(std::move(sdu)); }, @@ -53,14 +52,12 @@ SignalingChannel::ResponderImpl::ResponderImpl(SignalingChannel* sig, ZX_DEBUG_ASSERT(sig_); } -void SignalingChannel::ResponderImpl::Send( - const common::ByteBuffer& rsp_payload) { +void SignalingChannel::ResponderImpl::Send(const ByteBuffer& rsp_payload) { sig()->SendPacket(code_, id_, rsp_payload); } void SignalingChannel::ResponderImpl::RejectNotUnderstood() { - sig()->SendCommandReject(id_, RejectReason::kNotUnderstood, - common::BufferView()); + sig()->SendCommandReject(id_, RejectReason::kNotUnderstood, BufferView()); } void SignalingChannel::ResponderImpl::RejectInvalidChannelId( @@ -69,16 +66,16 @@ void SignalingChannel::ResponderImpl::RejectInvalidChannelId( ids[0] = htole16(local_cid); ids[1] = htole16(remote_cid); sig()->SendCommandReject(id_, RejectReason::kInvalidCID, - common::BufferView(ids, sizeof(ids))); + BufferView(ids, sizeof(ids))); } bool SignalingChannel::SendPacket(CommandCode code, uint8_t identifier, - const common::ByteBuffer& data) { + const ByteBuffer& data) { ZX_DEBUG_ASSERT(IsCreationThreadCurrent()); return Send(BuildPacket(code, identifier, data)); } -bool SignalingChannel::Send(common::ByteBufferPtr packet) { +bool SignalingChannel::Send(ByteBufferPtr packet) { ZX_DEBUG_ASSERT(IsCreationThreadCurrent()); ZX_DEBUG_ASSERT(packet); ZX_DEBUG_ASSERT(packet->size() >= sizeof(CommandHeader)); @@ -99,11 +96,12 @@ bool SignalingChannel::Send(common::ByteBufferPtr packet) { return chan_->Send(std::move(packet)); } -common::ByteBufferPtr SignalingChannel::BuildPacket( - CommandCode code, uint8_t identifier, const common::ByteBuffer& data) { +ByteBufferPtr SignalingChannel::BuildPacket(CommandCode code, + uint8_t identifier, + const ByteBuffer& data) { ZX_DEBUG_ASSERT(data.size() <= std::numeric_limits<uint16_t>::max()); - auto buffer = common::NewSlabBuffer(sizeof(CommandHeader) + data.size()); + auto buffer = NewSlabBuffer(sizeof(CommandHeader) + data.size()); ZX_ASSERT(buffer); MutableSignalingPacket packet(buffer.get(), data.size()); @@ -117,14 +115,14 @@ common::ByteBufferPtr SignalingChannel::BuildPacket( bool SignalingChannel::SendCommandReject(uint8_t identifier, RejectReason reason, - const common::ByteBuffer& data) { + const ByteBuffer& data) { ZX_DEBUG_ASSERT(data.size() <= kCommandRejectMaxDataLength); constexpr size_t kMaxPayloadLength = sizeof(CommandRejectPayload) + kCommandRejectMaxDataLength; - common::StaticByteBuffer<kMaxPayloadLength> rej_buf; + StaticByteBuffer<kMaxPayloadLength> rej_buf; - common::MutablePacketView<CommandRejectPayload> reject(&rej_buf, data.size()); + MutablePacketView<CommandRejectPayload> reject(&rej_buf, data.size()); reject.mutable_header()->reason = htole16(reason); reject.mutable_payload_data().Write(data); @@ -149,7 +147,7 @@ void SignalingChannel::OnChannelClosed() { is_open_ = false; } -void SignalingChannel::OnRxBFrame(common::ByteBufferPtr sdu) { +void SignalingChannel::OnRxBFrame(ByteBufferPtr sdu) { ZX_DEBUG_ASSERT(IsCreationThreadCurrent()); if (!is_open()) @@ -164,7 +162,7 @@ void SignalingChannel::CheckAndDispatchPacket(const SignalingPacket& packet) { if (packet.size() > mtu()) { // Respond with our signaling MTU. uint16_t rsp_mtu = htole16(mtu()); - common::BufferView rej_data(&rsp_mtu, sizeof(rsp_mtu)); + BufferView rej_data(&rsp_mtu, sizeof(rsp_mtu)); SendCommandReject(packet.header().id, RejectReason::kSignalingMTUExceeded, rej_data); } else if (!packet.header().id) { @@ -172,10 +170,10 @@ void SignalingChannel::CheckAndDispatchPacket(const SignalingPacket& packet) { // used in any command" (v5.0, Vol 3, Part A, Section 4). bt_log(TRACE, "l2cap", "illegal signaling cmd ID: 0x00; reject"); SendCommandReject(packet.header().id, RejectReason::kNotUnderstood, - common::BufferView()); + BufferView()); } else if (!HandlePacket(packet)) { SendCommandReject(packet.header().id, RejectReason::kNotUnderstood, - common::BufferView()); + BufferView()); } } diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/signaling_channel.h b/src/connectivity/bluetooth/core/bt-host/l2cap/signaling_channel.h index ff587a77274b7bf06f9118cf9f367686cf6d94d1..724f20d0bcef9d84a15f81c0b54fb5a808d0245a 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/signaling_channel.h +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/signaling_channel.h @@ -23,10 +23,10 @@ class Channel; namespace internal { -using SignalingPacket = common::PacketView<CommandHeader>; -using MutableSignalingPacket = common::MutablePacketView<CommandHeader>; +using SignalingPacket = PacketView<CommandHeader>; +using MutableSignalingPacket = MutablePacketView<CommandHeader>; -using DataCallback = fit::function<void(const common::ByteBuffer& data)>; +using DataCallback = fit::function<void(const ByteBuffer& data)>; using SignalingPacketHandler = fit::function<void(const SignalingPacket& packet)>; @@ -45,22 +45,21 @@ class SignalingChannelInterface { // is kSuccess or kReject, then |rsp_payload| will contain any payload // received. Return true if an additional response is expected. using ResponseHandler = - fit::function<bool(Status status, const common::ByteBuffer& rsp_payload)>; + fit::function<bool(Status status, const ByteBuffer& rsp_payload)>; // Initiate an outbound transaction. The signaling channel will send a request // then expect reception of one or more responses with a code one greater than // the request. Each response or rejection received invokes |cb|. When |cb| // returns false, it will be removed. Returns false if the request failed to // send. - virtual bool SendRequest(CommandCode req_code, - const common::ByteBuffer& payload, + virtual bool SendRequest(CommandCode req_code, const ByteBuffer& payload, ResponseHandler cb) = 0; // Send a command packet in response to an incoming request. class Responder { public: // Send a response that corresponds to the request received - virtual void Send(const common::ByteBuffer& rsp_payload) = 0; + virtual void Send(const ByteBuffer& rsp_payload) = 0; // Reject invalid, malformed, or unhandled request virtual void RejectNotUnderstood() = 0; @@ -77,8 +76,8 @@ class SignalingChannelInterface { // |req_payload| contains any payload received, without the command header. // The callee can use |responder| to respond or reject. Parameters passed to // this handler are only guaranteed to be valid while the handler is running. - using RequestDelegate = fit::function<void( - const common::ByteBuffer& req_payload, Responder* responder)>; + using RequestDelegate = + fit::function<void(const ByteBuffer& req_payload, Responder* responder)>; // Register a handler for all inbound transactions matching |req_code|, which // should be the code of a request. |cb| will be called with request payloads @@ -113,7 +112,7 @@ class SignalingChannel : public SignalingChannelInterface { class ResponderImpl : public Responder { public: ResponderImpl(SignalingChannel* sig, CommandCode code, CommandId id); - void Send(const common::ByteBuffer& rsp_payload) override; + void Send(const ByteBuffer& rsp_payload) override; void RejectNotUnderstood() override; void RejectInvalidChannelId(ChannelId local_cid, ChannelId remote_cid) override; @@ -127,15 +126,14 @@ class SignalingChannel : public SignalingChannelInterface { }; // Sends out a single signaling packet using the given parameters. - bool SendPacket(CommandCode code, uint8_t identifier, - const common::ByteBuffer& data); + bool SendPacket(CommandCode code, uint8_t identifier, const ByteBuffer& data); // Called when a frame is received to decode into L2CAP signaling command // packets. The derived implementation should invoke |cb| for each packet with // a valid payload length, send a Command Reject packet for each packet with // an intact ID in its header but invalid payload length, and drop any other // incoming data. - virtual void DecodeRxUnit(common::ByteBufferPtr sdu, + virtual void DecodeRxUnit(ByteBufferPtr sdu, const SignalingPacketHandler& cb) = 0; // Called when a new signaling packet has been received. Returns false if @@ -147,7 +145,7 @@ class SignalingChannel : public SignalingChannelInterface { // Sends out a command reject packet with the given parameters. bool SendCommandReject(uint8_t identifier, RejectReason reason, - const common::ByteBuffer& data); + const ByteBuffer& data); // Returns true if called on this SignalingChannel's creation thread. Mainly // intended for debug assertions. @@ -172,16 +170,16 @@ class SignalingChannel : public SignalingChannelInterface { // // TODO(armansito): This should be generalized for ACL-U to allow multiple // signaling commands in a single C-frame. - bool Send(common::ByteBufferPtr packet); + bool Send(ByteBufferPtr packet); // Builds a signaling packet with the given parameters and payload. The // backing buffer is slab allocated. - common::ByteBufferPtr BuildPacket(CommandCode code, uint8_t identifier, - const common::ByteBuffer& data); + ByteBufferPtr BuildPacket(CommandCode code, uint8_t identifier, + const ByteBuffer& data); // Channel callbacks: void OnChannelClosed(); - void OnRxBFrame(common::ByteBufferPtr sdu); + void OnRxBFrame(ByteBufferPtr sdu); // Invoke the abstract packet handler |HandlePacket| for well-formed command // packets and send responses for command packets that exceed this host's MTU diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/signaling_channel_unittest.cc b/src/connectivity/bluetooth/core/bt-host/l2cap/signaling_channel_unittest.cc index 581fce0e506ba11c06842a7581bc3e46bd8744bc..9b73d7834ccf794ed97691bcd8affef5a67b96c0 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/signaling_channel_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/signaling_channel_unittest.cc @@ -12,9 +12,6 @@ namespace l2cap { namespace internal { namespace { -using common::LowerBits; -using common::UpperBits; - constexpr CommandCode kUnknownCommandCode = 0x00; constexpr CommandCode kCommandCode = 0xFF; constexpr hci::ConnectionHandle kTestHandle = 0x0001; @@ -40,14 +37,14 @@ class TestSignalingChannel : public SignalingChannel { private: // SignalingChannelInterface overrides - bool SendRequest(CommandCode req_code, const common::ByteBuffer& payload, + bool SendRequest(CommandCode req_code, const ByteBuffer& payload, ResponseHandler cb) override { return false; } void ServeRequest(CommandCode req_code, RequestDelegate cb) override {} // SignalingChannel overrides - void DecodeRxUnit(common::ByteBufferPtr sdu, + void DecodeRxUnit(ByteBufferPtr sdu, const SignalingPacketHandler& cb) override { ZX_DEBUG_ASSERT(sdu); if (sdu->size()) { @@ -109,7 +106,7 @@ TEST_F(L2CAP_SignalingChannelTest, IgnoreEmptyFrame) { auto send_cb = [&send_cb_called](auto) { send_cb_called = true; }; fake_chan()->SetSendCallback(std::move(send_cb), dispatcher()); - fake_chan()->Receive(common::BufferView()); + fake_chan()->Receive(BufferView()); RunLoopUntilIdle(); EXPECT_FALSE(send_cb_called); @@ -119,7 +116,7 @@ TEST_F(L2CAP_SignalingChannelTest, Reject) { constexpr uint8_t kTestId = 14; // Command Reject packet. - auto expected = common::CreateStaticByteBuffer( + auto expected = CreateStaticByteBuffer( // Command header 0x01, kTestId, 0x02, 0x00, @@ -127,7 +124,7 @@ TEST_F(L2CAP_SignalingChannelTest, Reject) { 0x00, 0x00); // A command that TestSignalingChannel does not support. - auto cmd = common::CreateStaticByteBuffer( + auto cmd = CreateStaticByteBuffer( // header kUnknownCommandCode, kTestId, 0x04, 0x00, @@ -141,7 +138,7 @@ TEST_F(L2CAP_SignalingChannelTest, RejectCommandCodeZero) { constexpr uint8_t kTestId = 14; // Command Reject packet. - auto expected = common::CreateStaticByteBuffer( + auto expected = CreateStaticByteBuffer( // Command header 0x01, kTestId, 0x02, 0x00, @@ -149,7 +146,7 @@ TEST_F(L2CAP_SignalingChannelTest, RejectCommandCodeZero) { 0x00, 0x00); // A command that TestSignalingChannel does not support. - auto cmd = common::CreateStaticByteBuffer( + auto cmd = CreateStaticByteBuffer( // header 0x00, kTestId, 0x04, 0x00, @@ -162,7 +159,7 @@ TEST_F(L2CAP_SignalingChannelTest, RejectCommandCodeZero) { TEST_F(L2CAP_SignalingChannelTest, RejectNotUnderstoodWithResponder) { constexpr uint8_t kTestId = 14; - auto expected = common::CreateStaticByteBuffer( + auto expected = CreateStaticByteBuffer( // Command header (Command Reject, ID, length) 0x01, kTestId, 0x02, 0x00, @@ -172,7 +169,7 @@ TEST_F(L2CAP_SignalingChannelTest, RejectNotUnderstoodWithResponder) { bool cb_called = false; auto send_cb = [&expected, &cb_called](auto packet) { cb_called = true; - EXPECT_TRUE(common::ContainersEqual(expected, *packet)); + EXPECT_TRUE(ContainersEqual(expected, *packet)); }; fake_chan()->SetSendCallback(std::move(send_cb), dispatcher()); @@ -188,7 +185,7 @@ TEST_F(L2CAP_SignalingChannelTest, RejectInvalidCIdWithResponder) { constexpr uint16_t kLocalCId = 0xf00d; constexpr uint16_t kRemoteCId = 0xcafe; - auto expected = common::CreateStaticByteBuffer( + auto expected = CreateStaticByteBuffer( // Command header (Command Reject, ID, length) 0x01, kTestId, 0x06, 0x00, @@ -202,7 +199,7 @@ TEST_F(L2CAP_SignalingChannelTest, RejectInvalidCIdWithResponder) { bool cb_called = false; auto send_cb = [&expected, &cb_called](auto packet) { cb_called = true; - EXPECT_TRUE(common::ContainersEqual(expected, *packet)); + EXPECT_TRUE(ContainersEqual(expected, *packet)); }; fake_chan()->SetSendCallback(std::move(send_cb), dispatcher()); @@ -218,7 +215,7 @@ TEST_F(L2CAP_SignalingChannelTest, InvalidMTU) { constexpr uint16_t kTooSmallMTU = 7; // Command Reject packet. - auto expected = common::CreateStaticByteBuffer( + auto expected = CreateStaticByteBuffer( // Command header 0x01, kTestId, 0x04, 0x00, @@ -229,7 +226,7 @@ TEST_F(L2CAP_SignalingChannelTest, InvalidMTU) { static_cast<uint8_t>(kTooSmallMTU), 0x00); // A command that is one octet larger than the MTU. - auto cmd = common::CreateStaticByteBuffer( + auto cmd = CreateStaticByteBuffer( // header kCommandCode, kTestId, 0x04, 0x00, @@ -244,7 +241,7 @@ TEST_F(L2CAP_SignalingChannelTest, HandlePacket) { constexpr uint8_t kTestId = 14; // A command that TestSignalingChannel supports. - auto cmd = common::CreateStaticByteBuffer( + auto cmd = CreateStaticByteBuffer( // header kCommandCode, kTestId, 0x04, 0x00, @@ -253,7 +250,7 @@ TEST_F(L2CAP_SignalingChannelTest, HandlePacket) { bool called = false; sig()->set_packet_callback([&cmd, &called, this](auto packet) { - EXPECT_TRUE(common::ContainersEqual(cmd, packet.data())); + EXPECT_TRUE(ContainersEqual(cmd, packet.data())); called = true; }); diff --git a/src/connectivity/bluetooth/core/bt-host/l2cap/tx_engine.h b/src/connectivity/bluetooth/core/bt-host/l2cap/tx_engine.h index afd7484bb1f64f34abbf5edc75c60f73741a60fc..df7bed83d1af6736406e291740fb3748e1b3afc1 100644 --- a/src/connectivity/bluetooth/core/bt-host/l2cap/tx_engine.h +++ b/src/connectivity/bluetooth/core/bt-host/l2cap/tx_engine.h @@ -25,7 +25,7 @@ class TxEngine { // Type defining the callback that a TxEngine uses to deliver a PDU to lower // layers. The callee may assume that the ByteBufferPtr owns an instance of a // DynamicByteBuffer or SlabBuffer. - using SendBasicFrameCallback = fit::function<void(common::ByteBufferPtr pdu)>; + using SendBasicFrameCallback = fit::function<void(ByteBufferPtr pdu)>; // Creates a transmit engine, which will invoke |send_basic_frame_callback| // when a PDU is ready for transmission. This callback may be invoked @@ -50,7 +50,7 @@ class TxEngine { // invocation of |send_basic_frame_callback_|. // * It is presumed that the ByteBufferPtr owns an instance of a // DynamicByteBuffer or SlabBuffer. - virtual bool QueueSdu(common::ByteBufferPtr) = 0; + virtual bool QueueSdu(ByteBufferPtr) = 0; protected: const ChannelId channel_id_; diff --git a/src/connectivity/bluetooth/core/bt-host/rfcomm/channel.cc b/src/connectivity/bluetooth/core/bt-host/rfcomm/channel.cc index f5f06ce719aa18543dac6553aef64e91e37f006a..ab65dcb88f814fe4e22cb086a371556091acb1c9 100644 --- a/src/connectivity/bluetooth/core/bt-host/rfcomm/channel.cc +++ b/src/connectivity/bluetooth/core/bt-host/rfcomm/channel.cc @@ -2,9 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "channel.h" + #include <lib/async/cpp/task.h> -#include "channel.h" #include "session.h" namespace bt { @@ -44,14 +45,14 @@ bool ChannelImpl::Activate(RxCallback rx_callback, return true; } -bool ChannelImpl::Send(common::ByteBufferPtr data) { +bool ChannelImpl::Send(ByteBufferPtr data) { ZX_DEBUG_ASSERT(session_); ZX_DEBUG_ASSERT_MSG(rx_callback_, "must call Activate() first"); session_->SendUserData(dlci_, std::move(data)); return true; } -void ChannelImpl::Receive(common::ByteBufferPtr data) { +void ChannelImpl::Receive(ByteBufferPtr data) { if (rx_callback_) { async::PostTask(dispatcher_, [this, data_ = std::move(data)]() mutable { rx_callback_(std::move(data_)); diff --git a/src/connectivity/bluetooth/core/bt-host/rfcomm/channel.h b/src/connectivity/bluetooth/core/bt-host/rfcomm/channel.h index fddade69c2ffa37aa14849befc92aae95b956085..36ab1768c09b60183dcbc31eb1bbfa6ecb48ad15 100644 --- a/src/connectivity/bluetooth/core/bt-host/rfcomm/channel.h +++ b/src/connectivity/bluetooth/core/bt-host/rfcomm/channel.h @@ -36,7 +36,7 @@ class Channel : public fbl::RefCounted<Channel> { // connections. UniqueId unique_id() const { return dlci_; } - using RxCallback = fit::function<void(common::ByteBufferPtr)>; + using RxCallback = fit::function<void(ByteBufferPtr)>; using ClosedCallback = fit::closure; // Activates this channel assigning |dispatcher| to execute |rx_callback| and // |closed_callback|. Returns true on success. @@ -51,7 +51,7 @@ class Channel : public fbl::RefCounted<Channel> { // the assumption that the underlying transport is reliable. The channel must // be activated prior to sending. Returns true if the data was successfully // queued. - virtual bool Send(common::ByteBufferPtr data) = 0; + virtual bool Send(ByteBufferPtr data) = 0; protected: friend class Session; @@ -84,7 +84,7 @@ class Channel : public fbl::RefCounted<Channel> { // |rx_callback_| is registered, the frame is forwarded to the callback; // otherwise, the frame is buffered and is forwarded once a callback gets // registered. - virtual void Receive(common::ByteBufferPtr data) = 0; + virtual void Receive(ByteBufferPtr data) = 0; DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(Channel); }; @@ -96,7 +96,7 @@ class ChannelImpl : public Channel { // Channel overrides bool Activate(RxCallback rx_callback, ClosedCallback closed_callback, async_dispatcher_t* dispatcher) override; - bool Send(common::ByteBufferPtr data) override; + bool Send(ByteBufferPtr data) override; private: friend class rfcomm::Session; @@ -105,9 +105,9 @@ class ChannelImpl : public Channel { ChannelImpl(DLCI dlci, Session* session); // This should only be called from Session. - void Receive(common::ByteBufferPtr data) override; + void Receive(ByteBufferPtr data) override; - std::queue<common::ByteBufferPtr> pending_rxed_frames_; + std::queue<ByteBufferPtr> pending_rxed_frames_; }; } // namespace internal diff --git a/src/connectivity/bluetooth/core/bt-host/rfcomm/frames.cc b/src/connectivity/bluetooth/core/bt-host/rfcomm/frames.cc index 2d9a73bcc21a44cce2780c4e50205aa6ddcf9d06..4f532b5439ede2ad45f172a709fe104f88c32f80 100644 --- a/src/connectivity/bluetooth/core/bt-host/rfcomm/frames.cc +++ b/src/connectivity/bluetooth/core/bt-host/rfcomm/frames.cc @@ -4,11 +4,10 @@ #include "frames.h" +#include "rfcomm.h" #include "src/connectivity/bluetooth/core/bt-host/common/log.h" #include "src/connectivity/bluetooth/core/bt-host/common/slab_allocator.h" -#include "rfcomm.h" - namespace bt { namespace rfcomm { @@ -41,7 +40,7 @@ const uint8_t crctable[] = { 0xBD, 0x2C, 0x5E, 0xCF}; // FCS calculation function from GSM B.3.3. -uint8_t CalculateFCS(const common::ByteBuffer& p) { +uint8_t CalculateFCS(const ByteBuffer& p) { uint8_t fcs = 0xFF; size_t offset = 0; size_t len = p.size(); @@ -53,7 +52,7 @@ uint8_t CalculateFCS(const common::ByteBuffer& p) { } // FCS checking function from GSM B.3.4. -bool CheckFCS(uint8_t received_fcs, const common::ByteBuffer& p) { +bool CheckFCS(uint8_t received_fcs, const ByteBuffer& p) { uint8_t fcs = 0xFF; size_t offset = 0; size_t len = p.size(); @@ -112,7 +111,7 @@ Frame::Frame(Role role, CommandResponse command_response, DLCI dlci, // functions for each Frame subclass, as Frame::Parse will already parse all of // the needed information. std::unique_ptr<Frame> Frame::Parse(bool credit_based_flow, Role role, - const common::ByteBuffer& buffer) { + const ByteBuffer& buffer) { if (buffer.size() < kMinimumFrameSize) { bt_log(TRACE, "rfcomm", "buffer size of %zu is less than minimum frame size (%zu)", @@ -222,9 +221,9 @@ std::unique_ptr<Frame> Frame::Parse(bool credit_based_flow, Role role, mux_command_frame->set_credits(credits); return mux_command_frame; } else if (IsUserDLCI(dlci)) { - common::MutableByteBufferPtr information; + MutableByteBufferPtr information; if (length > 0) { - information = common::NewSlabBuffer(length); + information = NewSlabBuffer(length); buffer.Copy(information.get(), header_size, length); } auto user_data_frame = std::make_unique<UserDataFrame>( @@ -244,7 +243,7 @@ std::unique_ptr<Frame> Frame::Parse(bool credit_based_flow, Role role, } // Write this RFCOMM frame into a buffer. -void Frame::Write(common::MutableBufferView buffer) const { +void Frame::Write(MutableBufferView buffer) const { ZX_DEBUG_ASSERT(buffer.size() >= header_size()); // Writes address, control, and length octets. @@ -262,7 +261,7 @@ void Frame::Write(common::MutableBufferView buffer) const { buffer[offset] = fcs; } -void Frame::WriteHeader(common::MutableBufferView buffer) const { +void Frame::WriteHeader(MutableBufferView buffer) const { ZX_DEBUG_ASSERT(buffer.size() >= header_size()); size_t offset = 0; @@ -413,7 +412,7 @@ size_t UnnumberedInfoHeaderCheckFrame::header_size() const { } void UnnumberedInfoHeaderCheckFrame::WriteHeader( - common::MutableBufferView buffer) const { + MutableBufferView buffer) const { ZX_DEBUG_ASSERT(buffer.size() >= header_size()); // Write address, control, length @@ -427,11 +426,11 @@ void UnnumberedInfoHeaderCheckFrame::WriteHeader( } UserDataFrame::UserDataFrame(Role role, bool credit_based_flow, DLCI dlci, - common::ByteBufferPtr information) + ByteBufferPtr information) : UnnumberedInfoHeaderCheckFrame(role, credit_based_flow, dlci), information_(std::move(information)) {} -void UserDataFrame::Write(common::MutableBufferView buffer) const { +void UserDataFrame::Write(MutableBufferView buffer) const { ZX_DEBUG_ASSERT(buffer.size() >= written_size()); WriteHeader(buffer); @@ -452,7 +451,7 @@ size_t UserDataFrame::written_size() const { + sizeof(uint8_t); // FCS } -common::ByteBufferPtr UserDataFrame::TakeInformation() { +ByteBufferPtr UserDataFrame::TakeInformation() { return std::move(information_); } @@ -461,7 +460,7 @@ MuxCommandFrame::MuxCommandFrame(Role role, bool credit_based_flow, : UnnumberedInfoHeaderCheckFrame(role, credit_based_flow, kMuxControlDLCI), mux_command_(std::move(mux_command)) {} -void MuxCommandFrame::Write(common::MutableBufferView buffer) const { +void MuxCommandFrame::Write(MutableBufferView buffer) const { ZX_DEBUG_ASSERT(buffer.size() >= written_size()); WriteHeader(buffer); diff --git a/src/connectivity/bluetooth/core/bt-host/rfcomm/frames.h b/src/connectivity/bluetooth/core/bt-host/rfcomm/frames.h index 73484cf99274b9c0666898da65c71569a17500ed..63380b1c4f02866f402cb5e3363a5989a3c008f3 100644 --- a/src/connectivity/bluetooth/core/bt-host/rfcomm/frames.h +++ b/src/connectivity/bluetooth/core/bt-host/rfcomm/frames.h @@ -80,12 +80,12 @@ class Frame { // // For UIH frames, this function will copy from |buffer|. static std::unique_ptr<Frame> Parse(bool credit_based_flow, Role role, - const common::ByteBuffer& buffer); + const ByteBuffer& buffer); // Write this into a buffer. The base implementation of Write() will simply // write the address, control, length(=0), and FCS octets into a buffer. This // is adequate for non-UIH frames. - virtual void Write(common::MutableBufferView buffer) const; + virtual void Write(MutableBufferView buffer) const; // The amount of space this frame takes up when written. Used to allocate the // correct size for Write(). @@ -151,7 +151,7 @@ class Frame { virtual size_t header_size() const; // Write the header of this frame into a buffer. - virtual void WriteHeader(common::MutableBufferView buffer) const; + virtual void WriteHeader(MutableBufferView buffer) const; // RFCOMM session parameters. Role role_; @@ -209,7 +209,7 @@ class UnnumberedInfoHeaderCheckFrame : public Frame { virtual ~UnnumberedInfoHeaderCheckFrame() = default; // Frame overrides - virtual void Write(common::MutableBufferView buffer) const override = 0; + virtual void Write(MutableBufferView buffer) const override = 0; virtual size_t written_size() const override = 0; virtual InformationLength length() const override = 0; @@ -236,7 +236,7 @@ class UnnumberedInfoHeaderCheckFrame : public Frame { virtual size_t header_size() const override; // Write the header of this frame, including the optional credits octet. - virtual void WriteHeader(common::MutableBufferView buffer) const override; + virtual void WriteHeader(MutableBufferView buffer) const override; bool credit_based_flow_; uint8_t credits_; @@ -247,10 +247,10 @@ class UserDataFrame : public UnnumberedInfoHeaderCheckFrame { // |information| is the payload; "information" is RFCOMM/GSM's term for the // payload of a frame. Frame takes ownership of |information|. UserDataFrame(Role role, bool credit_based_flow, DLCI dlci, - common::ByteBufferPtr information); + ByteBufferPtr information); // UnnumberedInfoHeaderCheckFrame overrides - void Write(common::MutableBufferView buffer) const override; + void Write(MutableBufferView buffer) const override; size_t written_size() const override; inline InformationLength length() const override { return information_ ? information_->size() : 0; @@ -259,10 +259,10 @@ class UserDataFrame : public UnnumberedInfoHeaderCheckFrame { // Transfers ownership of the information field (aka the payload) from this // Frame to the caller. Future calls to TakeInformation() will return nullptr. // It is expected that the Frame will be destructed soon after this call. - common::ByteBufferPtr TakeInformation(); + ByteBufferPtr TakeInformation(); private: - common::ByteBufferPtr information_; + ByteBufferPtr information_; }; // Represents a UIH frame encapsulating a multiplexer control channel command. @@ -273,7 +273,7 @@ class MuxCommandFrame : public UnnumberedInfoHeaderCheckFrame { std::unique_ptr<MuxCommand> mux_command); // UnnumberedInfoHeaderCheckFrame overrides - void Write(common::MutableBufferView buffer) const override; + void Write(MutableBufferView buffer) const override; size_t written_size() const override; inline InformationLength length() const override { return mux_command_->written_size(); diff --git a/src/connectivity/bluetooth/core/bt-host/rfcomm/frames_unittest.cc b/src/connectivity/bluetooth/core/bt-host/rfcomm/frames_unittest.cc index abedbaaeacb0d894f2feab3771ad6b60f9ead0b9..e2ef0d46ad443e968b8abe29888fd57f83ec3dc6 100644 --- a/src/connectivity/bluetooth/core/bt-host/rfcomm/frames_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/rfcomm/frames_unittest.cc @@ -4,12 +4,11 @@ #include "frames.h" -#include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" -#include "src/connectivity/bluetooth/core/bt-host/common/slab_allocator.h" #include "gtest/gtest.h" - #include "mux_commands.h" #include "rfcomm.h" +#include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" +#include "src/connectivity/bluetooth/core/bt-host/common/slab_allocator.h" namespace bt { namespace rfcomm { @@ -29,7 +28,7 @@ constexpr FrameType kEmptyFrameType = FrameType::kSetAsynchronousBalancedMode; constexpr DLCI kEmptyFrameDLCI = 0x02; constexpr bool kEmptyFramePF = true; constexpr bool kEmptyFrameCreditBasedFlow = false; -const auto kEmptyFrame = common::CreateStaticByteBuffer( +const auto kEmptyFrame = CreateStaticByteBuffer( // Address octet: // E/A bit is always 1. C/R bit is 1 in the case of a command being sent // from the initiator role. DLCI is 0x02. Thus: 1 (E/A) ++ 1 (C/R) ++ 010000 @@ -57,9 +56,9 @@ constexpr FrameType kHelloFrameType = FrameType::kUnnumberedInfoHeaderCheck; constexpr DLCI kHelloFrameDLCI = 0x23; constexpr bool kHelloFramePF = false; constexpr bool kHelloFrameCreditBasedFlow = false; -const auto kHelloFrameInformation = common::CreateStaticByteBuffer( - 'h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'); -const auto kHelloFrame = common::CreateStaticByteBuffer( +const auto kHelloFrameInformation = + CreateStaticByteBuffer('h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'); +const auto kHelloFrame = CreateStaticByteBuffer( // Address octet: // E/A bit is always 1. C/R bit is 0 in the case of a command being sent // from the responder role. DLCI is 0x23. Thus: 1 (E/A) ++ 0 (C/R) ++ 110001 @@ -90,9 +89,9 @@ constexpr DLCI kFuchsiaFrameDLCI = 0x23; constexpr bool kFuchsiaFramePF = true; constexpr bool kFuchsiaFrameCreditBasedFlow = true; constexpr uint8_t kFuchsiaFrameCredits = 5; -const auto kFuchsiaFrameInformation = common::CreateStaticByteBuffer( +const auto kFuchsiaFrameInformation = CreateStaticByteBuffer( 'h', 'e', 'l', 'l', 'o', 'f', 'u', 'c', 'h', 's', 'i', 'a'); -const auto kFuchsiaFrame = common::CreateStaticByteBuffer( +const auto kFuchsiaFrame = CreateStaticByteBuffer( // Address octet: // E/A bit is always 1. C/R bit is 0 in the case of a command being sent // from the responder role. DLCI is 0x23. Thus: 1 (E/A) ++ 0 (C/R) ++ 110001 @@ -122,10 +121,10 @@ constexpr uint8_t kTestCommandFrameCredits = 63; constexpr MuxCommandType kTestCommandFrameMuxCommandType = MuxCommandType::kTestCommand; const auto kTestCommandFrameMuxCommandPattern = - common::CreateStaticByteBuffer(0, 1, 2, 3); + CreateStaticByteBuffer(0, 1, 2, 3); constexpr CommandResponse kTestCommandFrameMuxCommandCR = CommandResponse::kCommand; -const auto kTestCommandFrame = common::CreateStaticByteBuffer( +const auto kTestCommandFrame = CreateStaticByteBuffer( // Address: E/A = 1, C/R is 1 for a command from the initiator, DLCI = 0. 0b00000011, // Control: UIH is 1111p11, P/F is 1 due to presence of a credits field. @@ -146,7 +145,7 @@ const auto kTestCommandFrame = common::CreateStaticByteBuffer( // Contruction of pre-multiplexer-startup SABM frame: // - Role is unset // - Sent to DLCI 0 -const auto kPreMuxSABMFrame = common::CreateStaticByteBuffer( +const auto kPreMuxSABMFrame = CreateStaticByteBuffer( // Address octet: // E/A bit is always 1. Our implementation sets C/R bit to 1 for // pre-mux-startup SABM frames. DLCI is 0. @@ -164,7 +163,7 @@ const auto kPreMuxSABMFrame = common::CreateStaticByteBuffer( // Contruction of pre-multiplexer-startup SABM frame: // - Role is unset // - Sent to DLCI 0 -const auto kPreMuxUAFrame = common::CreateStaticByteBuffer( +const auto kPreMuxUAFrame = CreateStaticByteBuffer( // Address octet: // E/A bit is always 1. Our implementation sets C/R bit to 1 for // pre-mux-startup UA frames. DLCI is 0. @@ -182,7 +181,7 @@ const auto kPreMuxUAFrame = common::CreateStaticByteBuffer( // Contruction of pre-multiplexer-startup DM frame: // - Role is unset // - Sent to DLCI 0 -const auto kPreMuxDMFrame = common::CreateStaticByteBuffer( +const auto kPreMuxDMFrame = CreateStaticByteBuffer( // Address octet: // E/A bit is always 1. Our implementation sets C/R bit to 1 for // pre-mux-startup frames. DLCI is 0. @@ -207,7 +206,7 @@ constexpr Role kEmptyUserDataFrameRole = Role::kResponder; constexpr DLCI kEmptyUserDataFrameDLCI = 0x23; constexpr bool kEmptyUserDataFrameCreditBasedFlow = true; constexpr FrameCredits kEmptyUserDataFrameCredits = 11; -const auto kEmptyUserDataFrame = common::CreateStaticByteBuffer( +const auto kEmptyUserDataFrame = CreateStaticByteBuffer( // Address octet: // E/A bit is always 1. C/R bit is 0 in the case of a command being sent // from the responder role. DLCI is 0x23. Thus: 1 (E/A) ++ 0 (C/R) ++ 110001 @@ -224,24 +223,24 @@ const auto kEmptyUserDataFrame = common::CreateStaticByteBuffer( // Please see GSM 5.2.1.6, GSM Annex B, and RFCOMM 5.1.1. 0b10000001); -const auto kInvalidLengthFrame = common::CreateStaticByteBuffer(0, 1, 2); +const auto kInvalidLengthFrame = CreateStaticByteBuffer(0, 1, 2); // Same as the hellofuchsia frame, but information field is too short. -const auto kInvalidLengthFrame2 = common::CreateStaticByteBuffer( +const auto kInvalidLengthFrame2 = CreateStaticByteBuffer( 0b10001101, 0b11111111, 0b00011001, 0b00000101, 'h', 'e', 'l', 'l', 'o'); // Same as the hellofuchsia frame, but with an invalid FCS. -const auto kInvalidFCSFrame = common::CreateStaticByteBuffer( +const auto kInvalidFCSFrame = CreateStaticByteBuffer( 0b10001101, 0b11111111, 0b00011001, 0b00000101, 'h', 'e', 'l', 'l', 'o', 'f', 'u', 'c', 'h', 's', 'i', 'a', 0b10000001 + 1); // Same as the hellofuchsia frame, but with an invalid DLCI (1) -const auto kInvalidDLCIFrame = common::CreateStaticByteBuffer( +const auto kInvalidDLCIFrame = CreateStaticByteBuffer( 0b00000101, 0b11111111, 0b00011001, 0b00000101, 'h', 'e', 'l', 'l', 'o', 'f', 'u', 'c', 'h', 's', 'i', 'a', 0b11000011); // Same as the hellofuchsia frame, but with an invalid DLCI (62) -const auto kInvalidDLCIFrame2 = common::CreateStaticByteBuffer( +const auto kInvalidDLCIFrame2 = CreateStaticByteBuffer( 0b11111001, 0b11111111, 0b00011001, 0b00000101, 'h', 'e', 'l', 'l', 'o', 'f', 'u', 'c', 'h', 's', 'i', 'a', 0b10011111); @@ -249,30 +248,30 @@ using RFCOMM_FrameTest = ::testing::Test; TEST_F(RFCOMM_FrameTest, WriteFrame) { SetAsynchronousBalancedModeCommand frame(kEmptyFrameRole, kEmptyFrameDLCI); - common::DynamicByteBuffer buffer(frame.written_size()); + DynamicByteBuffer buffer(frame.written_size()); frame.Write(buffer.mutable_view()); EXPECT_EQ(4ul, frame.written_size()); EXPECT_EQ(kEmptyFrame, buffer); } TEST_F(RFCOMM_FrameTest, WriteFrameWithData) { - auto information = common::NewSlabBuffer(kHelloFrameInformation.size()); + auto information = NewSlabBuffer(kHelloFrameInformation.size()); kHelloFrameInformation.Copy(information.get()); UserDataFrame frame(kHelloFrameRole, kHelloFrameCreditBasedFlow, kHelloFrameDLCI, std::move(information)); - common::DynamicByteBuffer buffer(frame.written_size()); + DynamicByteBuffer buffer(frame.written_size()); frame.Write(buffer.mutable_view()); EXPECT_EQ(14ul, frame.written_size()); EXPECT_EQ(kHelloFrame, buffer); } TEST_F(RFCOMM_FrameTest, WriteFrameWithDataAndCredits) { - auto information = common::NewSlabBuffer(kFuchsiaFrameInformation.size()); + auto information = NewSlabBuffer(kFuchsiaFrameInformation.size()); kFuchsiaFrameInformation.Copy(information.get()); UserDataFrame frame(kFuchsiaFrameRole, kFuchsiaFrameCreditBasedFlow, kFuchsiaFrameDLCI, std::move(information)); frame.set_credits(kFuchsiaFrameCredits); - common::DynamicByteBuffer buffer(frame.written_size()); + DynamicByteBuffer buffer(frame.written_size()); frame.Write(buffer.mutable_view()); EXPECT_EQ(17ul, frame.written_size()); EXPECT_EQ(kFuchsiaFrame, buffer); @@ -285,27 +284,27 @@ TEST_F(RFCOMM_FrameTest, WriteFrameWithMuxCommandAndCredits) { std::move(mux_command)); frame.set_credits(kTestCommandFrameCredits); EXPECT_EQ(kTestCommandFrame.size(), frame.written_size()); - common::DynamicByteBuffer buffer(frame.written_size()); + DynamicByteBuffer buffer(frame.written_size()); frame.Write(buffer.mutable_view()); EXPECT_EQ(kTestCommandFrame, buffer); } TEST_F(RFCOMM_FrameTest, WritePreMuxStartupSABM) { SetAsynchronousBalancedModeCommand frame(Role::kUnassigned, kMuxControlDLCI); - common::DynamicByteBuffer buffer(frame.written_size()); + DynamicByteBuffer buffer(frame.written_size()); frame.Write(buffer.mutable_view()); EXPECT_EQ(kPreMuxSABMFrame, buffer); } TEST_F(RFCOMM_FrameTest, WritePreMuxStartupUA) { UnnumberedAcknowledgementResponse frame(Role::kUnassigned, kMuxControlDLCI); - common::DynamicByteBuffer buffer(frame.written_size()); + DynamicByteBuffer buffer(frame.written_size()); frame.Write(buffer.mutable_view()); EXPECT_EQ(kPreMuxUAFrame, buffer); } TEST_F(RFCOMM_FrameTest, WritePreMuxStartupDM) { DisconnectedModeResponse frame(Role::kUnassigned, kMuxControlDLCI); - common::DynamicByteBuffer buffer(frame.written_size()); + DynamicByteBuffer buffer(frame.written_size()); frame.Write(buffer.mutable_view()); EXPECT_EQ(kPreMuxDMFrame, buffer); } @@ -316,7 +315,7 @@ TEST_F(RFCOMM_FrameTest, WriteEmptyUserDataFrameWithCredits) { kEmptyUserDataFrameDLCI, nullptr); frame.set_credits(kEmptyUserDataFrameCredits); EXPECT_EQ(kEmptyUserDataFrame.size(), frame.written_size()); - common::DynamicByteBuffer buffer(frame.written_size()); + DynamicByteBuffer buffer(frame.written_size()); frame.Write(buffer.mutable_view()); EXPECT_EQ(kEmptyUserDataFrame, buffer); } diff --git a/src/connectivity/bluetooth/core/bt-host/rfcomm/mux_commands.cc b/src/connectivity/bluetooth/core/bt-host/rfcomm/mux_commands.cc index a28caa01b7759e9db5b628e1a693c7a6e20c15b7..17f9f6513a2ebd4c058134fe929ff3f6c6fae59d 100644 --- a/src/connectivity/bluetooth/core/bt-host/rfcomm/mux_commands.cc +++ b/src/connectivity/bluetooth/core/bt-host/rfcomm/mux_commands.cc @@ -118,8 +118,8 @@ size_t NumLengthOctetsNeeded(size_t length) { // most of the time), so this isn't a problem. However, the Test command takes a // user-supplied pattern of octets. There is no restriction in the spec on how // long this pattern can be. -common::DynamicByteBuffer CreateLengthFieldOctets(size_t length) { - common::DynamicByteBuffer octets(NumLengthOctetsNeeded(length)); +DynamicByteBuffer CreateLengthFieldOctets(size_t length) { + DynamicByteBuffer octets(NumLengthOctetsNeeded(length)); for (size_t i = 0; i < octets.size(); i++) { // There should still be meaningful data left in length. @@ -169,8 +169,7 @@ MuxCommand::MuxCommand(MuxCommandType command_type, CommandResponse command_response) : command_type_(command_type), command_response_(command_response) {} -std::unique_ptr<MuxCommand> MuxCommand::Parse( - const common::ByteBuffer& buffer) { +std::unique_ptr<MuxCommand> MuxCommand::Parse(const ByteBuffer& buffer) { ZX_DEBUG_ASSERT_MSG(buffer.size() >= kMinHeaderSize, "buffer must contain at least a type and length octet"); @@ -244,20 +243,19 @@ std::unique_ptr<MuxCommand> MuxCommand::Parse( } TestCommand::TestCommand(CommandResponse command_response, - const common::ByteBuffer& test_pattern) + const ByteBuffer& test_pattern) : MuxCommand(MuxCommandType::kTestCommand, command_response) { - test_pattern_ = common::DynamicByteBuffer(test_pattern.size()); + test_pattern_ = DynamicByteBuffer(test_pattern.size()); test_pattern.Copy(&test_pattern_, 0, test_pattern.size()); } std::unique_ptr<TestCommand> TestCommand::Parse( - CommandResponse command_response, size_t length, - const common::ByteBuffer& buffer) { + CommandResponse command_response, size_t length, const ByteBuffer& buffer) { return std::make_unique<TestCommand>(command_response, buffer.view(2, length)); } -void TestCommand::Write(common::MutableBufferView buffer) const { +void TestCommand::Write(MutableBufferView buffer) const { ZX_ASSERT(buffer.size() >= written_size()); size_t idx = 0; @@ -293,7 +291,7 @@ std::unique_ptr<FlowControlOnCommand> FlowControlOnCommand::Parse( return std::make_unique<FlowControlOnCommand>(command_response); } -void FlowControlOnCommand::Write(common::MutableBufferView buffer) const { +void FlowControlOnCommand::Write(MutableBufferView buffer) const { ZX_ASSERT(buffer.size() >= written_size()); buffer[kTypeIndex] = type_field_octet(); // Length = 0, EA bit = 1. @@ -307,7 +305,7 @@ std::unique_ptr<FlowControlOffCommand> FlowControlOffCommand::Parse( return std::make_unique<FlowControlOffCommand>(command_response); } -void FlowControlOffCommand::Write(common::MutableBufferView buffer) const { +void FlowControlOffCommand::Write(MutableBufferView buffer) const { ZX_ASSERT(buffer.size() >= written_size()); buffer[kTypeIndex] = type_field_octet(); // Length = 0, EA bit = 1. @@ -329,8 +327,7 @@ ModemStatusCommand::ModemStatusCommand(CommandResponse command_response, break_value_(break_value) {} std::unique_ptr<ModemStatusCommand> ModemStatusCommand::Parse( - CommandResponse command_response, size_t length, - const common::ByteBuffer& buffer) { + CommandResponse command_response, size_t length, const ByteBuffer& buffer) { DLCI dlci = buffer[2] >> kMSCDLCIShift; ModemStatusCommandSignals signals; BreakValue break_value = kDefaultInvalidBreakValue; @@ -354,7 +351,7 @@ std::unique_ptr<ModemStatusCommand> ModemStatusCommand::Parse( break_value); } -void ModemStatusCommand::Write(common::MutableBufferView buffer) const { +void ModemStatusCommand::Write(MutableBufferView buffer) const { ZX_ASSERT(buffer.size() >= written_size()); buffer[kTypeIndex] = type_field_octet(); // EA bit = 1. @@ -405,8 +402,7 @@ RemotePortNegotiationCommand::RemotePortNegotiationCommand( std::unique_ptr<RemotePortNegotiationCommand> RemotePortNegotiationCommand::Parse(CommandResponse command_response, - size_t length, - const common::ByteBuffer& buffer) { + size_t length, const ByteBuffer& buffer) { DLCI dlci = buffer[2] >> kRPNDLCIShift; if (length == kRPNShortLength) { @@ -434,8 +430,7 @@ RemotePortNegotiationCommand::Parse(CommandResponse command_response, command_response, dlci, std::move(params), std::move(mask)); } -void RemotePortNegotiationCommand::Write( - common::MutableBufferView buffer) const { +void RemotePortNegotiationCommand::Write(MutableBufferView buffer) const { ZX_ASSERT(buffer.size() >= written_size()); buffer[kTypeIndex] = type_field_octet(); // EA bit = 1. @@ -476,7 +471,7 @@ RemoteLineStatusCommand::RemoteLineStatusCommand( error_(error) {} std::unique_ptr<RemoteLineStatusCommand> RemoteLineStatusCommand::Parse( - CommandResponse command_response, const common::ByteBuffer& buffer) { + CommandResponse command_response, const ByteBuffer& buffer) { DLCI dlci = buffer[2] >> kRLSDLCIShift; bool error_occurred = buffer[3] & kRLSErrorOccurredMask; // TODO(gusss) @@ -487,7 +482,7 @@ std::unique_ptr<RemoteLineStatusCommand> RemoteLineStatusCommand::Parse( error_occurred, error); } -void RemoteLineStatusCommand::Write(common::MutableBufferView buffer) const { +void RemoteLineStatusCommand::Write(MutableBufferView buffer) const { ZX_ASSERT(buffer.size() >= written_size()); buffer[kTypeIndex] = type_field_octet(); // EA bit = 1. @@ -511,7 +506,7 @@ NonSupportedCommandResponse::NonSupportedCommandResponse( incoming_non_supported_command_(incoming_non_supported_command) {} std::unique_ptr<NonSupportedCommandResponse> NonSupportedCommandResponse::Parse( - CommandResponse command_response, const common::ByteBuffer& buffer) { + CommandResponse command_response, const ByteBuffer& buffer) { CommandResponse incoming_command_response = buffer[2] & kCRMask ? CommandResponse::kCommand : CommandResponse::kResponse; @@ -522,8 +517,7 @@ std::unique_ptr<NonSupportedCommandResponse> NonSupportedCommandResponse::Parse( incoming_command_response, incoming_non_supported_command); } -void NonSupportedCommandResponse::Write( - common::MutableBufferView buffer) const { +void NonSupportedCommandResponse::Write(MutableBufferView buffer) const { ZX_ASSERT(buffer.size() >= written_size()); buffer[kTypeIndex] = type_field_octet(); // EA bit = 1. @@ -545,7 +539,7 @@ DLCParameterNegotiationCommand::DLCParameterNegotiationCommand( std::unique_ptr<DLCParameterNegotiationCommand> DLCParameterNegotiationCommand::Parse(CommandResponse command_response, - const common::ByteBuffer& buffer) { + const ByteBuffer& buffer) { ParameterNegotiationParams params; params.dlci = buffer[2]; @@ -559,8 +553,7 @@ DLCParameterNegotiationCommand::Parse(CommandResponse command_response, params); } -void DLCParameterNegotiationCommand::Write( - common::MutableBufferView buffer) const { +void DLCParameterNegotiationCommand::Write(MutableBufferView buffer) const { ZX_ASSERT(buffer.size() >= written_size()); buffer[kTypeIndex] = type_field_octet(); // EA bit = 1. diff --git a/src/connectivity/bluetooth/core/bt-host/rfcomm/mux_commands.h b/src/connectivity/bluetooth/core/bt-host/rfcomm/mux_commands.h index 0959e5a8d1dc892bd2d7edcb2c82cd55df97e58a..c98d4fee29909256178ab3096f145f15769724cb 100644 --- a/src/connectivity/bluetooth/core/bt-host/rfcomm/mux_commands.h +++ b/src/connectivity/bluetooth/core/bt-host/rfcomm/mux_commands.h @@ -7,8 +7,8 @@ #include <cstddef> -#include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" #include "rfcomm.h" +#include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" namespace bt { namespace rfcomm { @@ -55,13 +55,13 @@ class MuxCommand { // Parses a buffer and constructs the appropriate subclass of MuxCommand. // Users of Parse should read the resulting command type and cast the pointer // to the appropriate MuxCommand subclass. - static std::unique_ptr<MuxCommand> Parse(const common::ByteBuffer& buffer); + static std::unique_ptr<MuxCommand> Parse(const ByteBuffer& buffer); virtual ~MuxCommand() = default; // Writes this MuxCommand into |buffer|. |buffer| must be at least the size // indicated by written_size(). - virtual void Write(common::MutableBufferView buffer) const = 0; + virtual void Write(MutableBufferView buffer) const = 0; // The amount of space this command takes up when written. This is used when // allocating space for an RFCOMM frame which will hold a multiplexer command. @@ -98,25 +98,22 @@ class MuxCommand { // is limited by the system's max value of size_t. class TestCommand : public MuxCommand { public: - TestCommand(CommandResponse command_response, - const common::ByteBuffer& test_pattern); + TestCommand(CommandResponse command_response, const ByteBuffer& test_pattern); // Returns nullptr if parse fails. |command_response| and |length| are // parameters which have already been parsed from |buffer|. static std::unique_ptr<TestCommand> Parse(CommandResponse command_response, size_t length, - const common::ByteBuffer& buffer); + const ByteBuffer& buffer); - inline common::BufferView test_pattern() const { - return test_pattern_.view(); - } + inline BufferView test_pattern() const { return test_pattern_.view(); } // MuxCommand overrides - void Write(common::MutableBufferView buffer) const override; + void Write(MutableBufferView buffer) const override; size_t written_size() const override; private: - common::DynamicByteBuffer test_pattern_; + DynamicByteBuffer test_pattern_; }; // This command is sent when our device is able to begin receiving messages. See @@ -131,7 +128,7 @@ class FlowControlOnCommand : public MuxCommand { CommandResponse command_response); // MuxCommand overrides - void Write(common::MutableBufferView buffer) const override; + void Write(MutableBufferView buffer) const override; size_t written_size() const override; }; @@ -147,7 +144,7 @@ class FlowControlOffCommand : public MuxCommand { CommandResponse command_response); // MuxCommand overrides - void Write(common::MutableBufferView buffer) const override; + void Write(MutableBufferView buffer) const override; size_t written_size() const override; }; @@ -178,10 +175,10 @@ class ModemStatusCommand : public MuxCommand { // parameters which have already been parsed from |buffer|. static std::unique_ptr<ModemStatusCommand> Parse( CommandResponse command_response, size_t length, - const common::ByteBuffer& buffer); + const ByteBuffer& buffer); // MuxCommand overrides - void Write(common::MutableBufferView buffer) const override; + void Write(MutableBufferView buffer) const override; size_t written_size() const override; @@ -324,10 +321,10 @@ class RemotePortNegotiationCommand : public MuxCommand { // parameters which have already been parsed from |buffer|. static std::unique_ptr<RemotePortNegotiationCommand> Parse( CommandResponse command_response, size_t length, - const common::ByteBuffer& buffer); + const ByteBuffer& buffer); // MuxCommand overrides - void Write(common::MutableBufferView buffer) const override; + void Write(MutableBufferView buffer) const override; size_t written_size() const override; // The DLCI which this RPN command is negotiating over. @@ -370,10 +367,10 @@ class RemoteLineStatusCommand : public MuxCommand { // Returns nullptr if parse fails. |command_response| is a parameter which has // already been parsed from |buffer|. static std::unique_ptr<RemoteLineStatusCommand> Parse( - CommandResponse command_response, const common::ByteBuffer& buffer); + CommandResponse command_response, const ByteBuffer& buffer); // MuxCommand overrides - void Write(common::MutableBufferView buffer) const override; + void Write(MutableBufferView buffer) const override; size_t written_size() const override; // The DLCI which this command pertains to. @@ -424,10 +421,10 @@ class DLCParameterNegotiationCommand : public MuxCommand { // Returns nullptr if parse fails. |command_response| is a parameter which has // already been parsed from |buffer|. static std::unique_ptr<DLCParameterNegotiationCommand> Parse( - CommandResponse command_response, const common::ByteBuffer& buffer); + CommandResponse command_response, const ByteBuffer& buffer); // MuxCommand overrides - void Write(common::MutableBufferView buffer) const override; + void Write(MutableBufferView buffer) const override; size_t written_size() const override; inline ParameterNegotiationParams params() const { return params_; } @@ -448,10 +445,10 @@ class NonSupportedCommandResponse : public MuxCommand { // Returns nullptr if parse fails. |command_response| is a parameter which has // already been parsed from |buffer|. static std::unique_ptr<NonSupportedCommandResponse> Parse( - CommandResponse command_response, const common::ByteBuffer& buffer); + CommandResponse command_response, const ByteBuffer& buffer); // MuxCommand overrides - void Write(common::MutableBufferView buffer) const override; + void Write(MutableBufferView buffer) const override; size_t written_size() const override; inline CommandResponse incoming_command_response() const { diff --git a/src/connectivity/bluetooth/core/bt-host/rfcomm/mux_commands_unittest.cc b/src/connectivity/bluetooth/core/bt-host/rfcomm/mux_commands_unittest.cc index 16fca1823dc8338117280bc1aaad3b4c82058668..814aa0be609ac901aef7d8cd74281bd9c7548d0f 100644 --- a/src/connectivity/bluetooth/core/bt-host/rfcomm/mux_commands_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/rfcomm/mux_commands_unittest.cc @@ -3,6 +3,7 @@ // found in the LICENSE file. #include "src/connectivity/bluetooth/core/bt-host/rfcomm/mux_commands.h" + #include "gtest/gtest.h" namespace bt { @@ -27,17 +28,15 @@ class RFCOMM_MuxCommandTest : public ::testing::Test {}; // // Length field is one octet long; the octet is EA ++ length, or 1 ++ 1110000. TEST_F(RFCOMM_MuxCommandTest, TestCommand) { - auto test_pattern = - common::CreateStaticByteBuffer('f', 'u', 'c', 'h', 's', 'i', 'a'); + auto test_pattern = CreateStaticByteBuffer('f', 'u', 'c', 'h', 's', 'i', 'a'); TestCommand command(CommandResponse::kCommand, test_pattern); ASSERT_EQ(command.written_size(), 1ul // Type + 1ul // Length + test_pattern.size()); // Payload - common::DynamicByteBuffer buffer(command.written_size()); + DynamicByteBuffer buffer(command.written_size()); command.Write(buffer.mutable_view()); - ASSERT_EQ(buffer, - common::CreateStaticByteBuffer(0b00100011, 0b00001111, 'f', 'u', + ASSERT_EQ(buffer, CreateStaticByteBuffer(0b00100011, 0b00001111, 'f', 'u', 'c', 'h', 's', 'i', 'a')); auto read_command = MuxCommand::Parse(buffer); @@ -67,9 +66,9 @@ TEST_F(RFCOMM_MuxCommandTest, FconCommand) { ASSERT_EQ(command.written_size(), 1ul // Type + 1ul); // Length - common::DynamicByteBuffer buffer(command.written_size()); + DynamicByteBuffer buffer(command.written_size()); command.Write(buffer.mutable_view()); - ASSERT_EQ(buffer, common::CreateStaticByteBuffer(0b10100001, 0b00000001)); + ASSERT_EQ(buffer, CreateStaticByteBuffer(0b10100001, 0b00000001)); auto read_command = MuxCommand::Parse(buffer); EXPECT_EQ(read_command->command_response(), CommandResponse::kResponse); @@ -96,9 +95,9 @@ TEST_F(RFCOMM_MuxCommandTest, FcoffCommand) { ASSERT_EQ(command.written_size(), 1ul // Type + 1ul); // Length - common::DynamicByteBuffer buffer(command.written_size()); + DynamicByteBuffer buffer(command.written_size()); command.Write(buffer.mutable_view()); - ASSERT_EQ(buffer, common::CreateStaticByteBuffer(0b01100011, 0b00000001)); + ASSERT_EQ(buffer, CreateStaticByteBuffer(0b01100011, 0b00000001)); auto read_command = MuxCommand::Parse(buffer); EXPECT_EQ(read_command->command_response(), CommandResponse::kCommand); @@ -137,10 +136,9 @@ TEST_F(RFCOMM_MuxCommandTest, ModemStatusCommand) { break_value); ASSERT_EQ(command.written_size(), 5ul); - common::DynamicByteBuffer buffer(command.written_size()); + DynamicByteBuffer buffer(command.written_size()); command.Write(buffer.mutable_view()); - ASSERT_EQ(buffer, - common::CreateStaticByteBuffer(0b11100011, 0b00000111, 0b10001111, + ASSERT_EQ(buffer, CreateStaticByteBuffer(0b11100011, 0b00000111, 0b10001111, 0b10001010, 0b10100011)); auto read_command = MuxCommand::Parse(buffer); @@ -187,10 +185,9 @@ TEST_F(RFCOMM_MuxCommandTest, RemotePortNegotiationCommand8Octets) { mask); EXPECT_EQ(command.written_size(), 10ul); - common::DynamicByteBuffer buffer(command.written_size()); + DynamicByteBuffer buffer(command.written_size()); command.Write(buffer.mutable_view()); - EXPECT_EQ(buffer, - common::CreateStaticByteBuffer(0b10010011, 0b00010001, 0b11110111, + EXPECT_EQ(buffer, CreateStaticByteBuffer(0b10010011, 0b00010001, 0b11110111, 0b00000111, 0b00001101, 0b00010101, 0x23, 0xDA, 0b01010101, 0b00011011)); @@ -215,10 +212,9 @@ TEST_F(RFCOMM_MuxCommandTest, RemotePortNegotiationCommand1Octet) { RemotePortNegotiationCommand command(CommandResponse::kCommand, 61); ASSERT_EQ(command.written_size(), 3ul); - common::DynamicByteBuffer buffer(command.written_size()); + DynamicByteBuffer buffer(command.written_size()); command.Write(buffer.mutable_view()); - ASSERT_EQ(buffer, - common::CreateStaticByteBuffer(0b10010011, 0b00000011, 0b11110111)); + ASSERT_EQ(buffer, CreateStaticByteBuffer(0b10010011, 0b00000011, 0b11110111)); auto read_command = MuxCommand::Parse(buffer); EXPECT_EQ(read_command->command_response(), CommandResponse::kCommand); @@ -234,10 +230,10 @@ TEST_F(RFCOMM_MuxCommandTest, RemoteLineStatusCommand) { LineError::kFramingError); ASSERT_EQ(command.written_size(), 4ul); - common::DynamicByteBuffer buffer(command.written_size()); + DynamicByteBuffer buffer(command.written_size()); command.Write(buffer.mutable_view()); - ASSERT_EQ(buffer, common::CreateStaticByteBuffer(0b01010011, 0b00000101, - 0b11110111, 0b00001001)); + ASSERT_EQ(buffer, CreateStaticByteBuffer(0b01010011, 0b00000101, 0b11110111, + 0b00001001)); auto read_command = MuxCommand::Parse(buffer); EXPECT_EQ(read_command->command_response(), CommandResponse::kCommand); @@ -254,10 +250,9 @@ TEST_F(RFCOMM_MuxCommandTest, NonSupportedCommandResponse) { NonSupportedCommandResponse command(CommandResponse::kResponse, 0b00101001); ASSERT_EQ(command.written_size(), 3ul); - common::DynamicByteBuffer buffer(command.written_size()); + DynamicByteBuffer buffer(command.written_size()); command.Write(buffer.mutable_view()); - ASSERT_EQ(buffer, - common::CreateStaticByteBuffer(0b00010001, 0b00000011, 0b10100101)); + ASSERT_EQ(buffer, CreateStaticByteBuffer(0b00010001, 0b00000011, 0b10100101)); auto read_command = MuxCommand::Parse(buffer); EXPECT_EQ(read_command->command_response(), CommandResponse::kResponse); @@ -282,11 +277,11 @@ TEST_F(RFCOMM_MuxCommandTest, DLCParameterNegotiationCommand) { DLCParameterNegotiationCommand command(CommandResponse::kResponse, params); ASSERT_EQ(command.written_size(), 10ul); - common::DynamicByteBuffer buffer(command.written_size()); + DynamicByteBuffer buffer(command.written_size()); command.Write(buffer.mutable_view()); - ASSERT_EQ(buffer, common::CreateStaticByteBuffer( - 0b10000001, 0b00010001, 0b00111101, 0xE0, kMaxPriority, - 0, 0x34, 0x12, 0, kMaxInitialCredits)); + ASSERT_EQ(buffer, CreateStaticByteBuffer(0b10000001, 0b00010001, 0b00111101, + 0xE0, kMaxPriority, 0, 0x34, 0x12, 0, + kMaxInitialCredits)); auto read_command = MuxCommand::Parse(buffer); EXPECT_EQ(read_command->command_response(), CommandResponse::kResponse); diff --git a/src/connectivity/bluetooth/core/bt-host/rfcomm/rfcomm_unittest.cc b/src/connectivity/bluetooth/core/bt-host/rfcomm/rfcomm_unittest.cc index cc61e47bca5a1010cf2624d4e8a485e9ec6f8a72..fb28ffe2782a35b24d07f0f092b92500541ddd9c 100644 --- a/src/connectivity/bluetooth/core/bt-host/rfcomm/rfcomm_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/rfcomm/rfcomm_unittest.cc @@ -18,7 +18,7 @@ constexpr hci::ConnectionHandle kHandle1 = 1; void DoNothingWithChannel(fbl::RefPtr<Channel> channel, ServerChannel server_channel) {} -void DoNothingWithBuffer(common::ByteBufferPtr buffer) {} +void DoNothingWithBuffer(ByteBufferPtr buffer) {} class RFCOMM_ChannelManagerTest : public l2cap::testing::FakeChannelTest { public: @@ -67,8 +67,7 @@ class RFCOMM_ChannelManagerTest : public l2cap::testing::FakeChannelTest { if (handle_to_incoming_frames_.find(handle) == handle_to_incoming_frames_.end()) { handle_to_incoming_frames_.emplace( - handle, - std::queue<std::unique_ptr<const common::ByteBuffer>>()); + handle, std::queue<std::unique_ptr<const ByteBuffer>>()); } handle_to_incoming_frames_[handle].push(std::move(sdu)); }, @@ -122,7 +121,7 @@ class RFCOMM_ChannelManagerTest : public l2cap::testing::FakeChannelTest { std::unique_ptr<Frame> frame) { auto channel = GetFakeChannel(handle); - auto buffer = common::NewSlabBuffer(frame->written_size()); + auto buffer = NewSlabBuffer(frame->written_size()); frame->Write(buffer->mutable_view()); channel->Receive(buffer->view()); } @@ -149,7 +148,7 @@ class RFCOMM_ChannelManagerTest : public l2cap::testing::FakeChannelTest { std::unique_ptr<ChannelManager> channel_manager_; std::unordered_map<hci::ConnectionHandle, - std::queue<std::unique_ptr<const common::ByteBuffer>>> + std::queue<std::unique_ptr<const ByteBuffer>>> handle_to_incoming_frames_; // Maps remote peers (represented as connection handles) to the L2CAP channel @@ -697,13 +696,13 @@ TEST_F(RFCOMM_ChannelManagerTest, OpenOutgoingChannel) { DLCI dlci = ServerChannelToDLCI(kMinServerChannel, state.role); - common::ByteBufferPtr received_data; + ByteBufferPtr received_data; channel->Activate( [&received_data](auto data) { received_data = std::move(data); }, []() {}, dispatcher()); - auto pattern = common::CreateStaticByteBuffer(1, 2, 3, 4); - auto buffer = std::make_unique<common::DynamicByteBuffer>(pattern); + auto pattern = CreateStaticByteBuffer(1, 2, 3, 4); + auto buffer = std::make_unique<DynamicByteBuffer>(pattern); channel->Send(std::move(buffer)); RunLoopUntilIdle(); @@ -717,7 +716,7 @@ TEST_F(RFCOMM_ChannelManagerTest, OpenOutgoingChannel) { EXPECT_EQ(pattern, *static_cast<UserDataFrame*>(frame.get())->TakeInformation()); - buffer = std::make_unique<common::DynamicByteBuffer>(pattern); + buffer = std::make_unique<DynamicByteBuffer>(pattern); ReceiveFrame(kHandle1, std::make_unique<UserDataFrame>( state.role, state.credit_based_flow, dlci, std::move(buffer))); @@ -744,13 +743,13 @@ TEST_F(RFCOMM_ChannelManagerTest, OpenIncomingChannel) { DLCI dlci = ServerChannelToDLCI(server_channel, OppositeRole(state.role)); - common::ByteBufferPtr received_data; + ByteBufferPtr received_data; channel->Activate( [&received_data](auto data) { received_data = std::move(data); }, []() {}, dispatcher()); - auto pattern = common::CreateStaticByteBuffer(1, 2, 3, 4); - auto buffer = std::make_unique<common::DynamicByteBuffer>(pattern); + auto pattern = CreateStaticByteBuffer(1, 2, 3, 4); + auto buffer = std::make_unique<DynamicByteBuffer>(pattern); channel->Send(std::move(buffer)); RunLoopUntilIdle(); @@ -764,7 +763,7 @@ TEST_F(RFCOMM_ChannelManagerTest, OpenIncomingChannel) { EXPECT_EQ(pattern, *static_cast<UserDataFrame*>(frame.get())->TakeInformation()); - buffer = std::make_unique<common::DynamicByteBuffer>(pattern); + buffer = std::make_unique<DynamicByteBuffer>(pattern); ReceiveFrame(kHandle1, std::make_unique<UserDataFrame>( state.role, state.credit_based_flow, dlci, std::move(buffer))); @@ -788,13 +787,14 @@ TEST_F(RFCOMM_ChannelManagerTest, CreditBasedFlow_Outgoing) { kHandle1, PeerState{true /*credit-based flow*/, Role::kUnassigned}); auto channel = OpenOutgoingChannel(kHandle1, kMinServerChannel); - channel->Activate(&DoNothingWithBuffer, [] {}, dispatcher()); + channel->Activate( + &DoNothingWithBuffer, [] {}, dispatcher()); auto& queue = handle_to_incoming_frames_[kHandle1]; for (uint8_t i = 0; i < kMaxInitialCredits; i++) { // Send UIH frame with data. - channel->Send(common::NewBuffer(i)); + channel->Send(NewBuffer(i)); RunLoopUntilIdle(); } @@ -803,7 +803,7 @@ TEST_F(RFCOMM_ChannelManagerTest, CreditBasedFlow_Outgoing) { { // Send one more. - channel->Send(common::NewBuffer(7)); + channel->Send(NewBuffer(7)); RunLoopUntilIdle(); } @@ -824,7 +824,7 @@ TEST_F(RFCOMM_ChannelManagerTest, CreditBasedFlow_Outgoing) { EXPECT_EQ(8ul, queue.size()); for (uint8_t i = 0; i < 3; i++) { - channel->Send(common::NewBuffer(8 + i)); + channel->Send(NewBuffer(8 + i)); RunLoopUntilIdle(); } @@ -898,7 +898,8 @@ TEST_F(RFCOMM_ChannelManagerTest, CreditBasedFlow_Incoming) { auto channel = OpenOutgoingChannel(kHandle1, kMinServerChannel); DLCI dlci = ServerChannelToDLCI(kMinServerChannel, state.role); - channel->Activate(&DoNothingWithBuffer, [] {}, dispatcher()); + channel->Activate( + &DoNothingWithBuffer, [] {}, dispatcher()); auto& queue = handle_to_incoming_frames_[kHandle1]; @@ -907,9 +908,9 @@ TEST_F(RFCOMM_ChannelManagerTest, CreditBasedFlow_Incoming) { { // Send one frame. - ReceiveFrame(kHandle1, std::make_unique<UserDataFrame>( - state.role, state.credit_based_flow, dlci, - common::NewBuffer(0))); + ReceiveFrame(kHandle1, + std::make_unique<UserDataFrame>( + state.role, state.credit_based_flow, dlci, NewBuffer(0))); credits--; RunLoopUntilIdle(); } @@ -934,7 +935,7 @@ TEST_F(RFCOMM_ChannelManagerTest, CreditBasedFlow_Incoming) { for (int i = 0; i < 2; i++) { ReceiveFrame(kHandle1, std::make_unique<UserDataFrame>( state.role, state.credit_based_flow, dlci, - common::NewBuffer(i + 1))); + NewBuffer(i + 1))); credits--; RunLoopUntilIdle(); } @@ -944,7 +945,7 @@ TEST_F(RFCOMM_ChannelManagerTest, CreditBasedFlow_Incoming) { { // Send frame to the remote, to which we should attach credits. - channel->Send(common::NewBuffer(3)); + channel->Send(NewBuffer(3)); RunLoopUntilIdle(); } @@ -952,7 +953,7 @@ TEST_F(RFCOMM_ChannelManagerTest, CreditBasedFlow_Incoming) { // Send and empty frame, which shouldn't cost any credits. ReceiveFrame(kHandle1, std::make_unique<UserDataFrame>( state.role, state.credit_based_flow, dlci, - common::NewSlabBuffer(0))); + NewSlabBuffer(0))); RunLoopUntilIdle(); } diff --git a/src/connectivity/bluetooth/core/bt-host/rfcomm/session.cc b/src/connectivity/bluetooth/core/bt-host/rfcomm/session.cc index a50d1a6eb32494fc2604a8caa181df2059026392..343ccdd264f941aac8f92df53fd1e88f2d00f838 100644 --- a/src/connectivity/bluetooth/core/bt-host/rfcomm/session.cc +++ b/src/connectivity/bluetooth/core/bt-host/rfcomm/session.cc @@ -110,7 +110,7 @@ bool CreditsCandidate(Frame* frame) { } // namespace -void Session::SendUserData(DLCI dlci, common::ByteBufferPtr data) { +void Session::SendUserData(DLCI dlci, ByteBufferPtr data) { ZX_DEBUG_ASSERT(!data || data->size() <= GetMaximumUserDataLength()); bool sent = SendFrame(std::make_unique<UserDataFrame>( role_, credit_based_flow_, dlci, std::move(data))); @@ -233,7 +233,7 @@ void Session::OpenRemoteChannel(ServerChannel server_channel, }); } -void Session::RxCallback(common::ByteBufferPtr sdu) { +void Session::RxCallback(ByteBufferPtr sdu) { ZX_DEBUG_ASSERT(sdu); auto frame = Frame::Parse(credit_based_flow_, OppositeRole(role_), *sdu); if (!frame) { @@ -404,7 +404,7 @@ bool Session::SendFrame(std::unique_ptr<Frame> frame, fit::closure sent_cb) { } // Allocate and write the buffer. - auto buffer = common::NewSlabBuffer(frame->written_size()); + auto buffer = NewSlabBuffer(frame->written_size()); if (!buffer) { bt_log(WARN, "rfcomm", "couldn't allocate frame buffer (%zu)", frame->written_size()); diff --git a/src/connectivity/bluetooth/core/bt-host/rfcomm/session.h b/src/connectivity/bluetooth/core/bt-host/rfcomm/session.h index 2326ae0428aa5f406520f99b41de611ee18d6f21..1a1a68755eeb2046e0dab1563e84bc1392784c45 100644 --- a/src/connectivity/bluetooth/core/bt-host/rfcomm/session.h +++ b/src/connectivity/bluetooth/core/bt-host/rfcomm/session.h @@ -37,7 +37,7 @@ class Session { public: // User should first use GetMaximumUserDataLength() to determine the maximum // amount of data they can send. - void SendUserData(DLCI dlci, common::ByteBufferPtr data); + void SendUserData(DLCI dlci, ByteBufferPtr data); // Get the maximum length of data which can be sent in a single RFCOMM frame. // This should only be called after initial parameter negotiation is complete. @@ -72,7 +72,7 @@ class Session { ChannelOpenedCallback channel_opened_cb); // l2cap::Channel callbacks. - void RxCallback(common::ByteBufferPtr sdu); + void RxCallback(ByteBufferPtr sdu); void ClosedCallback(); // Send a SABM or a DISC command. When a response (UA or DM) is received, diff --git a/src/connectivity/bluetooth/core/bt-host/sdp/client.cc b/src/connectivity/bluetooth/core/bt-host/sdp/client.cc index b6109e5ae329a7e1f374a89cc6f8d49ffbeec568..51099984d2043bc606a7d5152885e58023cdfc9d 100644 --- a/src/connectivity/bluetooth/core/bt-host/sdp/client.cc +++ b/src/connectivity/bluetooth/core/bt-host/sdp/client.cc @@ -21,7 +21,7 @@ class Impl final : public Client { private: void ServiceSearchAttributes( - std::unordered_set<common::UUID> search_pattern, + std::unordered_set<UUID> search_pattern, const std::unordered_set<AttributeId>& req_attributes, SearchResultCallback result_cb, async_dispatcher_t* cb_dispatcher) override; @@ -44,7 +44,7 @@ class Impl final : public Client { }; // Callbacks for l2cap::Channel - void OnRxFrame(common::ByteBufferPtr sdu); + void OnRxFrame(ByteBufferPtr sdu); void OnChannelClosed(); // Finishes a pending transaction on this client, completing their callbacks. @@ -94,12 +94,12 @@ Impl::Impl(fbl::RefPtr<l2cap::Channel> channel) Impl::~Impl() { while (!pending_.empty()) { - Cancel(pending_.begin()->first, Status(common::HostError::kCanceled)); + Cancel(pending_.begin()->first, Status(HostError::kCanceled)); } } void Impl::ServiceSearchAttributes( - std::unordered_set<common::UUID> search_pattern, + std::unordered_set<UUID> search_pattern, const std::unordered_set<AttributeId>& req_attributes, SearchResultCallback result_cb, async_dispatcher_t* cb_dispatcher) { ServiceSearchAttributeRequest req; @@ -125,7 +125,7 @@ void Impl::ServiceSearchAttributes( auto& timeout_task = iter->second; // Timeouts are held in this so it is safe to use. timeout_task.set_handler( - [this, next]() { Cancel(next, Status(common::HostError::kTimedOut)); }); + [this, next]() { Cancel(next, Status(HostError::kTimedOut)); }); timeout_task.PostDelayed(async_get_default_dispatcher(), kTransactionTimeout); } @@ -148,7 +148,7 @@ void Impl::Finish(TransactionId id) { return; } } - cb(Status(common::HostError::kNotFound), {}); + cb(Status(HostError::kNotFound), {}); }); } @@ -171,9 +171,9 @@ void Impl::Cancel(TransactionId id, Status status) { status = std::move(status)] { callback(status, {}); }); } -void Impl::OnRxFrame(common::ByteBufferPtr data) { +void Impl::OnRxFrame(ByteBufferPtr data) { // Each SDU in SDP is one request or one response. Core 5.0 Vol 3 Part B, 4.2 - common::PacketView<sdp::Header> packet(data.get()); + PacketView<sdp::Header> packet(data.get()); size_t pkt_params_len = data->size() - sizeof(Header); uint16_t params_len = betoh16(packet.header().param_length); if (params_len != pkt_params_len) { @@ -191,7 +191,7 @@ void Impl::OnRxFrame(common::ByteBufferPtr data) { auto& transaction = it->second; Status parse_status = transaction.response.Parse(packet.payload_data()); if (!parse_status) { - if (parse_status.error() == common::HostError::kInProgress) { + if (parse_status.error() == HostError::kInProgress) { bt_log(INFO, "sdp", "Requesting continuation of id (%u)", tid); transaction.request.SetContinuationState( transaction.response.ContinuationState()); @@ -215,8 +215,7 @@ void Impl::OnChannelClosed() { bt_log(INFO, "sdp", "client channel closed"); channel_ = nullptr; while (!pending_.empty()) { - Cancel(pending_.begin()->first, - Status(common::HostError::kLinkDisconnected)); + Cancel(pending_.begin()->first, Status(HostError::kLinkDisconnected)); } } diff --git a/src/connectivity/bluetooth/core/bt-host/sdp/client.h b/src/connectivity/bluetooth/core/bt-host/sdp/client.h index ddb2ee4e9c1bc324b0201a6675299f11c0bd9a79..92663755cc81ee30f59e6876a729757cdd1f0120 100644 --- a/src/connectivity/bluetooth/core/bt-host/sdp/client.h +++ b/src/connectivity/bluetooth/core/bt-host/sdp/client.h @@ -5,11 +5,11 @@ #ifndef SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_SDP_CLIENT_H_ #define SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_SDP_CLIENT_H_ -#include <unordered_map> - #include <fbl/ref_ptr.h> #include <lib/async/cpp/task.h> +#include <unordered_map> + #include "src/connectivity/bluetooth/core/bt-host/l2cap/scoped_channel.h" #include "src/connectivity/bluetooth/core/bt-host/sdp/pdu.h" #include "src/connectivity/bluetooth/core/bt-host/sdp/sdp.h" @@ -37,11 +37,11 @@ class Client { // the attributes requested. As long as true is returned, it can still // be called. // - when no more services remain, the result_cb status will be - // common::HostError::kNotFound. The return value is ignored. + // HostError::kNotFound. The return value is ignored. using SearchResultCallback = fit::function<bool( sdp::Status, const std::map<AttributeId, DataElement>&)>; virtual void ServiceSearchAttributes( - std::unordered_set<common::UUID> search_pattern, + std::unordered_set<UUID> search_pattern, const std::unordered_set<AttributeId>& req_attributes, SearchResultCallback result_cb, async_dispatcher_t* cb_dispatcher) = 0; }; diff --git a/src/connectivity/bluetooth/core/bt-host/sdp/client_unittest.cc b/src/connectivity/bluetooth/core/bt-host/sdp/client_unittest.cc index e34d790217217f0de1659e1b4991799737a8c4d6..99daea2583700704f9f15847ea1d0d57faa53d14 100644 --- a/src/connectivity/bluetooth/core/bt-host/sdp/client_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/sdp/client_unittest.cc @@ -5,7 +5,6 @@ #include "src/connectivity/bluetooth/core/bt-host/sdp/client.h" #include "gtest/gtest.h" - #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" #include "src/connectivity/bluetooth/core/bt-host/l2cap/fake_channel.h" #include "src/connectivity/bluetooth/core/bt-host/l2cap/fake_channel_test.h" @@ -18,10 +17,6 @@ namespace { using TestingBase = bt::l2cap::testing::FakeChannelTest; constexpr l2cap::ChannelId kTestChannelId = 0x0041; -using common::CreateStaticByteBuffer; -using common::LowerBits; -using common::UpperBits; - class SDP_ClientTest : public TestingBase { public: SDP_ClientTest() = default; @@ -59,7 +54,7 @@ TEST_F(SDP_ClientTest, ConnectAndQuery) { cb_count++; if (cb_count == 3) { EXPECT_FALSE(status); - EXPECT_EQ(common::HostError::kNotFound, status.error()); + EXPECT_EQ(HostError::kNotFound, status.error()); return true; } // All results should have the ServiceClassIdList. @@ -76,7 +71,7 @@ TEST_F(SDP_ClientTest, ConnectAndQuery) { return true; }; - const auto kSearchExpectedParams = common::CreateStaticByteBuffer( + const auto kSearchExpectedParams = CreateStaticByteBuffer( // ServiceSearchPattern 0x35, 0x03, // Sequence uint8 3 bytes 0x19, 0x11, 0x0B, // UUID (kAudioSink) @@ -135,8 +130,8 @@ TEST_F(SDP_ClientTest, ConnectAndQuery) { rsp.SetAttribute(1, kBluetoothProfileDescriptorList, rec.GetAttribute(kBluetoothProfileDescriptorList).Clone()); - auto rsp_ptr = rsp.GetPDU(0xFFFF /* Max attribute bytes */, request_tid, - common::BufferView()); + auto rsp_ptr = + rsp.GetPDU(0xFFFF /* Max attribute bytes */, request_tid, BufferView()); fake_chan()->Receive(*rsp_ptr); RunLoopUntilIdle(); @@ -162,7 +157,7 @@ TEST_F(SDP_ClientTest, ContinuingResponseRequested) { cb_count++; if (cb_count == 3) { EXPECT_FALSE(status); - EXPECT_EQ(common::HostError::kNotFound, status.error()); + EXPECT_EQ(HostError::kNotFound, status.error()); return true; } // All results should have the ServiceClassIdList. @@ -171,7 +166,7 @@ TEST_F(SDP_ClientTest, ContinuingResponseRequested) { return true; }; - const auto kSearchExpectedParams = common::CreateStaticByteBuffer( + const auto kSearchExpectedParams = CreateStaticByteBuffer( // ServiceSearchPattern 0x35, 0x03, // Sequence uint8 3 bytes 0x19, 0x11, 0x0B, // UUID (kAudioSink) @@ -243,7 +238,7 @@ TEST_F(SDP_ClientTest, NoResults) { const std::map<AttributeId, DataElement> &attrs) { cb_count++; EXPECT_FALSE(status); - EXPECT_EQ(common::HostError::kNotFound, status.error()); + EXPECT_EQ(HostError::kNotFound, status.error()); return true; }; @@ -285,8 +280,8 @@ TEST_F(SDP_ClientTest, NoResults) { // Receive an empty response ServiceSearchAttributeResponse rsp; - auto rsp_ptr = rsp.GetPDU(0xFFFF /* Max attribute bytes */, request_tid, - common::BufferView()); + auto rsp_ptr = + rsp.GetPDU(0xFFFF /* Max attribute bytes */, request_tid, BufferView()); fake_chan()->Receive(*rsp_ptr); RunLoopUntilIdle(); @@ -306,7 +301,7 @@ TEST_F(SDP_ClientTest, Disconnected) { const std::map<AttributeId, DataElement> &attrs) { cb_count++; EXPECT_FALSE(status); - EXPECT_EQ(common::HostError::kLinkDisconnected, status.error()); + EXPECT_EQ(HostError::kLinkDisconnected, status.error()); return true; }; @@ -365,7 +360,7 @@ TEST_F(SDP_ClientTest, InvalidResponse) { const std::map<AttributeId, DataElement> &attrs) { cb_count++; EXPECT_FALSE(status); - EXPECT_EQ(common::HostError::kPacketMalformed, status.error()); + EXPECT_EQ(HostError::kPacketMalformed, status.error()); return true; }; @@ -426,7 +421,7 @@ TEST_F(SDP_ClientTest, Timeout) { const std::map<AttributeId, DataElement> &attrs) { cb_count++; EXPECT_FALSE(status); - EXPECT_EQ(common::HostError::kTimedOut, status.error()); + EXPECT_EQ(HostError::kTimedOut, status.error()); return true; }; diff --git a/src/connectivity/bluetooth/core/bt-host/sdp/data_element.cc b/src/connectivity/bluetooth/core/bt-host/sdp/data_element.cc index 546636124e9d26ca0efb9e5eb73a47e06d1ce897..213e262744a08ee5a92e9828d691091479ef92cd 100644 --- a/src/connectivity/bluetooth/core/bt-host/sdp/data_element.cc +++ b/src/connectivity/bluetooth/core/bt-host/sdp/data_element.cc @@ -14,9 +14,6 @@ namespace bt { -using common::MutableByteBuffer; -using common::UUID; - namespace sdp { namespace { @@ -330,7 +327,7 @@ void DataElement::SetVariableSize(size_t length) { } } -size_t DataElement::Read(DataElement* elem, const common::ByteBuffer& buffer) { +size_t DataElement::Read(DataElement* elem, const ByteBuffer& buffer) { if (buffer.size() == 0) { return 0; } @@ -338,7 +335,7 @@ size_t DataElement::Read(DataElement* elem, const common::ByteBuffer& buffer) { Size size_desc = Size(buffer[0] & kDataElementSizeTypeMask); size_t data_bytes = 0; size_t bytes_read = 1; - common::BufferView cursor = buffer.view(bytes_read); + BufferView cursor = buffer.view(bytes_read); switch (size_desc) { case DataElement::Size::kOneByte: case DataElement::Size::kTwoBytes: @@ -433,7 +430,7 @@ size_t DataElement::Read(DataElement* elem, const common::ByteBuffer& buffer) { } else if (size_desc == Size::kFourBytes) { elem->Set(UUID(betoh32(cursor.As<uint32_t>()))); } else if (size_desc == Size::kSixteenBytes) { - common::StaticByteBuffer<16> uuid_bytes; + StaticByteBuffer<16> uuid_bytes; // UUID expects these to be in little-endian order. cursor.Copy(&uuid_bytes, 0, 16); std::reverse(uuid_bytes.mutable_data(), uuid_bytes.mutable_data() + 16); @@ -458,7 +455,7 @@ size_t DataElement::Read(DataElement* elem, const common::ByteBuffer& buffer) { if (static_cast<uint8_t>(size_desc) < 5) { return 0; } - common::BufferView sequence_buf = cursor.view(0, data_bytes); + BufferView sequence_buf = cursor.view(0, data_bytes); size_t remaining = data_bytes; ZX_DEBUG_ASSERT(sequence_buf.size() == data_bytes); @@ -524,7 +521,7 @@ size_t DataElement::Write(MutableByteBuffer* buffer) const { buffer->Write(&type_and_size, 1); size_t pos = 1; - common::MutableBufferView cursor = buffer->mutable_view(pos); + MutableBufferView cursor = buffer->mutable_view(pos); switch (type_) { case Type::kNull: { diff --git a/src/connectivity/bluetooth/core/bt-host/sdp/data_element.h b/src/connectivity/bluetooth/core/bt-host/sdp/data_element.h index e9efa501e890ed56ef1eb2317b5bbd2094706bf9..0be04ae02023182ce5bc6b8c5f77a516c0960e82 100644 --- a/src/connectivity/bluetooth/core/bt-host/sdp/data_element.h +++ b/src/connectivity/bluetooth/core/bt-host/sdp/data_element.h @@ -90,7 +90,7 @@ class DataElement { // Reads a DataElement from |buffer|, replacing any data that was in |elem|. // Returns the amount of space occupied on |buffer| by the data element, or // zero if no element could be read. - static size_t Read(DataElement* elem, const common::ByteBuffer& buffer); + static size_t Read(DataElement* elem, const ByteBuffer& buffer); // The type of this element. Type type() const { return type_; } @@ -104,7 +104,7 @@ class DataElement { // std::nullptr_t - kNull // uint8_t, .., uint64_t - kUnsignedInt // int8_t .. int64_t - kSignedInt - // const common::UUID& - kUuid + // const UUID& - kUuid // const std::string& - kString // bool - kBoolean // std::vector<DataElemnt> - kSequence @@ -132,7 +132,7 @@ class DataElement { // Writes this DataElement to |buffer|. // Returns the number of bytes used for writing this element. - size_t Write(common::MutableByteBuffer* buffer) const; + size_t Write(MutableByteBuffer* buffer) const; // Debug representation of this element (including it's type and size) in a // string, i.e. UnsignedInt:4(15) or Sequence { UUID(1567), UUID(2502) } @@ -152,7 +152,7 @@ class DataElement { // set correctly. int64_t int_value_; uint64_t uint_value_; - common::UUID uuid_; + UUID uuid_; std::string string_; std::vector<DataElement> aggregate_; }; diff --git a/src/connectivity/bluetooth/core/bt-host/sdp/data_element_unittest.cc b/src/connectivity/bluetooth/core/bt-host/sdp/data_element_unittest.cc index 5240d6af70c48801e5cc8b73cbbe65d5581c1fd0..d6293f085a13dc3900fc54e142b368edff435cbd 100644 --- a/src/connectivity/bluetooth/core/bt-host/sdp/data_element_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/sdp/data_element_unittest.cc @@ -3,20 +3,16 @@ // found in the LICENSE file. #include "src/connectivity/bluetooth/core/bt-host/sdp/data_element.h" -#include "src/connectivity/bluetooth/core/bt-host/sdp/sdp.h" #include "gtest/gtest.h" - #include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" +#include "src/connectivity/bluetooth/core/bt-host/sdp/sdp.h" namespace bt { namespace sdp { namespace { -using common::LowerBits; -using common::UpperBits; - using SDP_DataElementTest = ::testing::Test; TEST_F(SDP_DataElementTest, CreateIsNull) { @@ -25,8 +21,8 @@ TEST_F(SDP_DataElementTest, CreateIsNull) { EXPECT_TRUE(elem.Get<std::nullptr_t>()); EXPECT_EQ(nullptr, *elem.Get<std::nullptr_t>()); - auto expected = common::CreateStaticByteBuffer(0x00); - common::DynamicByteBuffer buf(1); + auto expected = CreateStaticByteBuffer(0x00); + DynamicByteBuffer buf(1); EXPECT_EQ(1u, elem.Write(&buf)); EXPECT_TRUE(ContainersEqual(expected, buf)); } @@ -48,7 +44,7 @@ TEST_F(SDP_DataElementTest, SetAndGet) { } TEST_F(SDP_DataElementTest, Read) { - auto buf = common::CreateStaticByteBuffer( + auto buf = CreateStaticByteBuffer( 0x25, // Type (4: String) & Size (5: in an additional byte) = 0b00100 101 0x0B, // Bytes 'F', 'u', 'c', 'h', 's', 'i', 'a', 0xF0, 0x9F, 0x92, 0x96, // String @@ -70,7 +66,7 @@ TEST_F(SDP_DataElementTest, Read) { } TEST_F(SDP_DataElementTest, ReadUUID) { - auto buf = common::CreateStaticByteBuffer( + auto buf = CreateStaticByteBuffer( 0x19, // Type (3: UUID) & Size (1: two bytes) = 0b00011 001 0x01, 0x00 // L2CAP ); @@ -78,24 +74,24 @@ TEST_F(SDP_DataElementTest, ReadUUID) { DataElement elem; EXPECT_EQ(3u, DataElement::Read(&elem, buf)); EXPECT_EQ(DataElement::Type::kUuid, elem.type()); - EXPECT_EQ(common::UUID(uint16_t(0x0100)), *elem.Get<common::UUID>()); + EXPECT_EQ(UUID(uint16_t(0x0100)), *elem.Get<UUID>()); - auto buf2 = common::CreateStaticByteBuffer( + auto buf2 = CreateStaticByteBuffer( 0x1A, // Type (3: UUID) & Size (2: four bytes) = 0b00011 010 0x01, 0x02, 0x03, 0x04); EXPECT_EQ(5u, DataElement::Read(&elem, buf2)); EXPECT_EQ(DataElement::Type::kUuid, elem.type()); - EXPECT_EQ(common::UUID(uint32_t(0x01020304)), *elem.Get<common::UUID>()); + EXPECT_EQ(UUID(uint32_t(0x01020304)), *elem.Get<UUID>()); - auto buf3 = common::CreateStaticByteBuffer( + auto buf3 = CreateStaticByteBuffer( 0x1B, // Type (3: UUID) & Size (3: eight bytes) = 0b00011 011 0x01, 0x02, 0x03, 0x04, 0x01, 0x02, 0x03, 0x04, 0x01, 0x02, 0x03, 0x04, 0x01, 0x02, 0x03, 0x04); EXPECT_EQ(0u, DataElement::Read(&elem, buf3)); - auto buf4 = common::CreateStaticByteBuffer( + auto buf4 = CreateStaticByteBuffer( 0x1C, // Type (3: UUID) & Size (3: eight bytes) = 0b00011 100 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10); @@ -103,9 +99,9 @@ TEST_F(SDP_DataElementTest, ReadUUID) { EXPECT_EQ(17u, DataElement::Read(&elem, buf4)); EXPECT_EQ(DataElement::Type::kUuid, elem.type()); // UInt128 in UUID is little-endian - EXPECT_EQ(common::UUID({0x10, 0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x08, - 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01}), - *elem.Get<common::UUID>()); + EXPECT_EQ(UUID({0x10, 0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x08, 0x07, + 0x06, 0x05, 0x04, 0x03, 0x02, 0x01}), + *elem.Get<UUID>()); } TEST_F(SDP_DataElementTest, Write) { @@ -115,7 +111,7 @@ TEST_F(SDP_DataElementTest, Write) { // SerialPort from Assigned Numbers std::vector<DataElement> service_class_list; - service_class_list.emplace_back(DataElement(common::UUID(uint16_t(0x1101)))); + service_class_list.emplace_back(DataElement(UUID(uint16_t(0x1101)))); DataElement service_class_value(std::move(service_class_list)); attribute_list.emplace_back(DataElement(kServiceClassIdList)); attribute_list.emplace_back(std::move(service_class_value)); @@ -144,7 +140,7 @@ TEST_F(SDP_DataElementTest, Write) { // Bluetooth Profile Descriptor List std::vector<DataElement> profile_sequence_list; std::vector<DataElement> spp_sequence; - spp_sequence.push_back(DataElement(common::UUID(uint16_t(0x1101)))); + spp_sequence.push_back(DataElement(UUID(uint16_t(0x1101)))); spp_sequence.push_back(DataElement(uint16_t(0x0102))); profile_sequence_list.emplace_back(std::move(spp_sequence)); @@ -155,7 +151,7 @@ TEST_F(SDP_DataElementTest, Write) { DataElement attribute_lists_elem(std::move(attribute_list)); // clang-format off - auto expected = common::CreateStaticByteBuffer( + auto expected = CreateStaticByteBuffer( 0x35, 0x29, // Sequence uint8 41 bytes 0x09, // uint16_t type UpperBits(kServiceClassIdList), LowerBits(kServiceClassIdList), @@ -187,7 +183,7 @@ TEST_F(SDP_DataElementTest, Write) { ); // clang-format on - common::DynamicByteBuffer block(43); + DynamicByteBuffer block(43); size_t written = attribute_lists_elem.Write(&block); @@ -198,7 +194,7 @@ TEST_F(SDP_DataElementTest, Write) { TEST_F(SDP_DataElementTest, ReadSequence) { // clang-format off - auto buf = common::CreateStaticByteBuffer( + auto buf = CreateStaticByteBuffer( 0x35, 0x08, // Sequence with 1 byte length (8) 0x09, 0x00, 0x01, // uint16_t: 1 0x0A, 0x00, 0x00, 0x00, 0x02 // uint32_t: 2 @@ -208,7 +204,7 @@ TEST_F(SDP_DataElementTest, ReadSequence) { DataElement elem; EXPECT_EQ(buf.size(), DataElement::Read(&elem, buf)); EXPECT_EQ(DataElement::Type::kSequence, elem.type()); - auto* it = elem.At(0); + auto *it = elem.At(0); EXPECT_EQ(DataElement::Type::kUnsignedInt, it->type()); EXPECT_EQ(1u, *it->Get<uint16_t>()); @@ -218,7 +214,7 @@ TEST_F(SDP_DataElementTest, ReadSequence) { } TEST_F(SDP_DataElementTest, ReadNestedSeqeunce) { - auto buf = common::CreateStaticByteBuffer( + auto buf = CreateStaticByteBuffer( 0x35, 0x1C, // Sequence uint8 28 bytes // Sequence 0 0x35, 0x08, // Sequence uint8 8 bytes diff --git a/src/connectivity/bluetooth/core/bt-host/sdp/pdu.cc b/src/connectivity/bluetooth/core/bt-host/sdp/pdu.cc index 3922fc931b1c6c4b6782e1be5447c4cd23c88674..f95235c90134f75a9ab76e2b471763e406a4fb1e 100644 --- a/src/connectivity/bluetooth/core/bt-host/sdp/pdu.cc +++ b/src/connectivity/bluetooth/core/bt-host/sdp/pdu.cc @@ -4,20 +4,15 @@ #include "src/connectivity/bluetooth/core/bt-host/sdp/pdu.h" +#include <endian.h> + #include "src/connectivity/bluetooth/core/bt-host/common/log.h" #include "src/connectivity/bluetooth/core/bt-host/common/packet_view.h" #include "src/connectivity/bluetooth/core/bt-host/common/slab_allocator.h" #include "src/connectivity/bluetooth/core/bt-host/sdp/status.h" -#include <endian.h> - namespace bt { -using common::BufferView; -using common::ByteBuffer; -using common::HostError; -using common::MutableByteBuffer; - namespace sdp { namespace { @@ -50,13 +45,13 @@ bool ValidContinuationState(const ByteBuffer& buf, BufferView* out) { return true; } -common::MutableByteBufferPtr GetNewPDU(OpCode pdu_id, TransactionId tid, - uint16_t param_length) { - auto ptr = common::NewSlabBuffer(sizeof(Header) + param_length); +MutableByteBufferPtr GetNewPDU(OpCode pdu_id, TransactionId tid, + uint16_t param_length) { + auto ptr = NewSlabBuffer(sizeof(Header) + param_length); if (!ptr) { return nullptr; } - common::MutablePacketView<Header> packet(ptr.get(), param_length); + MutablePacketView<Header> packet(ptr.get(), param_length); packet.mutable_header()->pdu_id = pdu_id; packet.mutable_header()->tid = htobe16(tid); packet.mutable_header()->param_length = htobe16(param_length); @@ -189,8 +184,8 @@ Status ErrorResponse::Parse(const ByteBuffer& buf) { return Status(); } -common::MutableByteBufferPtr ErrorResponse::GetPDU(uint16_t, TransactionId tid, - const ByteBuffer&) const { +MutableByteBufferPtr ErrorResponse::GetPDU(uint16_t, TransactionId tid, + const ByteBuffer&) const { auto ptr = GetNewPDU(kErrorResponse, tid, sizeof(ErrorCode)); size_t written = sizeof(Header); @@ -202,7 +197,7 @@ common::MutableByteBufferPtr ErrorResponse::GetPDU(uint16_t, TransactionId tid, ServiceSearchRequest::ServiceSearchRequest() : Request(), max_service_record_count_(0xFFFF) {} -ServiceSearchRequest::ServiceSearchRequest(const common::ByteBuffer& params) +ServiceSearchRequest::ServiceSearchRequest(const ByteBuffer& params) : ServiceSearchRequest() { DataElement search_pattern; size_t read_size = DataElement::Read(&search_pattern, params); @@ -226,7 +221,7 @@ ServiceSearchRequest::ServiceSearchRequest(const common::ByteBuffer& params) service_search_pattern_.clear(); return; } - service_search_pattern_.emplace(*(it->Get<common::UUID>())); + service_search_pattern_.emplace(*(it->Get<UUID>())); } if (count == 0) { bt_log(SPEW, "sdp", "Search pattern invalid: no records"); @@ -247,7 +242,7 @@ bool ServiceSearchRequest::valid() const { max_service_record_count_ > 0; } -common::ByteBufferPtr ServiceSearchRequest::GetPDU(TransactionId tid) const { +ByteBufferPtr ServiceSearchRequest::GetPDU(TransactionId tid) const { if (!valid()) { return nullptr; } @@ -286,14 +281,14 @@ bool ServiceSearchResponse::complete() const { return total_service_record_count_ == service_record_handle_list_.size(); } -const common::BufferView ServiceSearchResponse::ContinuationState() const { +const BufferView ServiceSearchResponse::ContinuationState() const { if (!continuation_state_) { - return common::BufferView(); + return BufferView(); } return continuation_state_->view(); } -Status ServiceSearchResponse::Parse(const common::ByteBuffer& buf) { +Status ServiceSearchResponse::Parse(const ByteBuffer& buf) { if (complete() && total_service_record_count_ != 0) { // This response was previously complete and non-empty. bt_log(SPEW, "sdp", "Can't parse into a complete response"); @@ -325,7 +320,7 @@ Status ServiceSearchResponse::Parse(const common::ByteBuffer& buf) { service_record_handle_list_.emplace_back(betoh32(view.As<uint32_t>())); } read_size += sizeof(ServiceHandle) * record_count; - common::BufferView cont_state_view; + BufferView cont_state_view; if (!ValidContinuationState(buf.view(read_size), &cont_state_view)) { bt_log(SPEW, "sdp", "Failed to find continuation state"); return Status(HostError::kPacketMalformed); @@ -333,16 +328,14 @@ Status ServiceSearchResponse::Parse(const common::ByteBuffer& buf) { if (cont_state_view.size() == 0) { continuation_state_ = nullptr; } else { - continuation_state_ = - std::make_unique<common::DynamicByteBuffer>(cont_state_view); + continuation_state_ = std::make_unique<DynamicByteBuffer>(cont_state_view); } return Status(); } // Continuation state: Index of the start record for the continued response. -common::MutableByteBufferPtr ServiceSearchResponse::GetPDU( - uint16_t max, TransactionId tid, - const common::ByteBuffer& cont_state) const { +MutableByteBufferPtr ServiceSearchResponse::GetPDU( + uint16_t max, TransactionId tid, const ByteBuffer& cont_state) const { if (!complete()) { return nullptr; } @@ -389,8 +382,7 @@ common::MutableByteBufferPtr ServiceSearchResponse::GetPDU( ServiceAttributeRequest::ServiceAttributeRequest() : service_record_handle_(0), max_attribute_byte_count_(0xFFFF) {} -ServiceAttributeRequest::ServiceAttributeRequest( - const common::ByteBuffer& params) { +ServiceAttributeRequest::ServiceAttributeRequest(const ByteBuffer& params) { if (params.size() < sizeof(uint32_t) + sizeof(uint16_t)) { bt_log(SPEW, "sdp", "packet too small for ServiceAttributeRequest"); max_attribute_byte_count_ = 0; @@ -427,7 +419,7 @@ bool ServiceAttributeRequest::valid() const { (attribute_ranges_.size() > 0); } -common::ByteBufferPtr ServiceAttributeRequest::GetPDU(TransactionId tid) const { +ByteBufferPtr ServiceAttributeRequest::GetPDU(TransactionId tid) const { if (!valid()) { return nullptr; } @@ -483,26 +475,26 @@ void ServiceAttributeRequest::AddAttributeRange(AttributeId start, ServiceAttributeResponse::ServiceAttributeResponse() {} -const common::BufferView ServiceAttributeResponse::ContinuationState() const { +const BufferView ServiceAttributeResponse::ContinuationState() const { if (!continuation_state_) { - return common::BufferView(); + return BufferView(); } return continuation_state_->view(); } bool ServiceAttributeResponse::complete() const { return !continuation_state_; } -Status ServiceAttributeResponse::Parse(const common::ByteBuffer& buf) { +Status ServiceAttributeResponse::Parse(const ByteBuffer& buf) { if (complete() && attributes_.size() != 0) { // This response was previously complete and non-empty bt_log(SPEW, "sdp", "Can't parse into a complete response"); // partial_response_ is already empty - return Status(common::HostError::kNotReady); + return Status(HostError::kNotReady); } if (buf.size() < sizeof(uint16_t)) { bt_log(SPEW, "sdp", "Packet too small to parse"); - return Status(common::HostError::kPacketMalformed); + return Status(HostError::kPacketMalformed); } uint16_t attribute_list_byte_count = betoh16(buf.As<uint16_t>()); @@ -510,20 +502,20 @@ Status ServiceAttributeResponse::Parse(const common::ByteBuffer& buf) { if (buf.view(read_size).size() < attribute_list_byte_count + sizeof(uint8_t)) { bt_log(SPEW, "sdp", "Not enough bytes in rest of packet"); - return Status(common::HostError::kPacketMalformed); + return Status(HostError::kPacketMalformed); } // Check to see if there's continuation. - common::BufferView cont_state_view; + BufferView cont_state_view; if (!ValidContinuationState(buf.view(read_size + attribute_list_byte_count), &cont_state_view)) { bt_log(SPEW, "sdp", "Continutation state is not valid"); - return Status(common::HostError::kPacketMalformed); + return Status(HostError::kPacketMalformed); } if (cont_state_view.size() == 0) { continuation_state_ = nullptr; } else { - continuation_state_ = common::NewSlabBuffer(cont_state_view.size()); + continuation_state_ = NewSlabBuffer(cont_state_view.size()); continuation_state_->Write(cont_state_view); } @@ -534,7 +526,7 @@ Status ServiceAttributeResponse::Parse(const common::ByteBuffer& buf) { if (partial_response_) { new_partial_size += partial_response_->size(); } - auto new_partial = common::NewSlabBuffer(new_partial_size); + auto new_partial = NewSlabBuffer(new_partial_size); if (partial_response_) { new_partial->Write(partial_response_->view()); new_partial->Write(attribute_list_bytes, partial_response_->size()); @@ -545,7 +537,7 @@ Status ServiceAttributeResponse::Parse(const common::ByteBuffer& buf) { if (continuation_state_) { // This is incomplete, we can't parse it yet. bt_log(SPEW, "sdp", "Continutation state, returning in progress"); - return Status(common::HostError::kInProgress); + return Status(HostError::kInProgress); } attribute_list_bytes = partial_response_->view(); } @@ -556,7 +548,7 @@ Status ServiceAttributeResponse::Parse(const common::ByteBuffer& buf) { (attribute_list.type() != DataElement::Type::kSequence)) { bt_log(SPEW, "sdp", "Couldn't parse attribute list or it wasn't a sequence"); - return Status(common::HostError::kPacketMalformed); + return Status(HostError::kPacketMalformed); } // Data Element sequence containing alternating attribute id and attribute @@ -569,12 +561,12 @@ Status ServiceAttributeResponse::Parse(const common::ByteBuffer& buf) { auto* val = attribute_list.At(idx + 1); if ((it->type() != DataElement::Type::kUnsignedInt) || (val == nullptr)) { attributes_.clear(); - return Status(common::HostError::kPacketMalformed); + return Status(HostError::kPacketMalformed); } AttributeId id = *(it->Get<uint16_t>()); if (id < last_id) { attributes_.clear(); - return Status(common::HostError::kPacketMalformed); + return Status(HostError::kPacketMalformed); } attributes_.emplace(id, val->Clone()); last_id = id; @@ -584,9 +576,8 @@ Status ServiceAttributeResponse::Parse(const common::ByteBuffer& buf) { } // Continuation state: index of # of bytes into the attribute list element -common::MutableByteBufferPtr ServiceAttributeResponse::GetPDU( - uint16_t max, TransactionId tid, - const common::ByteBuffer& cont_state) const { +MutableByteBufferPtr ServiceAttributeResponse::GetPDU( + uint16_t max, TransactionId tid, const ByteBuffer& cont_state) const { if (!complete()) { return nullptr; } @@ -634,7 +625,7 @@ common::MutableByteBufferPtr ServiceAttributeResponse::GetPDU( buf->WriteObj(htobe16(attribute_list_byte_count), written); written += sizeof(uint16_t); - auto attribute_list_bytes = common::NewSlabBuffer(write_size); + auto attribute_list_bytes = NewSlabBuffer(write_size); list_elem.Write(attribute_list_bytes.get()); buf->Write( attribute_list_bytes->view(bytes_skipped, attribute_list_byte_count), @@ -657,7 +648,7 @@ ServiceSearchAttributeRequest::ServiceSearchAttributeRequest() : Request(), max_attribute_byte_count_(0xFFFF) {} ServiceSearchAttributeRequest::ServiceSearchAttributeRequest( - const common::ByteBuffer& params) { + const ByteBuffer& params) { DataElement search_pattern; size_t read_size = DataElement::Read(&search_pattern, params); if ((read_size == 0) || @@ -685,7 +676,7 @@ ServiceSearchAttributeRequest::ServiceSearchAttributeRequest( service_search_pattern_.clear(); return; } - service_search_pattern_.emplace(*(it->Get<common::UUID>())); + service_search_pattern_.emplace(*(it->Get<UUID>())); } if (count == 0) { bt_log(SPEW, "sdp", "no elements in search pattern"); @@ -730,8 +721,7 @@ bool ServiceSearchAttributeRequest::valid() const { (attribute_ranges_.size() > 0); } -common::ByteBufferPtr ServiceSearchAttributeRequest::GetPDU( - TransactionId tid) const { +ByteBufferPtr ServiceSearchAttributeRequest::GetPDU(TransactionId tid) const { if (!valid()) { return nullptr; } @@ -758,7 +748,7 @@ common::ByteBufferPtr ServiceSearchAttributeRequest::GetPDU( std::vector<DataElement> pattern(service_search_pattern_.size()); size_t i = 0; for (const auto& it : service_search_pattern_) { - pattern.at(i).Set<common::UUID>(it); + pattern.at(i).Set<UUID>(it); i++; } DataElement search_pattern(std::move(pattern)); @@ -796,10 +786,9 @@ void ServiceSearchAttributeRequest::AddAttributeRange(AttributeId start, ServiceSearchAttributeResponse::ServiceSearchAttributeResponse() {} -const common::BufferView ServiceSearchAttributeResponse::ContinuationState() - const { +const BufferView ServiceSearchAttributeResponse::ContinuationState() const { if (!continuation_state_) { - return common::BufferView(); + return BufferView(); } return continuation_state_->view(); } @@ -808,12 +797,12 @@ bool ServiceSearchAttributeResponse::complete() const { return !continuation_state_; } -Status ServiceSearchAttributeResponse::Parse(const common::ByteBuffer& buf) { +Status ServiceSearchAttributeResponse::Parse(const ByteBuffer& buf) { if (complete() && attribute_lists_.size() != 0) { // This response was previously complete and non-empty bt_log(SPEW, "sdp", "can't parse into a complete response"); ZX_DEBUG_ASSERT(!partial_response_); - return Status(common::HostError::kNotReady); + return Status(HostError::kNotReady); } // Minimum size is an AttributeListsByteCount, an empty AttributeLists @@ -821,7 +810,7 @@ Status ServiceSearchAttributeResponse::Parse(const common::ByteBuffer& buf) { // of AttributeLists if (buf.size() < sizeof(uint16_t) + 3) { bt_log(SPEW, "sdp", "packet too small to parse"); - return Status(common::HostError::kPacketMalformed); + return Status(HostError::kPacketMalformed); } uint16_t attribute_lists_byte_count = betoh16(buf.As<uint16_t>()); @@ -829,20 +818,20 @@ Status ServiceSearchAttributeResponse::Parse(const common::ByteBuffer& buf) { if (buf.view(read_size).size() < attribute_lists_byte_count + sizeof(uint8_t)) { bt_log(SPEW, "sdp", "not enough bytes in rest of packet as indicated"); - return Status(common::HostError::kPacketMalformed); + return Status(HostError::kPacketMalformed); } // Check to see if there's continuation. - common::BufferView cont_state_view; + BufferView cont_state_view; if (!ValidContinuationState(buf.view(read_size + attribute_lists_byte_count), &cont_state_view)) { bt_log(SPEW, "sdp", "continutation state is not valid"); - return Status(common::HostError::kPacketMalformed); + return Status(HostError::kPacketMalformed); } if (cont_state_view.size() == 0) { continuation_state_ = nullptr; } else { - continuation_state_ = common::NewSlabBuffer(cont_state_view.size()); + continuation_state_ = NewSlabBuffer(cont_state_view.size()); continuation_state_->Write(cont_state_view); } @@ -853,7 +842,7 @@ Status ServiceSearchAttributeResponse::Parse(const common::ByteBuffer& buf) { if (partial_response_) { new_partial_size += partial_response_->size(); } - auto new_partial = common::NewSlabBuffer(new_partial_size); + auto new_partial = NewSlabBuffer(new_partial_size); if (partial_response_) { new_partial->Write(partial_response_->view()); new_partial->Write(attribute_lists_bytes, partial_response_->size()); @@ -864,7 +853,7 @@ Status ServiceSearchAttributeResponse::Parse(const common::ByteBuffer& buf) { if (continuation_state_) { // This is incomplete, we can't parse it yet. bt_log(SPEW, "sdp", "continutation state found, returning in progress"); - return Status(common::HostError::kInProgress); + return Status(HostError::kInProgress); } attribute_lists_bytes = partial_response_->view(); } @@ -874,7 +863,7 @@ Status ServiceSearchAttributeResponse::Parse(const common::ByteBuffer& buf) { if ((elem_size == 0) || (attribute_lists.type() != DataElement::Type::kSequence)) { bt_log(SPEW, "sdp", "couldn't parse attribute lists or wasn't a sequence"); - return Status(common::HostError::kPacketMalformed); + return Status(HostError::kPacketMalformed); } bt_log(SPEW, "sdp", "parsed AttributeLists: %s", attribute_lists.ToString().c_str()); @@ -887,7 +876,7 @@ Status ServiceSearchAttributeResponse::Parse(const common::ByteBuffer& buf) { list_it = attribute_lists.At(++list_idx)) { if ((list_it->type() != DataElement::Type::kSequence)) { bt_log(SPEW, "sdp", "list %zu wasn't a sequence", list_idx); - return Status(common::HostError::kPacketMalformed); + return Status(HostError::kPacketMalformed); } attribute_lists_.emplace(list_idx, std::map<AttributeId, DataElement>()); AttributeId last_id = 0; @@ -897,7 +886,7 @@ Status ServiceSearchAttributeResponse::Parse(const common::ByteBuffer& buf) { if ((it->type() != DataElement::Type::kUnsignedInt) || (val == nullptr)) { attribute_lists_.clear(); bt_log(SPEW, "sdp", "attribute isn't a ptr or doesn't exist"); - return Status(common::HostError::kPacketMalformed); + return Status(HostError::kPacketMalformed); } bt_log(SPEW, "sdp", "adding %zu:%s = %s", list_idx, bt_str(*it), bt_str(*val)); @@ -905,7 +894,7 @@ Status ServiceSearchAttributeResponse::Parse(const common::ByteBuffer& buf) { if (id < last_id) { attribute_lists_.clear(); bt_log(SPEW, "sdp", "attribute ids are in wrong order"); - return Status(common::HostError::kPacketMalformed); + return Status(HostError::kPacketMalformed); } attribute_lists_.at(list_idx).emplace(id, val->Clone()); last_id = id; @@ -925,9 +914,8 @@ void ServiceSearchAttributeResponse::SetAttribute(uint32_t idx, AttributeId id, } // Continuation state: index of # of bytes into the attribute list element -common::MutableByteBufferPtr ServiceSearchAttributeResponse::GetPDU( - uint16_t max, TransactionId tid, - const common::ByteBuffer& cont_state) const { +MutableByteBufferPtr ServiceSearchAttributeResponse::GetPDU( + uint16_t max, TransactionId tid, const ByteBuffer& cont_state) const { if (!complete()) { return nullptr; } @@ -983,7 +971,7 @@ common::MutableByteBufferPtr ServiceSearchAttributeResponse::GetPDU( buf->WriteObj(htobe16(attribute_lists_byte_count), written); written += sizeof(uint16_t); - auto attribute_list_bytes = common::NewSlabBuffer(write_size); + auto attribute_list_bytes = NewSlabBuffer(write_size); list_elem.Write(attribute_list_bytes.get()); buf->Write( attribute_list_bytes->view(bytes_skipped, attribute_lists_byte_count), diff --git a/src/connectivity/bluetooth/core/bt-host/sdp/pdu.h b/src/connectivity/bluetooth/core/bt-host/sdp/pdu.h index 145020804fe13f0b26f48f88c8a047208ae99a23..0afc374452091b0548f0cc51836d8fbd2c81ac9f 100644 --- a/src/connectivity/bluetooth/core/bt-host/sdp/pdu.h +++ b/src/connectivity/bluetooth/core/bt-host/sdp/pdu.h @@ -30,32 +30,32 @@ class Request { // Gets a buffer containing the PDU representation of this request. // Returns nullptr if the request is not valid. - virtual common::ByteBufferPtr GetPDU(TransactionId tid) const = 0; + virtual ByteBufferPtr GetPDU(TransactionId tid) const = 0; // Returns a view with the current continuation state. // In a response packet with more than one packet, this contains the most // recent continuaton state (so it can be read to request a continuation). - const common::BufferView ContinuationState() const { + const BufferView ContinuationState() const { return cont_state_.view(1, cont_info_size()); } // Sets the continuation state for this request. - void SetContinuationState(const common::ByteBuffer& buf); + void SetContinuationState(const ByteBuffer& buf); protected: // Parses the continuation state portion of a packet, which is in |buf|. // Returns true if the parsing succeeded. - bool ParseContinuationState(const common::ByteBuffer& buf); + bool ParseContinuationState(const ByteBuffer& buf); // Writes the continuation state to |buf|, which must have at least // cont_info_size() + 1 bytes avaiable. - size_t WriteContinuationState(common::MutableByteBuffer* buf) const; + size_t WriteContinuationState(MutableByteBuffer* buf) const; uint8_t cont_info_size() const { return cont_state_.data()[0]; } private: // Continuation information, including the length. - common::StaticByteBuffer<kMaxContStateLength> cont_state_; + StaticByteBuffer<kMaxContStateLength> cont_state_; }; // SDP Response objects are used in two places: @@ -70,7 +70,7 @@ class Response { // Returns the continuation state from a partial response, used to // make an additional request. Returns an empty view if this packet // is complete. - virtual const common::BufferView ContinuationState() const = 0; + virtual const BufferView ContinuationState() const = 0; // Parses parameters from a PDU response, storing a partial result if // necessary. @@ -79,7 +79,7 @@ class Response { // - kNotReady if this response is already complete. // - kPacketMalformed: if the parameters couldn't be parsed. // - kOutOfMemory: if memory isn't available to store a partial response. - virtual Status Parse(const common::ByteBuffer& buf) = 0; + virtual Status Parse(const ByteBuffer& buf) = 0; // Returns a buffer containing the PDU representation of this response, // including the header. @@ -93,9 +93,8 @@ class Response { // last valid packet representing a response. // If that continuation state is passed to this function with the same // |max_size| argument it will produce the next parameters of response. - virtual common::MutableByteBufferPtr GetPDU( - uint16_t max, TransactionId tid, - const common::ByteBuffer& cont_state) const = 0; + virtual MutableByteBufferPtr GetPDU(uint16_t max, TransactionId tid, + const ByteBuffer& cont_state) const = 0; }; // Error Response PDU, generated when the SDP server can't respond to a PDU @@ -107,18 +106,17 @@ class ErrorResponse : public Response { // Response overrides. bool complete() const override { return error_code_ != ErrorCode::kReserved; } - const common::BufferView ContinuationState() const override { + const BufferView ContinuationState() const override { // ErrorResponses never have continuation state. - return common::BufferView(); + return BufferView(); } - Status Parse(const common::ByteBuffer& buf) override; + Status Parse(const ByteBuffer& buf) override; // Note: |max_size| and |cont_state| are ignored. // Error Responses do not have a valid continuation. - common::MutableByteBufferPtr GetPDU( - uint16_t max, TransactionId tid, - const common::ByteBuffer& cont_state) const override; + MutableByteBufferPtr GetPDU(uint16_t max, TransactionId tid, + const ByteBuffer& cont_state) const override; ErrorCode error_code() const { return error_code_; } void set_error_code(ErrorCode code) { error_code_ = code; } @@ -135,21 +133,21 @@ class ServiceSearchRequest : public Request { // Create an empty search request. ServiceSearchRequest(); // Parse the parameters given in |params| to initialize this request. - explicit ServiceSearchRequest(const common::ByteBuffer& params); + explicit ServiceSearchRequest(const ByteBuffer& params); // Request overrides bool valid() const override; - common::ByteBufferPtr GetPDU(TransactionId tid) const override; + ByteBufferPtr GetPDU(TransactionId tid) const override; // A service search pattern matches if every UUID in the pattern is contained // within one of the services' attribute values. They don't need to be in any // specific attribute or in any particular order, and extraneous UUIDs are // allowed to exist in the attribute value. // See v5.0, Volume 3, Part B, Sec 2.5.2 - void set_search_pattern(std::unordered_set<common::UUID> pattern) { + void set_search_pattern(std::unordered_set<UUID> pattern) { service_search_pattern_ = pattern; } - const std::unordered_set<common::UUID>& service_search_pattern() const { + const std::unordered_set<UUID>& service_search_pattern() const { return service_search_pattern_; } @@ -163,7 +161,7 @@ class ServiceSearchRequest : public Request { } private: - std::unordered_set<common::UUID> service_search_pattern_; + std::unordered_set<UUID> service_search_pattern_; uint16_t max_service_record_count_; }; @@ -175,11 +173,10 @@ class ServiceSearchResponse : public Response { // Response overrides bool complete() const override; - const common::BufferView ContinuationState() const override; - Status Parse(const common::ByteBuffer& buf) override; - common::MutableByteBufferPtr GetPDU( - uint16_t max, TransactionId tid, - const common::ByteBuffer& cont_state) const override; + const BufferView ContinuationState() const override; + Status Parse(const ByteBuffer& buf) override; + MutableByteBufferPtr GetPDU(uint16_t max, TransactionId tid, + const ByteBuffer& cont_state) const override; // The ServiceRecordHandleList contains as list of service record handles. // This should be set to the list of handles that match the request. @@ -199,7 +196,7 @@ class ServiceSearchResponse : public Response { // The total number of service records in the full response. uint16_t total_service_record_count_; - common::ByteBufferPtr continuation_state_; + ByteBufferPtr continuation_state_; }; // Represents a range of attributes, inclusive of |start| and |end|. @@ -220,11 +217,11 @@ class ServiceAttributeRequest : public Request { ServiceAttributeRequest(); // Parse the parameters in |params| to initialize this request. // valid() will be false if |params| don't represent valid a valid request. - explicit ServiceAttributeRequest(const common::ByteBuffer& params); + explicit ServiceAttributeRequest(const ByteBuffer& params); // Request overrides bool valid() const override; - common::ByteBufferPtr GetPDU(TransactionId tid) const override; + ByteBufferPtr GetPDU(TransactionId tid) const override; void set_service_record_handle(ServiceHandle handle) { service_record_handle_ = handle; @@ -279,12 +276,11 @@ class ServiceAttributeResponse : public Response { ServiceAttributeResponse(); // Response overrides - const common::BufferView ContinuationState() const override; + const BufferView ContinuationState() const override; bool complete() const override; - Status Parse(const common::ByteBuffer& buf) override; - common::MutableByteBufferPtr GetPDU( - uint16_t max, TransactionId tid, - const common::ByteBuffer& cont_state) const override; + Status Parse(const ByteBuffer& buf) override; + MutableByteBufferPtr GetPDU(uint16_t max, TransactionId tid, + const ByteBuffer& cont_state) const override; void set_attribute(AttributeId id, DataElement value) { attributes_.emplace(id, std::move(value)); @@ -305,9 +301,9 @@ class ServiceAttributeResponse : public Response { // // This contains the partial attribute list response if there is continuation // state. - common::MutableByteBufferPtr partial_response_; + MutableByteBufferPtr partial_response_; - common::MutableByteBufferPtr continuation_state_; + MutableByteBufferPtr continuation_state_; }; // Combines the capabilities of ServiceSearchRequest and ServiceAttributeRequest @@ -319,21 +315,21 @@ class ServiceSearchAttributeRequest : public Request { // Create an empty service search attribute request. ServiceSearchAttributeRequest(); // Parse the parameters in |params| to initialize this request. - explicit ServiceSearchAttributeRequest(const common::ByteBuffer& params); + explicit ServiceSearchAttributeRequest(const ByteBuffer& params); // Request overrides bool valid() const override; - common::ByteBufferPtr GetPDU(TransactionId tid) const override; + ByteBufferPtr GetPDU(TransactionId tid) const override; // A service search pattern matches if every UUID in the pattern is contained // within one of the services' attribute values. They don't need to be in any // specific attribute or in any particular order, and extraneous UUIDs are // allowed to exist in the attribute value. // See v5.0, Volume 3, Part B, Sec 2.5.2. - void set_search_pattern(std::unordered_set<common::UUID> pattern) { + void set_search_pattern(std::unordered_set<UUID> pattern) { service_search_pattern_ = pattern; } - const std::unordered_set<common::UUID>& service_search_pattern() const { + const std::unordered_set<UUID>& service_search_pattern() const { return service_search_pattern_; } @@ -359,7 +355,7 @@ class ServiceSearchAttributeRequest : public Request { private: // The service search pattern to match services. - std::unordered_set<common::UUID> service_search_pattern_; + std::unordered_set<UUID> service_search_pattern_; // Maximum number of bytes of attribute data to be returned in the response. // If the attributes don't fit, the server decides how to segment them. @@ -379,12 +375,11 @@ class ServiceSearchAttributeResponse : public Response { ServiceSearchAttributeResponse(); // Response overrides - const common::BufferView ContinuationState() const override; + const BufferView ContinuationState() const override; bool complete() const override; - Status Parse(const common::ByteBuffer& buf) override; - common::MutableByteBufferPtr GetPDU( - uint16_t max, TransactionId tid, - const common::ByteBuffer& cont_state) const override; + Status Parse(const ByteBuffer& buf) override; + MutableByteBufferPtr GetPDU(uint16_t max, TransactionId tid, + const ByteBuffer& cont_state) const override; // Set an attribute to be included in the response. // |idx| is used to group attributes and does not need to be contiguous for @@ -414,9 +409,9 @@ class ServiceSearchAttributeResponse : public Response { // // This contains the partial attribute list response if there is continuation // state. - common::MutableByteBufferPtr partial_response_; + MutableByteBufferPtr partial_response_; - common::MutableByteBufferPtr continuation_state_; + MutableByteBufferPtr continuation_state_; }; } // namespace sdp diff --git a/src/connectivity/bluetooth/core/bt-host/sdp/pdu_unittest.cc b/src/connectivity/bluetooth/core/bt-host/sdp/pdu_unittest.cc index c0c1078bb371c9366ef709e62d68620173e1da01..049eebbd864c8c319364b52d5cdda6d67b5326e2 100644 --- a/src/connectivity/bluetooth/core/bt-host/sdp/pdu_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/sdp/pdu_unittest.cc @@ -4,28 +4,24 @@ // found in the LICENSE file. #include "src/connectivity/bluetooth/core/bt-host/sdp/pdu.h" -#include "src/connectivity/bluetooth/core/bt-host/sdp/sdp.h" -#include "src/connectivity/bluetooth/core/bt-host/sdp/status.h" #include "gtest/gtest.h" - #include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" +#include "src/connectivity/bluetooth/core/bt-host/sdp/sdp.h" +#include "src/connectivity/bluetooth/core/bt-host/sdp/status.h" namespace bt { namespace sdp { namespace { -using common::LowerBits; -using common::UpperBits; - using SDP_PDUTest = ::testing::Test; TEST_F(SDP_PDUTest, ErrorResponse) { ErrorResponse response; EXPECT_FALSE(response.complete()); - auto kInvalidContState = common::CreateStaticByteBuffer( + auto kInvalidContState = CreateStaticByteBuffer( 0x01, // opcode: kErrorResponse 0xDE, 0xAD, // transaction ID: 0xDEAD 0x00, 0x02, // parameter length: 2 bytes @@ -35,7 +31,7 @@ TEST_F(SDP_PDUTest, ErrorResponse) { Status status = response.Parse(kInvalidContState.view(sizeof(Header))); EXPECT_FALSE(status); - EXPECT_EQ(common::HostError::kPacketMalformed, status.error()); + EXPECT_EQ(HostError::kPacketMalformed, status.error()); status = response.Parse(kInvalidContState.view(sizeof(Header), 2)); EXPECT_TRUE(status); @@ -43,14 +39,13 @@ TEST_F(SDP_PDUTest, ErrorResponse) { EXPECT_EQ(ErrorCode::kInvalidContinuationState, response.error_code()); response.set_error_code(ErrorCode::kInvalidContinuationState); - auto ptr = - response.GetPDU(0xF00F /* ignored */, 0xDEAD, common::BufferView()); + auto ptr = response.GetPDU(0xF00F /* ignored */, 0xDEAD, BufferView()); EXPECT_TRUE(ContainersEqual(kInvalidContState.view(0, 7), *ptr)); } TEST_F(SDP_PDUTest, ServiceSearchRequestParse) { - const auto kL2capSearch = common::CreateStaticByteBuffer( + const auto kL2capSearch = CreateStaticByteBuffer( // ServiceSearchPattern 0x35, 0x03, // Sequence uint8 3 bytes 0x19, 0x01, 0x00, // UUID: Protocol: L2CAP @@ -64,7 +59,7 @@ TEST_F(SDP_PDUTest, ServiceSearchRequestParse) { EXPECT_TRUE(req.service_search_pattern().count(protocol::kL2CAP)); EXPECT_EQ(16, req.max_service_record_count()); - const auto kL2capSearchOne = common::CreateStaticByteBuffer( + const auto kL2capSearchOne = CreateStaticByteBuffer( // ServiceSearchPattern 0x35, 0x06, // Sequence uint8 6 bytes 0x19, 0x01, 0x00, // UUID: Protocol: L2CAP @@ -78,7 +73,7 @@ TEST_F(SDP_PDUTest, ServiceSearchRequestParse) { EXPECT_EQ(2u, req_one.service_search_pattern().size()); EXPECT_EQ(1, req_one.max_service_record_count()); - const auto kInvalidNoItems = common::CreateStaticByteBuffer( + const auto kInvalidNoItems = CreateStaticByteBuffer( // ServiceSearchPattern 0x35, 0x00, // Sequence uint8 0 bytes 0xFF, 0xFF, // MaximumServiceRecordCount: (none) @@ -88,7 +83,7 @@ TEST_F(SDP_PDUTest, ServiceSearchRequestParse) { ServiceSearchRequest req2(kInvalidNoItems); EXPECT_FALSE(req2.valid()); - const auto kInvalidTooManyItems = common::CreateStaticByteBuffer( + const auto kInvalidTooManyItems = CreateStaticByteBuffer( // ServiceSearchPattern 0x35, 0x27, // Sequence uint8 27 bytes 0x19, 0x30, 0x01, // 13 UUIDs in the search @@ -110,7 +105,7 @@ TEST_F(SDP_PDUTest, ServiceSearchRequestGetPDU) { req.set_max_service_record_count(64); // Order is not specified, so there are two valid PDUs representing this. - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( kServiceSearchRequest, 0x12, 0x34, // Transaction ID 0x00, 0x0B, // Parameter length (11 bytes) // ServiceSearchPattern @@ -120,7 +115,7 @@ TEST_F(SDP_PDUTest, ServiceSearchRequestGetPDU) { 0x00, 0x40, // MaximumServiceRecordCount: 64 0x00 // No continuation state ); - const auto kExpected2 = common::CreateStaticByteBuffer( + const auto kExpected2 = CreateStaticByteBuffer( kServiceSearchRequest, 0x12, 0x34, // Transaction ID 0x00, 0x0B, // Parameter length (11 bytes) // ServiceSearchPattern @@ -137,13 +132,13 @@ TEST_F(SDP_PDUTest, ServiceSearchRequestGetPDU) { }; TEST_F(SDP_PDUTest, ServiceSearchResponseParse) { - const auto kValidResponse = common::CreateStaticByteBuffer( - 0x00, 0x02, // Total service record count: 2 - 0x00, 0x02, // Current service record count: 2 - 0x00, 0x00, 0x00, 0x01, // Service Handle 1 - 0x00, 0x00, 0x00, 0x02, // Service Handle 2 - 0x00 // No continuation state - ); + const auto kValidResponse = + CreateStaticByteBuffer(0x00, 0x02, // Total service record count: 2 + 0x00, 0x02, // Current service record count: 2 + 0x00, 0x00, 0x00, 0x01, // Service Handle 1 + 0x00, 0x00, 0x00, 0x02, // Service Handle 2 + 0x00 // No continuation state + ); ServiceSearchResponse resp; auto status = resp.Parse(kValidResponse); @@ -153,12 +148,12 @@ TEST_F(SDP_PDUTest, ServiceSearchResponseParse) { status = resp.Parse(kValidResponse); EXPECT_FALSE(status); - const auto kNotEnoughRecords = common::CreateStaticByteBuffer( - 0x00, 0x02, // Total service record count: 2 - 0x00, 0x02, // Current service record count: 2 - 0x00, 0x00, 0x00, 0x01, // Service Handle 1 - 0x00 // No continuation state - ); + const auto kNotEnoughRecords = + CreateStaticByteBuffer(0x00, 0x02, // Total service record count: 2 + 0x00, 0x02, // Current service record count: 2 + 0x00, 0x00, 0x00, 0x01, // Service Handle 1 + 0x00 // No continuation state + ); // Doesn't contain the right # of records. ServiceSearchResponse resp2; status = resp2.Parse(kNotEnoughRecords); @@ -170,31 +165,31 @@ TEST_F(SDP_PDUTest, ServiceSearchResponsePDU) { ServiceSearchResponse resp; resp.set_service_record_handle_list(results); - const auto kExpected = common::CreateStaticByteBuffer( - 0x03, // ServiceSearch Response PDU ID - 0x01, 0x10, // Transaction ID (0x0110) - 0x00, 0x0d, // Parameter length: 13 bytes - 0x00, 0x02, // Total service record count: 2 - 0x00, 0x02, // Current service record count: 2 - 0x00, 0x00, 0x00, 0x01, // Service record 1 - 0x00, 0x00, 0x00, 0x02, // Service record 2 - 0x00 // No continuation state - ); - - auto pdu = resp.GetPDU(0xFFFF, 0x0110, common::BufferView()); + const auto kExpected = + CreateStaticByteBuffer(0x03, // ServiceSearch Response PDU ID + 0x01, 0x10, // Transaction ID (0x0110) + 0x00, 0x0d, // Parameter length: 13 bytes + 0x00, 0x02, // Total service record count: 2 + 0x00, 0x02, // Current service record count: 2 + 0x00, 0x00, 0x00, 0x01, // Service record 1 + 0x00, 0x00, 0x00, 0x02, // Service record 2 + 0x00 // No continuation state + ); + + auto pdu = resp.GetPDU(0xFFFF, 0x0110, BufferView()); EXPECT_TRUE(ContainersEqual(kExpected, *pdu)); - const auto kExpectedLimited = common::CreateStaticByteBuffer( - 0x03, // ServiceSearchResponse PDU ID - 0x01, 0x10, // Transaction ID (0x0110) - 0x00, 0x09, // Parameter length: 9 - 0x00, 0x01, // Total service record count: 1 - 0x00, 0x01, // Current service record count: 1 - 0x00, 0x00, 0x00, 0x01, // Service record 1 - 0x00 // No continuation state - ); - - pdu = resp.GetPDU(1, 0x0110, common::BufferView()); + const auto kExpectedLimited = + CreateStaticByteBuffer(0x03, // ServiceSearchResponse PDU ID + 0x01, 0x10, // Transaction ID (0x0110) + 0x00, 0x09, // Parameter length: 9 + 0x00, 0x01, // Total service record count: 1 + 0x00, 0x01, // Current service record count: 1 + 0x00, 0x00, 0x00, 0x01, // Service record 1 + 0x00 // No continuation state + ); + + pdu = resp.GetPDU(1, 0x0110, BufferView()); EXPECT_TRUE(ContainersEqual(kExpectedLimited, *pdu)); }; @@ -295,7 +290,7 @@ TEST_F(SDP_PDUTest, ServiceAttriuteRequestAddRange) { } TEST_F(SDP_PDUTest, ServiceAttributeRequestParse) { - const auto kSDPAllAttributes = common::CreateStaticByteBuffer( + const auto kSDPAllAttributes = CreateStaticByteBuffer( 0x00, 0x00, 0x00, 0x00, // ServiceRecordHandle: 0 0xF0, 0x0F, // Maximum attribute byte count: (max = 61455) // Attribute ID List @@ -313,7 +308,7 @@ TEST_F(SDP_PDUTest, ServiceAttributeRequestParse) { EXPECT_EQ(0xFFFF, req.attribute_ranges().front().end); EXPECT_EQ(61455, req.max_attribute_byte_count()); - const auto kContinued = common::CreateStaticByteBuffer( + const auto kContinued = CreateStaticByteBuffer( 0x00, 0x00, 0x00, 0x00, // ServiceRecordHandle: 0 0x00, 0x0F, // Maximum attribute byte count: (max = 15) // Attribute ID List @@ -336,25 +331,25 @@ TEST_F(SDP_PDUTest, ServiceAttributeRequestParse) { EXPECT_EQ(15, req_cont_state.max_attribute_byte_count()); // Too short request. - ServiceAttributeRequest req_short((common::BufferView())); + ServiceAttributeRequest req_short((BufferView())); EXPECT_FALSE(req_short.valid()); - const auto kInvalidMaxBytes = common::CreateStaticByteBuffer( - 0x00, 0x00, 0x00, 0x00, // ServiceRecordHandle: 0 - 0x00, 0x04, // Maximum attribute byte count (4) - // Attribute ID List - 0x35, 0x03, // Sequence uint8 3 bytes - 0x09, 0x00, 0x02, // uint16_t (2) - 0x00 // No continuation state - ); + const auto kInvalidMaxBytes = + CreateStaticByteBuffer(0x00, 0x00, 0x00, 0x00, // ServiceRecordHandle: 0 + 0x00, 0x04, // Maximum attribute byte count (4) + // Attribute ID List + 0x35, 0x03, // Sequence uint8 3 bytes + 0x09, 0x00, 0x02, // uint16_t (2) + 0x00 // No continuation state + ); ServiceAttributeRequest req_minmax(kInvalidMaxBytes); EXPECT_FALSE(req_minmax.valid()); // Invalid order of the attributes. - const auto kInvalidAttributeListOrder = common::CreateStaticByteBuffer( + const auto kInvalidAttributeListOrder = CreateStaticByteBuffer( 0x00, 0x00, 0x00, 0x00, // ServiceRecordHandle: 0 0xFF, 0xFF, // Maximum attribute byte count: (max = 65535) // Attribute ID List @@ -369,7 +364,7 @@ TEST_F(SDP_PDUTest, ServiceAttributeRequestParse) { EXPECT_FALSE(req_short.valid()); // AttributeID List has invalid items - const auto kInvalidAttributeList = common::CreateStaticByteBuffer( + const auto kInvalidAttributeList = CreateStaticByteBuffer( 0x00, 0x00, 0x00, 0x00, // ServiceRecordHandle: 0 0xFF, 0xFF, // Maximum attribute byte count: (max = 65535) // Attribute ID List @@ -392,7 +387,7 @@ TEST_F(SDP_PDUTest, ServiceAttributeRequestGetPDU) { req.set_service_record_handle(0xEFFECACE); req.set_max_attribute_byte_count(32); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( kServiceAttributeRequest, 0x12, 0x34, // transaction id 0x00, 0x11, // Parameter Length (17 bytes) 0xEF, 0xFE, 0xCA, 0xCE, // ServiceRecordHandle (0xEFFECACE) @@ -409,19 +404,19 @@ TEST_F(SDP_PDUTest, ServiceAttributeRequestGetPDU) { } TEST_F(SDP_PDUTest, ServiceAttributeResponseParse) { - const auto kValidResponseEmpty = common::CreateStaticByteBuffer( - 0x00, 0x02, // AttributeListByteCount (2 bytes) - // Attribute List - 0x35, 0x00, // Sequence uint8 0 bytes - 0x00 // No continuation state - ); + const auto kValidResponseEmpty = + CreateStaticByteBuffer(0x00, 0x02, // AttributeListByteCount (2 bytes) + // Attribute List + 0x35, 0x00, // Sequence uint8 0 bytes + 0x00 // No continuation state + ); ServiceAttributeResponse resp; auto status = resp.Parse(kValidResponseEmpty); EXPECT_TRUE(status); - const auto kValidResponseItems = common::CreateStaticByteBuffer( + const auto kValidResponseItems = CreateStaticByteBuffer( 0x00, 0x12, // AttributeListByteCount (18 bytes) // Attribute List 0x35, 0x10, // Sequence uint8 16 bytes @@ -444,7 +439,7 @@ TEST_F(SDP_PDUTest, ServiceAttributeResponseParse) { EXPECT_NE(resp.attributes().end(), it); EXPECT_EQ(DataElement::Type::kSequence, it->second.type()); - const auto kInvalidItemsWrongOrder = common::CreateStaticByteBuffer( + const auto kInvalidItemsWrongOrder = CreateStaticByteBuffer( 0x00, 0x12, // AttributeListByteCount (18 bytes) // Attribute List 0x35, 0x10, // Sequence uint8 16 bytes @@ -459,7 +454,7 @@ TEST_F(SDP_PDUTest, ServiceAttributeResponseParse) { EXPECT_FALSE(status); - const auto kInvalidByteCount = common::CreateStaticByteBuffer( + const auto kInvalidByteCount = CreateStaticByteBuffer( 0x00, 0x12, // AttributeListByteCount (18 bytes) // Attribute List 0x35, 0x0F, // Sequence uint8 15 bytes @@ -476,7 +471,7 @@ TEST_F(SDP_PDUTest, ServiceAttributeResponseParse) { } TEST_F(SDP_PDUTest, ServiceSearchAttributeRequestParse) { - const auto kSDPL2CAPAllAttributes = common::CreateStaticByteBuffer( + const auto kSDPL2CAPAllAttributes = CreateStaticByteBuffer( // Service search pattern 0x35, 0x03, // Sequence uint8 3 bytes 0x19, 0x01, 0x00, // UUID: Protocol: L2CAP @@ -498,7 +493,7 @@ TEST_F(SDP_PDUTest, ServiceSearchAttributeRequestParse) { EXPECT_EQ(0xFFFF, req.attribute_ranges().front().end); EXPECT_EQ(61455, req.max_attribute_byte_count()); - const auto kContinued = common::CreateStaticByteBuffer( + const auto kContinued = CreateStaticByteBuffer( 0x35, 0x03, // Sequence uint8 3 bytes 0x19, 0x01, 0x00, // UUID: Protocol: L2CAP 0x00, 0x0F, // Maximum attribute byte count: (max = 15) @@ -524,26 +519,26 @@ TEST_F(SDP_PDUTest, ServiceSearchAttributeRequestParse) { EXPECT_EQ(15, req_cont_state.max_attribute_byte_count()); // Too short request. - ServiceSearchAttributeRequest req_short((common::BufferView())); + ServiceSearchAttributeRequest req_short((BufferView())); EXPECT_FALSE(req_short.valid()); - const auto kInvalidMaxBytes = common::CreateStaticByteBuffer( - 0x35, 0x03, // Sequence uint8 3 bytes - 0x19, 0x01, 0x00, // UUID: Protocol: L2CAP - 0x00, 0x04, // Maximum attribute byte count (4) - // Attribute ID List - 0x35, 0x03, // Sequence uint8 3 bytes - 0x09, 0x00, 0x02, // uint16_t (2) - 0x00 // No continuation state - ); + const auto kInvalidMaxBytes = + CreateStaticByteBuffer(0x35, 0x03, // Sequence uint8 3 bytes + 0x19, 0x01, 0x00, // UUID: Protocol: L2CAP + 0x00, 0x04, // Maximum attribute byte count (4) + // Attribute ID List + 0x35, 0x03, // Sequence uint8 3 bytes + 0x09, 0x00, 0x02, // uint16_t (2) + 0x00 // No continuation state + ); ServiceSearchAttributeRequest req_minmax(kInvalidMaxBytes); EXPECT_FALSE(req_minmax.valid()); // Invalid order of the attributes. - const auto kInvalidAttributeListOrder = common::CreateStaticByteBuffer( + const auto kInvalidAttributeListOrder = CreateStaticByteBuffer( 0x35, 0x03, // Sequence uint8 3 bytes 0x19, 0x01, 0x00, // UUID: Protocol: L2CAP 0xFF, 0xFF, // Maximum attribute byte count: (max = 65535) @@ -559,7 +554,7 @@ TEST_F(SDP_PDUTest, ServiceSearchAttributeRequestParse) { EXPECT_FALSE(req_short.valid()); // AttributeID List has invalid items - const auto kInvalidAttributeList = common::CreateStaticByteBuffer( + const auto kInvalidAttributeList = CreateStaticByteBuffer( 0x35, 0x03, // Sequence uint8 3 bytes 0x19, 0x01, 0x00, // UUID: Protocol: L2CAP 0xFF, 0xFF, // Maximum attribute byte count: (max = 65535) @@ -574,7 +569,7 @@ TEST_F(SDP_PDUTest, ServiceSearchAttributeRequestParse) { EXPECT_FALSE(req_baditems.valid()); - const auto kInvalidNoItems = common::CreateStaticByteBuffer( + const auto kInvalidNoItems = CreateStaticByteBuffer( 0x35, 0x00, // Sequence uint8 0 bytes 0xF0, 0x0F, // Maximum attribute byte count (61455) // Attribute ID List @@ -586,7 +581,7 @@ TEST_F(SDP_PDUTest, ServiceSearchAttributeRequestParse) { ServiceSearchAttributeRequest req_noitems(kInvalidNoItems); EXPECT_FALSE(req_noitems.valid()); - const auto kInvalidTooManyItems = common::CreateStaticByteBuffer( + const auto kInvalidTooManyItems = CreateStaticByteBuffer( // ServiceSearchPattern 0x35, 0x27, // Sequence uint8 27 bytes 0x19, 0x30, 0x01, // 13 UUIDs in the search @@ -611,7 +606,7 @@ TEST_F(SDP_PDUTest, ServiceSearchAttributeRequestGetPDU) { req.set_search_pattern({protocol::kATT, protocol::kL2CAP}); req.set_max_attribute_byte_count(32); - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( kServiceSearchAttributeRequest, 0x12, 0x34, // transaction id 0x00, 0x15, // Parameter Length (21 bytes) // ServiceSearchPattern @@ -626,7 +621,7 @@ TEST_F(SDP_PDUTest, ServiceSearchAttributeRequestGetPDU) { 0x00 // No continuation state ); - const auto kExpected2 = common::CreateStaticByteBuffer( + const auto kExpected2 = CreateStaticByteBuffer( kServiceSearchAttributeRequest, 0x12, 0x34, // transaction id 0x00, 0x15, // Parameter Length (21 bytes) // ServiceSearchPattern @@ -647,12 +642,12 @@ TEST_F(SDP_PDUTest, ServiceSearchAttributeRequestGetPDU) { } TEST_F(SDP_PDUTest, ServiceSearchAttributeResponseParse) { - const auto kValidResponseEmpty = common::CreateStaticByteBuffer( - 0x00, 0x02, // AttributeListsByteCount (2 bytes) - // Attribute List - 0x35, 0x00, // Sequence uint8 0 bytes - 0x00 // No continuation state - ); + const auto kValidResponseEmpty = + CreateStaticByteBuffer(0x00, 0x02, // AttributeListsByteCount (2 bytes) + // Attribute List + 0x35, 0x00, // Sequence uint8 0 bytes + 0x00 // No continuation state + ); ServiceSearchAttributeResponse resp; auto status = resp.Parse(kValidResponseEmpty); @@ -661,7 +656,7 @@ TEST_F(SDP_PDUTest, ServiceSearchAttributeResponseParse) { EXPECT_TRUE(resp.complete()); EXPECT_EQ(0u, resp.num_attribute_lists()); - const auto kValidResponseItems = common::CreateStaticByteBuffer( + const auto kValidResponseItems = CreateStaticByteBuffer( 0x00, 0x14, // AttributeListsByteCount (20 bytes) // Wrapping Attribute List 0x35, 0x12, // Sequence uint8 18 bytes @@ -688,7 +683,7 @@ TEST_F(SDP_PDUTest, ServiceSearchAttributeResponseParse) { EXPECT_NE(resp.attributes(0).end(), it); EXPECT_EQ(DataElement::Type::kSequence, it->second.type()); - const auto kValidResponseTwoLists = common::CreateStaticByteBuffer( + const auto kValidResponseTwoLists = CreateStaticByteBuffer( 0x00, 0x1E, // AttributeListsByteCount (30 bytes) // Wrapping Attribute List 0x35, 0x1C, // Sequence uint8 28 bytes @@ -722,7 +717,7 @@ TEST_F(SDP_PDUTest, ServiceSearchAttributeResponseParse) { EXPECT_NE(resp2.attributes(1).end(), it); EXPECT_EQ(DataElement::Type::kUnsignedInt, it->second.type()); - const auto kInvalidItemsWrongOrder = common::CreateStaticByteBuffer( + const auto kInvalidItemsWrongOrder = CreateStaticByteBuffer( 0x00, 0x14, // AttributeListByteCount (20 bytes) // Wrapping Attribute List 0x35, 0x12, // Sequence uint8 18 bytes @@ -740,7 +735,7 @@ TEST_F(SDP_PDUTest, ServiceSearchAttributeResponseParse) { EXPECT_FALSE(status); - const auto kInvalidByteCount = common::CreateStaticByteBuffer( + const auto kInvalidByteCount = CreateStaticByteBuffer( 0x00, 0x12, // AttributeListsByteCount (18 bytes) 0x35, 0x11, // Sequence uint8 17 bytes // Attribute List @@ -770,7 +765,7 @@ TEST_F(SDP_PDUTest, ServiceSearchAttributeRepsonseGetPDU) { const uint16_t kTransactionID = 0xfeed; - const auto kExpected = common::CreateStaticByteBuffer( + const auto kExpected = CreateStaticByteBuffer( 0x07, // ServiceSearchAttributeResponse UpperBits(kTransactionID), LowerBits(kTransactionID), // Transaction ID 0x00, 0x25, // Param Length (37 bytes) @@ -790,8 +785,7 @@ TEST_F(SDP_PDUTest, ServiceSearchAttributeRepsonseGetPDU) { 0x00 // Continutation state (none) ); - auto pdu = - resp.GetPDU(0xFFFF /* no max */, kTransactionID, common::BufferView()); + auto pdu = resp.GetPDU(0xFFFF /* no max */, kTransactionID, BufferView()); EXPECT_TRUE(ContainersEqual(kExpected, *pdu)); } @@ -799,21 +793,20 @@ TEST_F(SDP_PDUTest, ServiceSearchAttributeRepsonseGetPDU) { TEST_F(SDP_PDUTest, ResponseOutOfRangeContinuation) { ServiceSearchResponse rsp_search; rsp_search.set_service_record_handle_list({1, 2, 3, 4}); - auto buf = rsp_search.GetPDU(0xFFFF, 0x0110, common::BufferView()); + auto buf = rsp_search.GetPDU(0xFFFF, 0x0110, BufferView()); EXPECT_TRUE(buf); // Any contnuation state is out of range for ServiceSearch - buf = rsp_search.GetPDU(0xFFFF, 0x0110, - common::CreateStaticByteBuffer(0x01, 0xFF)); + buf = rsp_search.GetPDU(0xFFFF, 0x0110, CreateStaticByteBuffer(0x01, 0xFF)); EXPECT_FALSE(buf); ServiceAttributeResponse rsp_attr; rsp_attr.set_attribute(1, DataElement(uint32_t(45))); - buf = rsp_attr.GetPDU(0xFFFF, 0x0110, common::BufferView()); + buf = rsp_attr.GetPDU(0xFFFF, 0x0110, BufferView()); EXPECT_TRUE(buf); uint32_t rsp_size = htobe32(buf->size() + 5); - auto too_large_cont = common::DynamicByteBuffer(sizeof(uint32_t)); + auto too_large_cont = DynamicByteBuffer(sizeof(uint32_t)); too_large_cont.WriteObj(rsp_size, 0); buf = rsp_attr.GetPDU(0xFFFF, 0x0110, too_large_cont); @@ -828,7 +821,7 @@ TEST_F(SDP_PDUTest, ResponseOutOfRangeContinuation) { rsp_search_attr.SetAttribute(5, kServiceRecordHandle, DataElement(uint32_t(0x10002000))); - buf = rsp_search_attr.GetPDU(0xFFFF, 0x0110, common::BufferView()); + buf = rsp_search_attr.GetPDU(0xFFFF, 0x0110, BufferView()); EXPECT_TRUE(buf); diff --git a/src/connectivity/bluetooth/core/bt-host/sdp/sdp.h b/src/connectivity/bluetooth/core/bt-host/sdp/sdp.h index 46b24ed08921f227160257d33cef216ae626dcd8..416e779651bc57f4502f381ddc7ab7f5cad67611 100644 --- a/src/connectivity/bluetooth/core/bt-host/sdp/sdp.h +++ b/src/connectivity/bluetooth/core/bt-host/sdp/sdp.h @@ -91,15 +91,15 @@ constexpr OpCode kServiceSearchAttributeResponse = 0x07; namespace protocol { -constexpr common::UUID kSDP(uint16_t(0x0001)); -constexpr common::UUID kRFCOMM(uint16_t(0x0003)); -constexpr common::UUID kATT(uint16_t(0x0007)); -constexpr common::UUID kOBEX(uint16_t(0x0008)); // IrDA Interop -constexpr common::UUID kBNEP(uint16_t(0x000F)); -constexpr common::UUID kHIDP(uint16_t(0x0011)); -constexpr common::UUID kAVCTP(uint16_t(0x0017)); -constexpr common::UUID kAVDTP(uint16_t(0x0019)); -constexpr common::UUID kL2CAP(uint16_t(0x0100)); +constexpr UUID kSDP(uint16_t(0x0001)); +constexpr UUID kRFCOMM(uint16_t(0x0003)); +constexpr UUID kATT(uint16_t(0x0007)); +constexpr UUID kOBEX(uint16_t(0x0008)); // IrDA Interop +constexpr UUID kBNEP(uint16_t(0x000F)); +constexpr UUID kHIDP(uint16_t(0x0011)); +constexpr UUID kAVCTP(uint16_t(0x0017)); +constexpr UUID kAVDTP(uint16_t(0x0019)); +constexpr UUID kL2CAP(uint16_t(0x0100)); } // namespace protocol @@ -110,63 +110,63 @@ constexpr common::UUID kL2CAP(uint16_t(0x0100)); namespace profile { // Service Discovery Profile (SDP) -constexpr common::UUID kServiceDiscoveryClass(uint16_t(0x1000)); -constexpr common::UUID kBrowseGroupClass(uint16_t(0x1001)); +constexpr UUID kServiceDiscoveryClass(uint16_t(0x1000)); +constexpr UUID kBrowseGroupClass(uint16_t(0x1001)); // Serial Port Profile (SPP) -constexpr common::UUID kSerialPort(uint16_t(0x1101)); +constexpr UUID kSerialPort(uint16_t(0x1101)); // Dial-up Networking Profile (DUN) -constexpr common::UUID kDialupNetworking(uint16_t(0x1103)); +constexpr UUID kDialupNetworking(uint16_t(0x1103)); // Object Push Profile (OPP) -constexpr common::UUID kObexObjectPush(uint16_t(0x1105)); +constexpr UUID kObexObjectPush(uint16_t(0x1105)); // File Transfer Profile (FTP) -constexpr common::UUID kObexFileTransfer(uint16_t(0x1106)); +constexpr UUID kObexFileTransfer(uint16_t(0x1106)); // Headset Profile (HSP) -constexpr common::UUID kHeadset(uint16_t(0x1108)); -constexpr common::UUID kHeadsetAudioGateway(uint16_t(0x1112)); -constexpr common::UUID kHeadsetHS(uint16_t(0x1131)); +constexpr UUID kHeadset(uint16_t(0x1108)); +constexpr UUID kHeadsetAudioGateway(uint16_t(0x1112)); +constexpr UUID kHeadsetHS(uint16_t(0x1131)); // Advanced Audio Distribution Profile (A2DP) -constexpr common::UUID kAudioSource(uint16_t(0x110A)); -constexpr common::UUID kAudioSink(uint16_t(0x110B)); -constexpr common::UUID kAdvancedAudioDistribution(uint16_t(0x110D)); +constexpr UUID kAudioSource(uint16_t(0x110A)); +constexpr UUID kAudioSink(uint16_t(0x110B)); +constexpr UUID kAdvancedAudioDistribution(uint16_t(0x110D)); // Audio/Video Remote Control Profile (AVRCP) -constexpr common::UUID kAVRemoteControlTarget(uint16_t(0x110C)); -constexpr common::UUID kAVRemoteControl(uint16_t(0x110E)); -constexpr common::UUID kAVRemoteControlController(uint16_t(0x110F)); +constexpr UUID kAVRemoteControlTarget(uint16_t(0x110C)); +constexpr UUID kAVRemoteControl(uint16_t(0x110E)); +constexpr UUID kAVRemoteControlController(uint16_t(0x110F)); // Personal Area Networking (PAN) -constexpr common::UUID kPANU(uint16_t(0x1115)); -constexpr common::UUID kNAP(uint16_t(0x1116)); -constexpr common::UUID kGN(uint16_t(0x1117)); +constexpr UUID kPANU(uint16_t(0x1115)); +constexpr UUID kNAP(uint16_t(0x1116)); +constexpr UUID kGN(uint16_t(0x1117)); // Basic Printing and Basic Imaging Profiles omitted (unsupported) // Hands-Free Profile (HFP) -constexpr common::UUID kHandsfree(uint16_t(0x111E)); -constexpr common::UUID kHandsfreeAudioGateway(uint16_t(0x111F)); +constexpr UUID kHandsfree(uint16_t(0x111E)); +constexpr UUID kHandsfreeAudioGateway(uint16_t(0x111F)); // Human Interface Device omitted (unsupported) // Hardcopy Cable Replacement Profile omitted (unsupported) // Sim Access Profile (SAP) -constexpr common::UUID kSIM_Access(uint16_t(0x112D)); +constexpr UUID kSIM_Access(uint16_t(0x112D)); // Phonebook Access Profile (PBAP) -constexpr common::UUID kPhonebookPCE(uint16_t(0x112E)); -constexpr common::UUID kPhonebookPSE(uint16_t(0x112F)); -constexpr common::UUID kPhonebook(uint16_t(0x1130)); +constexpr UUID kPhonebookPCE(uint16_t(0x112E)); +constexpr UUID kPhonebookPSE(uint16_t(0x112F)); +constexpr UUID kPhonebook(uint16_t(0x1130)); // Message Access Profile (MAP) -constexpr common::UUID kMessageAccessServer(uint16_t(0x1132)); -constexpr common::UUID kMessageNotificationServer(uint16_t(0x1133)); -constexpr common::UUID kMessageAccessProfile(uint16_t(0x1134)); +constexpr UUID kMessageAccessServer(uint16_t(0x1132)); +constexpr UUID kMessageNotificationServer(uint16_t(0x1133)); +constexpr UUID kMessageAccessProfile(uint16_t(0x1134)); // GNSS and 3DSP omitted (unsupported) // Multi-Profile Specification (MPS) -constexpr common::UUID kMPSProfile(uint16_t(0x113A)); -constexpr common::UUID kMPSClass(uint16_t(0x113B)); +constexpr UUID kMPSProfile(uint16_t(0x113A)); +constexpr UUID kMPSClass(uint16_t(0x113B)); // Calendar, Task, and Notes Profile omitted (unsupported) // Device ID -constexpr common::UUID kPeerIdentification(uint16_t(0x1200)); +constexpr UUID kPeerIdentification(uint16_t(0x1200)); // Video Distribution Profile (VDP) -constexpr common::UUID kVideoSource(uint16_t(0x1303)); -constexpr common::UUID kVideoSink(uint16_t(0x1304)); -constexpr common::UUID kVideoDistribution(uint16_t(0x1305)); +constexpr UUID kVideoSource(uint16_t(0x1303)); +constexpr UUID kVideoSink(uint16_t(0x1304)); +constexpr UUID kVideoDistribution(uint16_t(0x1305)); // Health Device Profile (HDP) -constexpr common::UUID kHDP(uint16_t(0x1400)); -constexpr common::UUID kHDPSource(uint16_t(0x1401)); -constexpr common::UUID kHDPSink(uint16_t(0x1402)); +constexpr UUID kHDP(uint16_t(0x1400)); +constexpr UUID kHDPSource(uint16_t(0x1401)); +constexpr UUID kHDPSink(uint16_t(0x1402)); } // namespace profile @@ -197,7 +197,7 @@ using ServiceRecordStateValueType = uint32_t; // Service ID constexpr AttributeId kServiceId = 0x0003; -using ServiceIdValueType = common::UUID; +using ServiceIdValueType = UUID; // Protocol Descriptor List constexpr AttributeId kProtocolDescriptorList = 0x0004; @@ -222,7 +222,7 @@ constexpr AttributeId kBrowseGroupList = 0x0005; using BrowseGroupListValueType = std::vector<DataElement>; // The UUID used for the root of the browsing hierarchy -constexpr common::UUID kPublicBrowseRootUuid(uint16_t(0x1002)); +constexpr UUID kPublicBrowseRootUuid(uint16_t(0x1002)); // Language Base Attribute Id List constexpr AttributeId kLanguageBaseAttributeIdList = 0x0006; diff --git a/src/connectivity/bluetooth/core/bt-host/sdp/server.cc b/src/connectivity/bluetooth/core/bt-host/sdp/server.cc index 9d1ffdcd7c4cb2b1dc9ed477a97a30c98b0af1c1..0e67ce86f1b0fe8c8b9611845e9f2a407cd684e4 100644 --- a/src/connectivity/bluetooth/core/bt-host/sdp/server.cc +++ b/src/connectivity/bluetooth/core/bt-host/sdp/server.cc @@ -13,9 +13,6 @@ namespace bt { namespace sdp { -using common::BufferView; -using common::UUID; - namespace { // The VersionNumberList value. (5.0, Vol 3, Part B, 5.2.3) @@ -140,7 +137,7 @@ bool Server::AddConnection(fbl::RefPtr<l2cap::Channel> channel) { auto self = weak_ptr_factory_.GetWeakPtr(); bool activated = channel->Activate( - [self, handle](common::ByteBufferPtr sdu) { + [self, handle](ByteBufferPtr sdu) { if (self) { self->OnRxBFrame(handle, std::move(sdu)); } @@ -369,7 +366,7 @@ void Server::OnChannelClosed(const hci::ConnectionHandle& handle) { } void Server::OnRxBFrame(const hci::ConnectionHandle& handle, - common::ByteBufferPtr sdu) { + ByteBufferPtr sdu) { ZX_DEBUG_ASSERT(sdu); uint16_t length = sdu->size(); if (length < sizeof(Header)) { @@ -384,7 +381,7 @@ void Server::OnRxBFrame(const hci::ConnectionHandle& handle, } l2cap::Channel* chan = it->second.get(); - common::PacketView<Header> packet(sdu.get()); + PacketView<Header> packet(sdu.get()); TransactionId tid = betoh16(packet.header().tid); uint16_t param_length = betoh16(packet.header().param_length); diff --git a/src/connectivity/bluetooth/core/bt-host/sdp/server.h b/src/connectivity/bluetooth/core/bt-host/sdp/server.h index 08a261dd4107c816b2b909bf91e6b6b7eea6ceed..5af54acafef2b67e9f2217cfcc9dcbec4ebd34ce 100644 --- a/src/connectivity/bluetooth/core/bt-host/sdp/server.h +++ b/src/connectivity/bluetooth/core/bt-host/sdp/server.h @@ -62,7 +62,7 @@ class Server final { // Performs a Service Search, returning any service record that contains // all UUID from the |search_pattern| ServiceSearchResponse SearchServices( - const std::unordered_set<common::UUID>& pattern) const; + const std::unordered_set<UUID>& pattern) const; // Gets Service Attributes in the |attribute_ranges| from the service record // with |handle|. @@ -72,13 +72,12 @@ class Server final { // Retrieves Service Attributes in the |attribute_ranges|, using the pattern // to search for the services that contain all UUIDs from the |search_pattern| ServiceSearchAttributeResponse SearchAllServiceAttributes( - const std::unordered_set<common::UUID>& search_pattern, + const std::unordered_set<UUID>& search_pattern, const std::list<AttributeRange>& attribute_ranges) const; // l2cap::Channel callbacks void OnChannelClosed(const hci::ConnectionHandle& handle); - void OnRxBFrame(const hci::ConnectionHandle& handle, - common::ByteBufferPtr sdu); + void OnRxBFrame(const hci::ConnectionHandle& handle, ByteBufferPtr sdu); // The data domain that owns the L2CAP layer. Used to register callbacks for // the channels of services registered. diff --git a/src/connectivity/bluetooth/core/bt-host/sdp/server_unittest.cc b/src/connectivity/bluetooth/core/bt-host/sdp/server_unittest.cc index dc24e2f4879029844a8b6be4c182c3a4e30204e0..2f3fe7ab6b78738f24e1346c19ae4d83cdfac09a 100644 --- a/src/connectivity/bluetooth/core/bt-host/sdp/server_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/sdp/server_unittest.cc @@ -5,7 +5,6 @@ #include "src/connectivity/bluetooth/core/bt-host/sdp/server.h" #include "gtest/gtest.h" - #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" #include "src/connectivity/bluetooth/core/bt-host/data/fake_domain.h" #include "src/connectivity/bluetooth/core/bt-host/l2cap/fake_channel.h" @@ -19,9 +18,6 @@ namespace bt { namespace sdp { namespace { -using common::LowerBits; -using common::UpperBits; - using bt::testing::FakeController; using TestingBase = bt::testing::FakeControllerTest<FakeController>; @@ -64,7 +60,7 @@ class SDP_ServerTest : public TestingBase { return channel_; } - bool Expect(const common::ByteBuffer& expected) { + bool Expect(const ByteBuffer& expected) { if (!fake_chan()) { bt_log(ERROR, "unittest", "no channel, failing!"); return false; @@ -72,7 +68,7 @@ class SDP_ServerTest : public TestingBase { bool success = false; auto cb = [&expected, &success, this](auto cb_packet) { - success = common::ContainersEqual(expected, *cb_packet); + success = ContainersEqual(expected, *cb_packet); }; fake_chan()->SetSendCallback(cb, dispatcher()); @@ -81,8 +77,8 @@ class SDP_ServerTest : public TestingBase { return success; } - bool ReceiveAndExpect(const common::ByteBuffer& packet, - const common::ByteBuffer& expected_response) { + bool ReceiveAndExpect(const ByteBuffer& packet, + const ByteBuffer& expected_response) { if (!fake_chan()) { bt_log(ERROR, "unittest", "no channel, failing!"); return false; @@ -135,10 +131,10 @@ class SDP_ServerTest : public TestingBase { constexpr l2cap::ChannelId kSdpChannel = 0x0041; -#define SDP_ERROR_RSP(t_id, code) \ - common::CreateStaticByteBuffer(0x01, UpperBits(t_id), LowerBits(t_id), 0x00, \ - 0x02, UpperBits(uint16_t(code)), \ - LowerBits(uint16_t(code))); +#define SDP_ERROR_RSP(t_id, code) \ + CreateStaticByteBuffer(0x01, UpperBits(t_id), LowerBits(t_id), 0x00, 0x02, \ + UpperBits(uint16_t(code)), \ + LowerBits(uint16_t(code))); // Test: // - Accepts channels and holds channel open correctly. @@ -154,18 +150,18 @@ TEST_F(SDP_ServerTest, BasicError) { const auto kRspErrSize = SDP_ERROR_RSP(0x1001, ErrorCode::kInvalidSize); const auto kTooSmall = - common::CreateStaticByteBuffer(0x01, // SDP_ServiceSearchRequest - 0x10, 0x01, // Transaction ID (0x1001) - 0x00, 0x09 // Parameter length (9 bytes) + CreateStaticByteBuffer(0x01, // SDP_ServiceSearchRequest + 0x10, 0x01, // Transaction ID (0x1001) + 0x00, 0x09 // Parameter length (9 bytes) ); const auto kRspTooSmall = SDP_ERROR_RSP(0x1001, ErrorCode::kInvalidSize); const auto kTooBig = - common::CreateStaticByteBuffer(0x01, // SDP_ServiceSearchRequest - 0x20, 0x10, // Transaction ID (0x2010) - 0x00, 0x02, // Parameter length (2 bytes) - 0x01, 0x02, 0x03 // 3 bytes of parameters + CreateStaticByteBuffer(0x01, // SDP_ServiceSearchRequest + 0x20, 0x10, // Transaction ID (0x2010) + 0x00, 0x02, // Parameter length (2 bytes) + 0x01, 0x02, 0x03 // 3 bytes of parameters ); const auto kRspTooBig = SDP_ERROR_RSP(0x2010, ErrorCode::kInvalidSize); @@ -294,16 +290,16 @@ TEST_F(SDP_ServerTest, ServiceSearchRequest) { 0x0bad); RunLoopUntilIdle(); - const auto kL2capSearch = common::CreateStaticByteBuffer( - 0x02, // SDP_ServiceSearchRequest - 0x10, 0x01, // Transaction ID (0x1001) - 0x00, 0x08, // Parameter length (8 bytes) - // ServiceSearchPattern - 0x35, 0x03, // Sequence uint8 3 bytes - 0x19, 0x01, 0x00, // UUID: Protocol: L2CAP - 0xFF, 0xFF, // MaximumServiceRecordCount: (none) - 0x00 // Contunuation State: none - ); + const auto kL2capSearch = + CreateStaticByteBuffer(0x02, // SDP_ServiceSearchRequest + 0x10, 0x01, // Transaction ID (0x1001) + 0x00, 0x08, // Parameter length (8 bytes) + // ServiceSearchPattern + 0x35, 0x03, // Sequence uint8 3 bytes + 0x19, 0x01, 0x00, // UUID: Protocol: L2CAP + 0xFF, 0xFF, // MaximumServiceRecordCount: (none) + 0x00 // Contunuation State: none + ); ServiceSearchRequest search_req; EXPECT_FALSE(search_req.valid()); @@ -316,7 +312,7 @@ TEST_F(SDP_ServerTest, ServiceSearchRequest) { EXPECT_TRUE(ContainersEqual(kL2capSearch, *pdu)); - const auto kL2capSearchResponse = common::CreateStaticByteBuffer( + const auto kL2capSearchResponse = CreateStaticByteBuffer( 0x03, // SDP_ServicesearchResponse 0x10, 0x01, // Transaction ID (0x1001) 0x00, 0x0D, // Parameter length (13 bytes) @@ -332,7 +328,7 @@ TEST_F(SDP_ServerTest, ServiceSearchRequest) { TransactionId tid; auto cb = [&recv, &handles, &tid](auto cb_packet) { EXPECT_LE(sizeof(Header), cb_packet->size()); - common::PacketView<Header> packet(cb_packet.get()); + PacketView<Header> packet(cb_packet.get()); EXPECT_EQ(kServiceSearchResponse, packet.header().pdu_id); tid = betoh16(packet.header().tid); uint16_t len = betoh16(packet.header().param_length); @@ -357,22 +353,22 @@ TEST_F(SDP_ServerTest, ServiceSearchRequest) { EXPECT_NE(handles.end(), std::find(handles.begin(), handles.end(), a2dp_handle)); - const auto kInvalidNoItems = common::CreateStaticByteBuffer( - 0x02, // SDP_ServiceSearchRequest - 0x10, 0xA1, // Transaction ID (0x10A1) - 0x00, 0x05, // Parameter length (5 bytes) - // ServiceSearchPattern - 0x35, 0x00, // Sequence uint8 0 bytes - 0xFF, 0xFF, // MaximumServiceRecordCount: (none) - 0x00 // Contunuation State: none - ); + const auto kInvalidNoItems = + CreateStaticByteBuffer(0x02, // SDP_ServiceSearchRequest + 0x10, 0xA1, // Transaction ID (0x10A1) + 0x00, 0x05, // Parameter length (5 bytes) + // ServiceSearchPattern + 0x35, 0x00, // Sequence uint8 0 bytes + 0xFF, 0xFF, // MaximumServiceRecordCount: (none) + 0x00 // Contunuation State: none + ); const auto kRspErrSyntax = SDP_ERROR_RSP(0x10A1, ErrorCode::kInvalidRequestSyntax); EXPECT_TRUE(ReceiveAndExpect(kInvalidNoItems, kRspErrSyntax)); - const auto kInvalidTooManyItems = common::CreateStaticByteBuffer( + const auto kInvalidTooManyItems = CreateStaticByteBuffer( 0x02, // SDP_ServiceSearchRequest 0x10, 0xA1, // Transaction ID (0x10B1) 0x00, 0x2C, // Parameter length (44 bytes) @@ -404,7 +400,7 @@ TEST_F(SDP_ServerTest, ServiceSearchRequestOneOfMany) { TransactionId tid; auto cb = [&recv, &handles, &tid](auto cb_packet) { EXPECT_LE(sizeof(Header), cb_packet->size()); - common::PacketView<Header> packet(cb_packet.get()); + PacketView<Header> packet(cb_packet.get()); EXPECT_EQ(kServiceSearchResponse, packet.header().pdu_id); tid = betoh16(packet.header().tid); uint16_t len = betoh16(packet.header().param_length); @@ -417,16 +413,16 @@ TEST_F(SDP_ServerTest, ServiceSearchRequestOneOfMany) { recv = true; }; - const auto kL2capSearchOne = common::CreateStaticByteBuffer( - 0x02, // SDP_ServiceSearchRequest - 0x10, 0xC1, // Transaction ID (0x10C1) - 0x00, 0x08, // Parameter length (8 bytes) - // ServiceSearchPattern - 0x35, 0x03, // Sequence uint8 3 bytes - 0x19, 0x01, 0x00, // UUID: Protocol: L2CAP - 0x00, 0x01, // MaximumServiceRecordCount: 1 - 0x00 // Contunuation State: none - ); + const auto kL2capSearchOne = + CreateStaticByteBuffer(0x02, // SDP_ServiceSearchRequest + 0x10, 0xC1, // Transaction ID (0x10C1) + 0x00, 0x08, // Parameter length (8 bytes) + // ServiceSearchPattern + 0x35, 0x03, // Sequence uint8 3 bytes + 0x19, 0x01, 0x00, // UUID: Protocol: L2CAP + 0x00, 0x01, // MaximumServiceRecordCount: 1 + 0x00 // Contunuation State: none + ); handles.clear(); recv = false; @@ -464,7 +460,7 @@ TEST_F(SDP_ServerTest, ServiceAttributeRequest) { 0x0bad); RunLoopUntilIdle(); - const auto kRequestAttr = common::CreateStaticByteBuffer( + const auto kRequestAttr = CreateStaticByteBuffer( 0x04, // SDP_ServiceAttritbuteRequest 0x10, 0x01, // Transaction ID (0x1001) 0x00, 0x11, // Parameter length (17 bytes) @@ -486,7 +482,7 @@ TEST_F(SDP_ServerTest, ServiceAttributeRequest) { auto send_cb = [this, handle, &rsp, &received](auto cb_packet) { EXPECT_LE(sizeof(Header), cb_packet->size()); - common::PacketView<sdp::Header> packet(cb_packet.get()); + PacketView<sdp::Header> packet(cb_packet.get()); ASSERT_EQ(0x05, packet.header().pdu_id); uint16_t len = betoh16(packet.header().param_length); EXPECT_LE(len, 0x11); // 10 + 2 (byte count) + 5 (cont state) @@ -495,11 +491,11 @@ TEST_F(SDP_ServerTest, ServiceAttributeRequest) { if (received == 0) { // Server should have split this into more than one response. EXPECT_FALSE(st); - EXPECT_EQ(common::HostError::kInProgress, st.error()); + EXPECT_EQ(HostError::kInProgress, st.error()); EXPECT_FALSE(rsp.complete()); } received++; - if (!st && (st.error() != common::HostError::kInProgress)) { + if (!st && (st.error() != HostError::kInProgress)) { // This isn't a valid packet and we shouldn't try to get // a continuation. return; @@ -511,7 +507,7 @@ TEST_F(SDP_ServerTest, ServiceAttributeRequest) { EXPECT_NE(0u, cont_size); // Make another request with the continutation data. size_t param_size = 17 + cont_size; - auto kContinuedRequestAttrStart = common::CreateStaticByteBuffer( + auto kContinuedRequestAttrStart = CreateStaticByteBuffer( 0x04, // SDP_ServiceAttributeRequest 0x10, static_cast<uint8_t>(received + 1), UpperBits(param_size), LowerBits(param_size), // Parameter length @@ -525,8 +521,8 @@ TEST_F(SDP_ServerTest, ServiceAttributeRequest) { 0x30, 0x00, // low end of range 0xf0, 0x00 // high end of range ); - common::DynamicByteBuffer req(kContinuedRequestAttrStart.size() + - sizeof(uint8_t) + cont_size); + DynamicByteBuffer req(kContinuedRequestAttrStart.size() + + sizeof(uint8_t) + cont_size); kContinuedRequestAttrStart.Copy(&req); req.Write(&cont_size, sizeof(uint8_t), kContinuedRequestAttrStart.size()); @@ -547,7 +543,7 @@ TEST_F(SDP_ServerTest, ServiceAttributeRequest) { EXPECT_NE(attrs.end(), attrs.find(kServiceClassIdList)); EXPECT_NE(attrs.end(), attrs.find(0xf000)); - const auto kInvalidRangeOrder = common::CreateStaticByteBuffer( + const auto kInvalidRangeOrder = CreateStaticByteBuffer( 0x04, // SDP_ServiceAttritbuteRequest 0xE0, 0x01, // Transaction ID (0xE001) 0x00, 0x11, // Parameter length (17 bytes) @@ -568,7 +564,7 @@ TEST_F(SDP_ServerTest, ServiceAttributeRequest) { EXPECT_TRUE(ReceiveAndExpect(kInvalidRangeOrder, kRspErrSyntax)); - const auto kInvalidMaxBytes = common::CreateStaticByteBuffer( + const auto kInvalidMaxBytes = CreateStaticByteBuffer( 0x04, // SDP_ServiceAttritbuteRequest 0xE0, 0x02, // Transaction ID (0xE001) 0x00, 0x0C, // Parameter length (12 bytes) @@ -618,7 +614,7 @@ TEST_F(SDP_ServerTest, SearchAttributeRequest) { 0x0bad); RunLoopUntilIdle(); - const auto kRequestAttr = common::CreateStaticByteBuffer( + const auto kRequestAttr = CreateStaticByteBuffer( 0x06, // SDP_ServiceAttritbuteRequest 0x10, 0x01, // Transaction ID (0x1001) 0x00, 0x12, // Parameter length (18 bytes) @@ -642,7 +638,7 @@ TEST_F(SDP_ServerTest, SearchAttributeRequest) { auto send_cb = [this, &rsp, &received](auto cb_packet) { EXPECT_LE(sizeof(Header), cb_packet->size()); - common::PacketView<sdp::Header> packet(cb_packet.get()); + PacketView<sdp::Header> packet(cb_packet.get()); ASSERT_EQ(0x07, packet.header().pdu_id); uint16_t len = betoh16(packet.header().param_length); EXPECT_LE(len, 0x11); // 2 (byte count) + 10 (max len) + 5 (cont state) @@ -651,11 +647,11 @@ TEST_F(SDP_ServerTest, SearchAttributeRequest) { if (received == 0) { // Server should have split this into more than one response. EXPECT_FALSE(st); - EXPECT_EQ(common::HostError::kInProgress, st.error()); + EXPECT_EQ(HostError::kInProgress, st.error()); EXPECT_FALSE(rsp.complete()); } received++; - if (!st && (st.error() != common::HostError::kInProgress)) { + if (!st && (st.error() != HostError::kInProgress)) { // This isn't a valid packet and we shouldn't try to get // a continuation. return; @@ -667,7 +663,7 @@ TEST_F(SDP_ServerTest, SearchAttributeRequest) { EXPECT_NE(0u, cont_size); // Make another request with the continutation data. size_t param_size = 18 + cont_size; - auto kContinuedRequestAttrStart = common::CreateStaticByteBuffer( + auto kContinuedRequestAttrStart = CreateStaticByteBuffer( 0x06, // SDP_ServiceAttributeRequest 0x10, static_cast<uint8_t>(received + 1), // Transaction ID UpperBits(param_size), LowerBits(param_size), // Parameter length @@ -682,8 +678,8 @@ TEST_F(SDP_ServerTest, SearchAttributeRequest) { 0x30, 0x00, // low end of range 0xf0, 0x00 // high end of range ); - common::DynamicByteBuffer req(kContinuedRequestAttrStart.size() + - sizeof(uint8_t) + cont_size); + DynamicByteBuffer req(kContinuedRequestAttrStart.size() + + sizeof(uint8_t) + cont_size); kContinuedRequestAttrStart.Copy(&req); req.Write(&cont_size, sizeof(uint8_t), kContinuedRequestAttrStart.size()); @@ -714,7 +710,7 @@ TEST_F(SDP_ServerTest, SearchAttributeRequest) { } } - const auto kInvalidRangeOrder = common::CreateStaticByteBuffer( + const auto kInvalidRangeOrder = CreateStaticByteBuffer( 0x06, // SDP_ServiceAttritbuteRequest 0xE0, 0x01, // Transaction ID (0xE001) 0x00, 0x12, // Parameter length (18 bytes) @@ -735,7 +731,7 @@ TEST_F(SDP_ServerTest, SearchAttributeRequest) { EXPECT_TRUE(ReceiveAndExpect(kInvalidRangeOrder, kRspErrSyntax)); - const auto kInvalidMaxBytes = common::CreateStaticByteBuffer( + const auto kInvalidMaxBytes = CreateStaticByteBuffer( 0x04, // SDP_ServiceAttritbuteRequest 0xE0, 0x02, // Transaction ID (0xE002) 0x00, 0x0D, // Parameter length (13 bytes) @@ -798,25 +794,25 @@ TEST_F(SDP_ServerTest, BrowseGroup) { 0x0bad); RunLoopUntilIdle(); - const auto kRequestAttr = common::CreateStaticByteBuffer( - 0x06, // SDP_ServiceAttritbuteRequest - 0x10, 0x01, // Transaction ID (0x1001) - 0x00, 0x0D, // Parameter length (12 bytes) - // ServiceSearchPattern - 0x35, 0x03, // Sequence uint8 3 bytes - 0x19, 0x01, 0x00, // UUID: Protocol: L2CAP - 0xFF, 0xFF, // MaximumAttributeByteCount (no max) - // AttributeIDList - 0x35, 0x03, // Sequence uint8 3 bytes - 0x09, // uint16_t, single attribute - 0x00, 0x05, // BrowseGroupList - 0x00 // Contunuation State: none - ); + const auto kRequestAttr = + CreateStaticByteBuffer(0x06, // SDP_ServiceAttritbuteRequest + 0x10, 0x01, // Transaction ID (0x1001) + 0x00, 0x0D, // Parameter length (12 bytes) + // ServiceSearchPattern + 0x35, 0x03, // Sequence uint8 3 bytes + 0x19, 0x01, 0x00, // UUID: Protocol: L2CAP + 0xFF, 0xFF, // MaximumAttributeByteCount (no max) + // AttributeIDList + 0x35, 0x03, // Sequence uint8 3 bytes + 0x09, // uint16_t, single attribute + 0x00, 0x05, // BrowseGroupList + 0x00 // Contunuation State: none + ); ServiceSearchAttributeResponse rsp; auto send_cb = [this, &rsp](auto cb_packet) { EXPECT_LE(sizeof(Header), cb_packet->size()); - common::PacketView<sdp::Header> packet(cb_packet.get()); + PacketView<sdp::Header> packet(cb_packet.get()); ASSERT_EQ(0x07, packet.header().pdu_id); uint16_t len = betoh16(packet.header().param_length); packet.Resize(len); @@ -834,8 +830,7 @@ TEST_F(SDP_ServerTest, BrowseGroup) { ASSERT_EQ(DataElement::Type::kSequence, group_attr_it->second.type()); ASSERT_EQ(DataElement::Type::kUuid, group_attr_it->second.At(0)->type()); EXPECT_NE(attributes.end(), group_attr_it); - EXPECT_EQ(kPublicBrowseRootUuid, - *group_attr_it->second.At(0)->Get<common::UUID>()); + EXPECT_EQ(kPublicBrowseRootUuid, *group_attr_it->second.At(0)->Get<UUID>()); } #undef SDP_ERROR_RSP diff --git a/src/connectivity/bluetooth/core/bt-host/sdp/service_discoverer.cc b/src/connectivity/bluetooth/core/bt-host/sdp/service_discoverer.cc index e88c55f3dfb36cc740329f87d3f0776f1b4aed7e..0d6d4885254cc27b54a8cf68807d876729e54e35 100644 --- a/src/connectivity/bluetooth/core/bt-host/sdp/service_discoverer.cc +++ b/src/connectivity/bluetooth/core/bt-host/sdp/service_discoverer.cc @@ -12,7 +12,7 @@ namespace sdp { ServiceDiscoverer::ServiceDiscoverer() : next_id_(1) {} ServiceDiscoverer::SearchId ServiceDiscoverer::AddSearch( - const common::UUID& uuid, std::unordered_set<AttributeId> attributes, + const UUID& uuid, std::unordered_set<AttributeId> attributes, ResultCallback callback) { ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); Search s; @@ -40,7 +40,7 @@ bool ServiceDiscoverer::RemoveSearch(SearchId id) { return searches_.erase(id); } -bool ServiceDiscoverer::StartServiceDiscovery(common::PeerId peer_id, +bool ServiceDiscoverer::StartServiceDiscovery(PeerId peer_id, std::unique_ptr<Client> client) { ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); // If discovery is already happening on this peer, then we can't start it @@ -78,8 +78,7 @@ bool ServiceDiscoverer::StartServiceDiscovery(common::PeerId peer_id, size_t ServiceDiscoverer::search_count() const { return searches_.size(); } -void ServiceDiscoverer::FinishPeerSearch(common::PeerId peer_id, - SearchId search_id) { +void ServiceDiscoverer::FinishPeerSearch(PeerId peer_id, SearchId search_id) { auto it = sessions_.find(peer_id); if (it == sessions_.end()) { bt_log(INFO, "sdp", "Couldn't find session to finish search"); diff --git a/src/connectivity/bluetooth/core/bt-host/sdp/service_discoverer.h b/src/connectivity/bluetooth/core/bt-host/sdp/service_discoverer.h index c6645983d299fdf5df01c28c0ae84a0647745bff..7f2a61fca93996d527de3a76924e7da9ea4e6861 100644 --- a/src/connectivity/bluetooth/core/bt-host/sdp/service_discoverer.h +++ b/src/connectivity/bluetooth/core/bt-host/sdp/service_discoverer.h @@ -48,9 +48,9 @@ class ServiceDiscoverer final { // Returns a SearchId can be used to remove the search later if successful, // or kInvalidSearchId if adding the search failed. // |callback| will be called on the creation thread of ServiceDiscoverer. - using ResultCallback = fit::function<void( - common::PeerId, const std::map<AttributeId, DataElement> &)>; - SearchId AddSearch(const common::UUID &uuid, + using ResultCallback = + fit::function<void(PeerId, const std::map<AttributeId, DataElement> &)>; + SearchId AddSearch(const UUID &uuid, std::unordered_set<AttributeId> attributes, ResultCallback callback); @@ -64,8 +64,7 @@ class ServiceDiscoverer final { // If a search is already being performed on the same |peer_id|, the client // is immediately dropped. // Returns true if discovery was started, and false otherwise. - bool StartServiceDiscovery(common::PeerId peer_id, - std::unique_ptr<Client> client); + bool StartServiceDiscovery(PeerId peer_id, std::unique_ptr<Client> client); // Returns the number of searches that will be performed on a // StartServiceDiscovery. @@ -74,7 +73,7 @@ class ServiceDiscoverer final { private: // A registered search. struct Search { - common::UUID uuid; + UUID uuid; std::unordered_set<AttributeId> attributes; ResultCallback callback; }; @@ -90,7 +89,7 @@ class ServiceDiscoverer final { // Finish the Discovery Session for |peer_id| searching |search_id|, // releasing the client if all searches are complete. - void FinishPeerSearch(common::PeerId peer_id, SearchId search_id); + void FinishPeerSearch(PeerId peer_id, SearchId search_id); // Next likely search id SearchId next_id_; @@ -100,7 +99,7 @@ class ServiceDiscoverer final { // Clients that searches are still being performed on, based on the remote // peer id. - std::unordered_map<common::PeerId, DiscoverySession> sessions_; + std::unordered_map<PeerId, DiscoverySession> sessions_; fxl::ThreadChecker thread_checker_; }; diff --git a/src/connectivity/bluetooth/core/bt-host/sdp/service_discoverer_unittest.cc b/src/connectivity/bluetooth/core/bt-host/sdp/service_discoverer_unittest.cc index afcd5c0d70df29b05a24119ed7578ec7137b9e23..91292b243f7e1127902eff269635a3755d50de00 100644 --- a/src/connectivity/bluetooth/core/bt-host/sdp/service_discoverer_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/sdp/service_discoverer_unittest.cc @@ -17,9 +17,7 @@ namespace { using TestingBase = ::gtest::TestLoopFixture; -using common::CreateStaticByteBuffer; - -constexpr common::PeerId kDeviceOne(1), kDeviceTwo(2), kDeviceThree(3); +constexpr PeerId kDeviceOne(1), kDeviceTwo(2), kDeviceThree(3); class FakeClient : public Client { public: @@ -31,7 +29,7 @@ class FakeClient : public Client { virtual ~FakeClient() override { destroyed_cb_(); } virtual void ServiceSearchAttributes( - std::unordered_set<common::UUID> search_pattern, + std::unordered_set<UUID> search_pattern, const std::unordered_set<AttributeId> &req_attributes, SearchResultCallback result_cb, async_dispatcher_t *cb_dispatcher) override { @@ -45,7 +43,7 @@ class FakeClient : public Client { } using ServiceSearchAttributesCalllback = fit::function<void( - std::unordered_set<common::UUID>, std::unordered_set<AttributeId>, + std::unordered_set<UUID>, std::unordered_set<AttributeId>, SearchResultCallback, async_dispatcher_t *)>; void SetServiceSearchAttributesCallback( ServiceSearchAttributesCalllback callback) { @@ -113,14 +111,14 @@ TEST_F(SDP_ServiceDiscovererTest, NoResults) { auto client = GetFakeClient(); - std::vector<std::unordered_set<common::UUID>> searches; + std::vector<std::unordered_set<UUID>> searches; client->SetServiceSearchAttributesCallback( [&searches](auto pattern, auto attributes, auto callback, auto *cb_dispatcher) { searches.emplace_back(std::move(pattern)); async::PostTask(cb_dispatcher, [cb = std::move(callback)]() { - cb(Status(common::HostError::kNotFound), {}); + cb(Status(HostError::kNotFound), {}); }); }); @@ -140,11 +138,10 @@ TEST_F(SDP_ServiceDiscovererTest, NoResults) { TEST_F(SDP_ServiceDiscovererTest, SomeResults) { ServiceDiscoverer discoverer; - std::vector<std::pair<common::PeerId, std::map<AttributeId, DataElement>>> - results; + std::vector<std::pair<PeerId, std::map<AttributeId, DataElement>>> results; ServiceDiscoverer::ResultCallback result_cb = - [&results](common::PeerId id, const auto &attributes) { + [&results](PeerId id, const auto &attributes) { std::map<AttributeId, DataElement> attributes_clone; for (const auto &it : attributes) { auto [inserted_it, added] = @@ -169,14 +166,14 @@ TEST_F(SDP_ServiceDiscovererTest, SomeResults) { auto client = GetFakeClient(); - std::vector<std::unordered_set<common::UUID>> searches; + std::vector<std::unordered_set<UUID>> searches; client->SetServiceSearchAttributesCallback( [&searches](auto pattern, auto attributes, auto callback, auto *cb_dispatcher) { searches.emplace_back(std::move(pattern)); async::PostTask(cb_dispatcher, [cb = std::move(callback)]() { - cb(Status(common::HostError::kNotFound), {}); + cb(Status(HostError::kNotFound), {}); }); }); @@ -192,44 +189,43 @@ TEST_F(SDP_ServiceDiscovererTest, SomeResults) { searches.clear(); - client->SetServiceSearchAttributesCallback([&searches](auto pattern, - auto attributes, - auto callback, - auto *cb_dispatcher) { - searches.emplace_back(pattern); - if (pattern.count(profile::kSerialPort)) { - async::PostTask(cb_dispatcher, [cb = std::move(callback)]() { - ServiceSearchAttributeResponse rsp; - rsp.SetAttribute(0, kServiceId, DataElement(common::UUID(uint16_t(1)))); - // This would normally be a element list. uint32_t for Testing. - rsp.SetAttribute(0, kBluetoothProfileDescriptorList, - DataElement(uint32_t(1))); - - if (!cb(Status(), rsp.attributes(0))) { - return; - } - cb(Status(common::HostError::kNotFound), {}); - }); - } else if (pattern.count(profile::kAudioSink)) { - async::PostTask(cb_dispatcher, [cb = std::move(callback)]() { - ServiceSearchAttributeResponse rsp; - // This would normally be a element list. uint32_t for Testing. - rsp.SetAttribute(0, kBluetoothProfileDescriptorList, - DataElement(uint32_t(1))); - - if (!cb(Status(), rsp.attributes(0))) { - return; + client->SetServiceSearchAttributesCallback( + [&searches](auto pattern, auto attributes, auto callback, + auto *cb_dispatcher) { + searches.emplace_back(pattern); + if (pattern.count(profile::kSerialPort)) { + async::PostTask(cb_dispatcher, [cb = std::move(callback)]() { + ServiceSearchAttributeResponse rsp; + rsp.SetAttribute(0, kServiceId, DataElement(UUID(uint16_t(1)))); + // This would normally be a element list. uint32_t for Testing. + rsp.SetAttribute(0, kBluetoothProfileDescriptorList, + DataElement(uint32_t(1))); + + if (!cb(Status(), rsp.attributes(0))) { + return; + } + cb(Status(HostError::kNotFound), {}); + }); + } else if (pattern.count(profile::kAudioSink)) { + async::PostTask(cb_dispatcher, [cb = std::move(callback)]() { + ServiceSearchAttributeResponse rsp; + // This would normally be a element list. uint32_t for Testing. + rsp.SetAttribute(0, kBluetoothProfileDescriptorList, + DataElement(uint32_t(1))); + + if (!cb(Status(), rsp.attributes(0))) { + return; + } + cb(Status(HostError::kNotFound), {}); + }); + } else { + std::cerr << "Searched for " << pattern.size() << std::endl; + for (auto it : pattern) { + std::cerr << it.ToString() << std::endl; + } + FAIL() << "Unexpected search called"; } - cb(Status(common::HostError::kNotFound), {}); }); - } else { - std::cerr << "Searched for " << pattern.size() << std::endl; - for (auto it : pattern) { - std::cerr << it.ToString() << std::endl; - } - FAIL() << "Unexpected search called"; - } - }); discoverer.StartServiceDiscovery(kDeviceTwo, std::move(client)); @@ -267,7 +263,7 @@ TEST_F(SDP_ServiceDiscovererTest, SomeResults) { if (!cb(Status(), rsp.attributes(1))) { return; } - cb(Status(common::HostError::kNotFound), {}); + cb(Status(HostError::kNotFound), {}); }); } else { std::cerr << "Searched for " << pattern.size() << std::endl; @@ -304,7 +300,7 @@ TEST_F(SDP_ServiceDiscovererTest, Disconnected) { auto client = GetFakeClient(); - std::vector<std::unordered_set<common::UUID>> searches; + std::vector<std::unordered_set<UUID>> searches; client->SetServiceSearchAttributesCallback( [&searches](auto pattern, auto attributes, auto callback, @@ -312,7 +308,7 @@ TEST_F(SDP_ServiceDiscovererTest, Disconnected) { searches.emplace_back(pattern); if (pattern.count(profile::kSerialPort)) { async::PostTask(cb_dispatcher, [cb = std::move(callback)]() { - cb(Status(common::HostError::kLinkDisconnected), {}); + cb(Status(HostError::kLinkDisconnected), {}); }); } else { std::cerr << "Searched for " << pattern.size() << std::endl; @@ -336,8 +332,7 @@ TEST_F(SDP_ServiceDiscovererTest, Disconnected) { TEST_F(SDP_ServiceDiscovererTest, UnregisterInProgress) { ServiceDiscoverer discoverer; - std::optional<std::pair<common::PeerId, std::map<AttributeId, DataElement>>> - result; + std::optional<std::pair<PeerId, std::map<AttributeId, DataElement>>> result; ServiceDiscoverer::SearchId id = ServiceDiscoverer::kInvalidSearchId; @@ -364,7 +359,7 @@ TEST_F(SDP_ServiceDiscovererTest, UnregisterInProgress) { auto client = GetFakeClient(); - std::vector<std::unordered_set<common::UUID>> searches; + std::vector<std::unordered_set<UUID>> searches; client->SetServiceSearchAttributesCallback([&searches](auto pattern, auto attributes, @@ -385,7 +380,7 @@ TEST_F(SDP_ServiceDiscovererTest, UnregisterInProgress) { if (!cb(Status(), rsp.attributes(1))) { return; } - cb(Status(common::HostError::kNotFound), {}); + cb(Status(HostError::kNotFound), {}); }); } else { std::cerr << "Searched for " << pattern.size() << std::endl; diff --git a/src/connectivity/bluetooth/core/bt-host/sdp/service_record.cc b/src/connectivity/bluetooth/core/bt-host/sdp/service_record.cc index f430f3266784a27a564087d9b52619f72b55f661..887f3d535ec5b30743316c5b7e2d68459024f9c9 100644 --- a/src/connectivity/bluetooth/core/bt-host/sdp/service_record.cc +++ b/src/connectivity/bluetooth/core/bt-host/sdp/service_record.cc @@ -18,11 +18,10 @@ namespace { // Adds all UUIDs that it finds in |elem| to |out|, recursing through // sequences and alternatives if necessary. -void AddAllUUIDs(const DataElement& elem, - std::unordered_set<common::UUID>* out) { +void AddAllUUIDs(const DataElement& elem, std::unordered_set<UUID>* out) { DataElement::Type type = elem.type(); if (type == DataElement::Type::kUuid) { - out->emplace(*elem.Get<common::UUID>()); + out->emplace(*elem.Get<UUID>()); } else if (type == DataElement::Type::kSequence || type == DataElement::Type::kAlternative) { const DataElement* it; @@ -35,8 +34,8 @@ void AddAllUUIDs(const DataElement& elem, } // namespace ServiceRecord::ServiceRecord() { - common::UUID service_uuid; - common::StringToUuid(uuid::Generate(), &service_uuid); + UUID service_uuid; + StringToUuid(uuid::Generate(), &service_uuid); SetAttribute(kServiceId, DataElement(service_uuid)); } @@ -76,13 +75,12 @@ std::set<AttributeId> ServiceRecord::GetAttributesInRange( return attrs; } -bool ServiceRecord::FindUUID( - const std::unordered_set<common::UUID>& uuids) const { +bool ServiceRecord::FindUUID(const std::unordered_set<UUID>& uuids) const { if (uuids.size() == 0) { return true; } // Gather all the UUIDs in the attributes - std::unordered_set<common::UUID> attribute_uuids; + std::unordered_set<UUID> attribute_uuids; for (const auto& it : attributes_) { AddAllUUIDs(it.second, &attribute_uuids); } @@ -94,8 +92,7 @@ bool ServiceRecord::FindUUID( return true; } -void ServiceRecord::SetServiceClassUUIDs( - const std::vector<common::UUID>& classes) { +void ServiceRecord::SetServiceClassUUIDs(const std::vector<UUID>& classes) { std::vector<DataElement> class_uuids; for (const auto& uuid : classes) { class_uuids.emplace_back(DataElement(uuid)); @@ -105,7 +102,7 @@ void ServiceRecord::SetServiceClassUUIDs( } void ServiceRecord::AddProtocolDescriptor(const ProtocolListId id, - const common::UUID& uuid, + const UUID& uuid, DataElement params) { std::vector<DataElement> seq; if (id == kPrimaryProtocolList) { @@ -148,8 +145,7 @@ void ServiceRecord::AddProtocolDescriptor(const ProtocolListId id, } } -void ServiceRecord::AddProfile(const common::UUID& uuid, uint8_t major, - uint8_t minor) { +void ServiceRecord::AddProfile(const UUID& uuid, uint8_t major, uint8_t minor) { std::vector<DataElement> seq; auto list_it = attributes_.find(kBluetoothProfileDescriptorList); if (list_it != attributes_.end()) { diff --git a/src/connectivity/bluetooth/core/bt-host/sdp/service_record.h b/src/connectivity/bluetooth/core/bt-host/sdp/service_record.h index f33717b53ca2dd7ccb4a52c37a1be02f008798cc..a90779caed6090b8b5c517759218facbceed79d2 100644 --- a/src/connectivity/bluetooth/core/bt-host/sdp/service_record.h +++ b/src/connectivity/bluetooth/core/bt-host/sdp/service_record.h @@ -56,10 +56,10 @@ class ServiceRecord { // Returns true if any value of the attributes in this service contain all // of the |uuids| given. The uuids need not be in any specific attribute // value. - bool FindUUID(const std::unordered_set<common::UUID>& uuids) const; + bool FindUUID(const std::unordered_set<UUID>& uuids) const; // Convenience function to set the service class id list attribute. - void SetServiceClassUUIDs(const std::vector<common::UUID>& classes); + void SetServiceClassUUIDs(const std::vector<UUID>& classes); using ProtocolListId = uint8_t; @@ -75,13 +75,13 @@ class ServiceRecord { // - a single DataElement parameter // kPrimaryProtocolList is presented as the primary protocol. // Other protocol will be added to the addiitonal protocol lists, - void AddProtocolDescriptor(const ProtocolListId id, const common::UUID& uuid, + void AddProtocolDescriptor(const ProtocolListId id, const UUID& uuid, DataElement params); // Adds a profile to the bluetooth profile descrpitor list attribute. // |uuid| is the UUID of the profile. |major| and |minor| are the major and // minor versions of the profile supported. - void AddProfile(const common::UUID& uuid, uint8_t major, uint8_t minor); + void AddProfile(const UUID& uuid, uint8_t major, uint8_t minor); // Adds a set of language attributes. // |language| is required (and must be two characters long) diff --git a/src/connectivity/bluetooth/core/bt-host/sdp/service_record_unittest.cc b/src/connectivity/bluetooth/core/bt-host/sdp/service_record_unittest.cc index 975eb754556ae62327cb6f1b35d8aaff55ced81d..61319a78abc79bbe9ca82b0ac12ec2f70d78b201 100644 --- a/src/connectivity/bluetooth/core/bt-host/sdp/service_record_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/sdp/service_record_unittest.cc @@ -3,12 +3,11 @@ // found in the LICENSE file. #include "src/connectivity/bluetooth/core/bt-host/sdp/service_record.h" -#include "src/connectivity/bluetooth/core/bt-host/sdp/data_element.h" #include "gtest/gtest.h" - #include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" +#include "src/connectivity/bluetooth/core/bt-host/sdp/data_element.h" namespace bt { namespace sdp { @@ -38,9 +37,9 @@ TEST_F(SDP_ServiceRecordTest, BasicFunctionality) { // This isn't a valid service class ID list: // - ServiceDiscoveryServerServiceClassID // - BrowseGroupDesciptorServiceClassID - common::UUID sdp_id(uint16_t(0x1000)); - common::UUID group_id(uint16_t(0x1001)); - std::vector<common::UUID> service_class; + UUID sdp_id(uint16_t(0x1000)); + UUID group_id(uint16_t(0x1001)); + std::vector<UUID> service_class; service_class.push_back(sdp_id); service_class.emplace_back(group_id); @@ -57,8 +56,8 @@ TEST_F(SDP_ServiceRecordTest, BasicFunctionality) { EXPECT_TRUE(vec); EXPECT_EQ(2u, vec->size()); - EXPECT_EQ(sdp_id, *(vec->at(0).Get<common::UUID>())); - EXPECT_EQ(group_id, *(vec->at(1).Get<common::UUID>())); + EXPECT_EQ(sdp_id, *(vec->at(0).Get<UUID>())); + EXPECT_EQ(group_id, *(vec->at(1).Get<UUID>())); record.RemoveAttribute(kServiceId); @@ -99,23 +98,23 @@ TEST_F(SDP_ServiceRecordTest, FindUUID) { ServiceRecord record; DataElement elem; - elem.Set(common::UUID(uint16_t(0xfeaa))); + elem.Set(UUID(uint16_t(0xfeaa))); record.SetAttribute(0xb001, std::move(elem)); - elem.Set(common::UUID(uint16_t(0xfeed))); + elem.Set(UUID(uint16_t(0xfeed))); record.SetAttribute(0xb002, std::move(elem)); - elem.Set(common::UUID(uint16_t(0xfeec))); + elem.Set(UUID(uint16_t(0xfeec))); record.SetAttribute(0xb003, std::move(elem)); - std::unordered_set<common::UUID> search_pattern; - search_pattern.insert(common::UUID(uint16_t(0xfeaa))); + std::unordered_set<UUID> search_pattern; + search_pattern.insert(UUID(uint16_t(0xfeaa))); EXPECT_TRUE(record.FindUUID(search_pattern)); - search_pattern.insert(common::UUID(uint16_t(0xfeec))); + search_pattern.insert(UUID(uint16_t(0xfeec))); EXPECT_TRUE(record.FindUUID(search_pattern)); - search_pattern.insert(common::UUID(uint16_t(0xfeeb))); + search_pattern.insert(UUID(uint16_t(0xfeeb))); EXPECT_FALSE(record.FindUUID(search_pattern)); } @@ -132,7 +131,7 @@ TEST_F(SDP_ServiceRecordTest, AddProtocolDescriptor) { protocol::kL2CAP, std::move(psm)); // clang-format off - auto expected = common::CreateStaticByteBuffer( + auto expected = CreateStaticByteBuffer( 0x35, 0x08, // Data Element Sequence (8 bytes) 0x35, 0x06, // Data Element Sequence (6 bytes) 0x19, // UUID (16 bits) @@ -145,7 +144,7 @@ TEST_F(SDP_ServiceRecordTest, AddProtocolDescriptor) { EXPECT_TRUE(record.HasAttribute(kProtocolDescriptorList)); const DataElement& val = record.GetAttribute(kProtocolDescriptorList); - common::DynamicByteBuffer block(val.WriteSize()); + DynamicByteBuffer block(val.WriteSize()); val.Write(&block); EXPECT_EQ(expected.size(), block.size()); @@ -157,7 +156,7 @@ TEST_F(SDP_ServiceRecordTest, AddProtocolDescriptor) { EXPECT_TRUE(record.HasAttribute(kProtocolDescriptorList)); // clang-format off - auto expected_sdp = common::CreateStaticByteBuffer( + auto expected_sdp = CreateStaticByteBuffer( 0x35, 0x0D, // Data Element Sequence (13 bytes) 0x35, 0x06, // Data Element Sequence (6 bytes) 0x19, // UUID (16 bits) @@ -171,7 +170,7 @@ TEST_F(SDP_ServiceRecordTest, AddProtocolDescriptor) { // clang-format on const DataElement& pdl = record.GetAttribute(kProtocolDescriptorList); - common::DynamicByteBuffer block_sdp(pdl.WriteSize()); + DynamicByteBuffer block_sdp(pdl.WriteSize()); pdl.Write(&block_sdp); EXPECT_EQ(expected_sdp.size(), block_sdp.size()); @@ -182,7 +181,7 @@ TEST_F(SDP_ServiceRecordTest, AddProtocolDescriptor) { EXPECT_TRUE(record.HasAttribute(kAdditionalProtocolDescriptorList)); // clang-format off - auto expected_addl = common::CreateStaticByteBuffer( + auto expected_addl = CreateStaticByteBuffer( 0x35, 0x07, // Data Element Sequence (AdditionalProtocolDescriptorLists) 0x35, 0x05, // Data Element Sequence (ProtocolDescriptorList 1) 0x35, 0x03, // Data Element Sequence Protocol List 1 Descriptor 0 @@ -193,7 +192,7 @@ TEST_F(SDP_ServiceRecordTest, AddProtocolDescriptor) { const DataElement& apdl = record.GetAttribute(kAdditionalProtocolDescriptorList); - common::DynamicByteBuffer block_addl(apdl.WriteSize()); + DynamicByteBuffer block_addl(apdl.WriteSize()); apdl.Write(&block_addl); EXPECT_EQ(expected_addl.size(), block_addl.size()); @@ -213,7 +212,7 @@ TEST_F(SDP_ServiceRecordTest, AddProfile) { EXPECT_TRUE(record.HasAttribute(kBluetoothProfileDescriptorList)); // clang-format off - auto expected = common::CreateStaticByteBuffer( + auto expected = CreateStaticByteBuffer( 0x35, 0x08, // Data Element Sequence (8 bytes) 0x35, 0x06, // Data Element Sequence (6 bytes) 0x19, // UUID (16 bits) @@ -224,7 +223,7 @@ TEST_F(SDP_ServiceRecordTest, AddProfile) { // clang-format on const DataElement& val = record.GetAttribute(kBluetoothProfileDescriptorList); - common::DynamicByteBuffer block(val.WriteSize()); + DynamicByteBuffer block(val.WriteSize()); val.Write(&block); EXPECT_EQ(expected.size(), block.size()); @@ -233,7 +232,7 @@ TEST_F(SDP_ServiceRecordTest, AddProfile) { record.AddProfile(profile::kDialupNetworking, 4, 5); // clang-format off - auto expected_dun = common::CreateStaticByteBuffer( + auto expected_dun = CreateStaticByteBuffer( 0x35, 0x10, // Data Element Sequence (16 bytes) 0x35, 0x06, // Data Element Sequence (6 bytes) 0x19, // UUID (16 bits) @@ -250,7 +249,7 @@ TEST_F(SDP_ServiceRecordTest, AddProfile) { const DataElement& val_dun = record.GetAttribute(kBluetoothProfileDescriptorList); - common::DynamicByteBuffer block_dun(val_dun.WriteSize()); + DynamicByteBuffer block_dun(val_dun.WriteSize()); val_dun.Write(&block_dun); EXPECT_EQ(expected_dun.size(), block_dun.size()); diff --git a/src/connectivity/bluetooth/core/bt-host/sdp/status.cc b/src/connectivity/bluetooth/core/bt-host/sdp/status.cc index 19c192e77bfd935ea93aac087cd59c136a7025e9..1b7bf419f151ca01899a661dd720abc3ed3535ea 100644 --- a/src/connectivity/bluetooth/core/bt-host/sdp/status.cc +++ b/src/connectivity/bluetooth/core/bt-host/sdp/status.cc @@ -5,7 +5,6 @@ #include "status.h" namespace bt { -namespace common { // static std::string ProtocolErrorTraits<sdp::ErrorCode>::ToString( @@ -15,8 +14,6 @@ std::string ProtocolErrorTraits<sdp::ErrorCode>::ToString( static_cast<unsigned int>(ecode)); } -} // namespace common - namespace sdp { std::string ErrorCodeToString(ErrorCode code) { @@ -41,9 +38,9 @@ std::string ErrorCodeToString(ErrorCode code) { return "unknown status"; } -using Base = common::Status<ErrorCode>; +using Base = bt::Status<ErrorCode>; -Status::Status(common::HostError ecode) : Base(ecode) {} +Status::Status(HostError ecode) : Base(ecode) {} Status::Status(ErrorCode proto_code) : Base(proto_code) {} diff --git a/src/connectivity/bluetooth/core/bt-host/sdp/status.h b/src/connectivity/bluetooth/core/bt-host/sdp/status.h index 5fd35981ee0017b2d91035622b4ab000def28a61..a100c436d74b66d0b146f8afbe3f52c5a687cbdf 100644 --- a/src/connectivity/bluetooth/core/bt-host/sdp/status.h +++ b/src/connectivity/bluetooth/core/bt-host/sdp/status.h @@ -8,7 +8,7 @@ #include "src/connectivity/bluetooth/core/bt-host/common/status.h" #include "src/connectivity/bluetooth/core/bt-host/sdp/sdp.h" -// This file provides a common::Status template specialization for sdp::Status +// This file provides a Status template specialization for sdp::Status // // EXAMPLES: // @@ -16,28 +16,25 @@ // sdp::Status status; // // // 2. Status containing a host-internal error: -// sdp::Status status(common::HostError::kTimedOut); +// sdp::Status status(HostError::kTimedOut); // // // 3. Status containing SDP status code: // sdp::Status status(sdp::ErrorCode::kInvalidSize); namespace bt { -namespace common { template <> struct ProtocolErrorTraits<bt::sdp::ErrorCode> { static std::string ToString(bt::sdp::ErrorCode ecode); }; -} // namespace common - namespace sdp { std::string ErrorCodeToString(ErrorCode code); -class Status : public common::Status<ErrorCode> { +class Status : public bt::Status<ErrorCode> { public: - explicit Status(common::HostError ecode = common::HostError::kNoError); + explicit Status(HostError ecode = HostError::kNoError); explicit Status(sdp::ErrorCode proto_code); }; diff --git a/src/connectivity/bluetooth/core/bt-host/sm/bearer.cc b/src/connectivity/bluetooth/core/bt-host/sm/bearer.cc index e610910dd78d33ad0ed6f774a1f4bc6f30789c40..6f1f016bbfecd8496cf69f22a455e06f614dd63a 100644 --- a/src/connectivity/bluetooth/core/bt-host/sm/bearer.cc +++ b/src/connectivity/bluetooth/core/bt-host/sm/bearer.cc @@ -9,23 +9,16 @@ #include "src/connectivity/bluetooth/core/bt-host/common/log.h" #include "src/connectivity/bluetooth/core/bt-host/common/slab_allocator.h" - #include "src/lib/fxl/strings/string_printf.h" - #include "util.h" namespace bt { -using common::ByteBuffer; -using common::DeviceAddress; -using common::HostError; -using common::UInt128; - namespace sm { namespace { -common::MutableByteBufferPtr NewPDU(size_t param_size) { - auto pdu = common::NewSlabBuffer(sizeof(Header) + param_size); +MutableByteBufferPtr NewPDU(size_t param_size) { + auto pdu = NewSlabBuffer(sizeof(Header) + param_size); if (!pdu) { bt_log(TRACE, "sm", "out of memory"); } @@ -115,7 +108,7 @@ bool Bearer::InitiateFeatureExchange() { return true; } -bool Bearer::SendConfirmValue(const common::UInt128& confirm) { +bool Bearer::SendConfirmValue(const UInt128& confirm) { if (!pairing_started()) { bt_log(TRACE, "sm", "not pairing!"); return false; @@ -140,7 +133,7 @@ bool Bearer::SendConfirmValue(const common::UInt128& confirm) { return true; } -bool Bearer::SendRandomValue(const common::UInt128& random) { +bool Bearer::SendRandomValue(const UInt128& random) { if (!pairing_started()) { bt_log(TRACE, "sm", "not pairing!"); return false; @@ -698,7 +691,7 @@ void Bearer::OnChannelClosed() { } } -void Bearer::OnRxBFrame(common::ByteBufferPtr sdu) { +void Bearer::OnRxBFrame(ByteBufferPtr sdu) { ZX_DEBUG_ASSERT(sdu); uint8_t length = sdu->size(); if (length < sizeof(Code)) { diff --git a/src/connectivity/bluetooth/core/bt-host/sm/bearer.h b/src/connectivity/bluetooth/core/bt-host/sm/bearer.h index 59f2ae087bba184b32b23ec923a888f46b6efad8..bb932a666b43ba00424207a0c691c6c6be614182 100644 --- a/src/connectivity/bluetooth/core/bt-host/sm/bearer.h +++ b/src/connectivity/bluetooth/core/bt-host/sm/bearer.h @@ -67,19 +67,19 @@ class Bearer final { // The Pairing Feature Exchange procedures will fail if no feature exchange // callback is assigned. virtual void OnFeatureExchange(const PairingFeatures& features, - const common::ByteBuffer& preq, - const common::ByteBuffer& pres) = 0; + const ByteBuffer& preq, + const ByteBuffer& pres) = 0; // Called when a "confirm value" is received from the peer during Legacy // Pairing Phase 2. - virtual void OnPairingConfirm(const common::UInt128& confirm) = 0; + virtual void OnPairingConfirm(const UInt128& confirm) = 0; // Called when a "random value" is received from the peer during Legacy // Pairing Phase 2. - virtual void OnPairingRandom(const common::UInt128& random) = 0; + virtual void OnPairingRandom(const UInt128& random) = 0; // Called when a "Long Term Key" is received from the peer. - virtual void OnLongTermKey(const common::UInt128& ltk) = 0; + virtual void OnLongTermKey(const UInt128& ltk) = 0; // Called when EDiv and Rand values are received from the peer during Legacy // Pairing Phase 3. @@ -87,11 +87,11 @@ class Bearer final { // Called when the "Identity Resolving Key" is received from the peer during // Phase 3. - virtual void OnIdentityResolvingKey(const common::UInt128& irk) = 0; + virtual void OnIdentityResolvingKey(const UInt128& irk) = 0; // Called when the "Identity Address" is received from the peer during Phase // 3. - virtual void OnIdentityAddress(const common::DeviceAddress& address) = 0; + virtual void OnIdentityAddress(const DeviceAddress& address) = 0; // Called when a "Security Request" is received from the peer (see Vol 3, // Part H, 2.4.6) (Note: A device in the link layer master role is not @@ -144,11 +144,11 @@ class Bearer final { // Sends a "confirm value" for Phase 2 of legacy pairing. Returns false if // feature exchange is in progress or pairing hasn't been started. - bool SendConfirmValue(const common::UInt128& confirm); + bool SendConfirmValue(const UInt128& confirm); // Sends a "random value" for Phase 2 of legacy pairing. Returns false if // feature exchange is in progress or pairing hasn't been started. - bool SendRandomValue(const common::UInt128& random); + bool SendRandomValue(const UInt128& random); // Sends the encryption information during the key distribution phase // (Phase 3) of legacy pairing. Returns false if the command cannot be sent. @@ -215,7 +215,7 @@ class Bearer final { // l2cap::Channel callbacks: void OnChannelClosed(); - void OnRxBFrame(common::ByteBufferPtr sdu); + void OnRxBFrame(ByteBufferPtr sdu); l2cap::ScopedChannel chan_; hci::Connection::Role role_; @@ -230,7 +230,7 @@ class Bearer final { // We use this buffer to store pairing request and response PDUs as they are // needed to complete the feature exchange (i.e. the "preq" and "pres" // payloads needed for Phase 2 (see Vol 3, Part H, 2.2.3 for example). - common::StaticByteBuffer<sizeof(Header) + sizeof(PairingRequestParams)> + StaticByteBuffer<sizeof(Header) + sizeof(PairingRequestParams)> pairing_payload_buffer_; // Task used to drive the "SMP Timeout" (Vol 3, Part H, 3.4). The timer is diff --git a/src/connectivity/bluetooth/core/bt-host/sm/bearer_unittest.cc b/src/connectivity/bluetooth/core/bt-host/sm/bearer_unittest.cc index bebbbfdd2752bd446078362713e949fd28d9495d..37a88cbfdecef4e349ac64a92989c13c6145f4ac 100644 --- a/src/connectivity/bluetooth/core/bt-host/sm/bearer_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/sm/bearer_unittest.cc @@ -13,16 +13,6 @@ namespace bt { namespace sm { namespace { -using common::BufferView; -using common::ByteBuffer; -using common::ContainersEqual; -using common::CreateStaticByteBuffer; -using common::DeviceAddress; -using common::DynamicByteBuffer; -using common::HostError; -using common::StaticByteBuffer; -using common::UInt128; - class SMP_BearerTest : public l2cap::testing::FakeChannelTest, public Bearer::Listener { public: diff --git a/src/connectivity/bluetooth/core/bt-host/sm/packet.cc b/src/connectivity/bluetooth/core/bt-host/sm/packet.cc index 9b96ad15a835eadbce1a2ae2e8b9d924c1bd44b7..8bd0bebc7f4e352ed085f03a2a36f2271afafc0e 100644 --- a/src/connectivity/bluetooth/core/bt-host/sm/packet.cc +++ b/src/connectivity/bluetooth/core/bt-host/sm/packet.cc @@ -7,12 +7,11 @@ namespace bt { namespace sm { -PacketReader::PacketReader(const common::ByteBuffer* buffer) - : common::PacketView<Header>(buffer, buffer->size() - sizeof(Header)) {} +PacketReader::PacketReader(const ByteBuffer* buffer) + : PacketView<Header>(buffer, buffer->size() - sizeof(Header)) {} -PacketWriter::PacketWriter(Code code, common::MutableByteBuffer* buffer) - : common::MutablePacketView<Header>(buffer, - buffer->size() - sizeof(Header)) { +PacketWriter::PacketWriter(Code code, MutableByteBuffer* buffer) + : MutablePacketView<Header>(buffer, buffer->size() - sizeof(Header)) { mutable_header()->code = code; } diff --git a/src/connectivity/bluetooth/core/bt-host/sm/packet.h b/src/connectivity/bluetooth/core/bt-host/sm/packet.h index 7748cdaffe9e8e33962ec19f57cdf194c19cc5f7..bab3a7afa0e98a33c9f280b734c029ac00f61c89 100644 --- a/src/connectivity/bluetooth/core/bt-host/sm/packet.h +++ b/src/connectivity/bluetooth/core/bt-host/sm/packet.h @@ -14,16 +14,16 @@ namespace sm { // Utilities for processing SMP packets. -class PacketReader : public common::PacketView<Header> { +class PacketReader : public PacketView<Header> { public: - explicit PacketReader(const common::ByteBuffer* buffer); + explicit PacketReader(const ByteBuffer* buffer); inline Code code() const { return header().code; } }; -class PacketWriter : public common::MutablePacketView<Header> { +class PacketWriter : public MutablePacketView<Header> { public: // Constructor writes |code| into |buffer|. - PacketWriter(Code code, common::MutableByteBuffer* buffer); + PacketWriter(Code code, MutableByteBuffer* buffer); }; } // namespace sm diff --git a/src/connectivity/bluetooth/core/bt-host/sm/pairing_state.cc b/src/connectivity/bluetooth/core/bt-host/sm/pairing_state.cc index a614ef6811c07a24123e3bc38ec2e13b25bd9e27..e2845a59561dd0d43a5a90efa0e85507fb65171b 100644 --- a/src/connectivity/bluetooth/core/bt-host/sm/pairing_state.cc +++ b/src/connectivity/bluetooth/core/bt-host/sm/pairing_state.cc @@ -6,17 +6,10 @@ #include "src/connectivity/bluetooth/core/bt-host/common/log.h" #include "src/connectivity/bluetooth/core/bt-host/common/random.h" - #include "util.h" namespace bt { -using common::ByteBuffer; -using common::DeviceAddress; -using common::HostError; -using common::MutableBufferView; -using common::UInt128; - namespace sm { namespace { @@ -279,7 +272,7 @@ void PairingState::BeginLegacyPairingPhase2(const ByteBuffer& preq, // We have TK so we can generate the confirm value now. const DeviceAddress *ia, *ra; self->LEPairingAddresses(&ia, &ra); - state->local_rand = common::RandomUInt128(); + state->local_rand = RandomUInt128(); util::C1(state->tk, state->local_rand, state->preq, state->pres, *ia, *ra, &state->local_confirm); @@ -355,8 +348,7 @@ bool PairingState::SendLocalKeys() { if (legacy_state_->ShouldSendLTK()) { // Generate completely random values for LTK, EDiv, and Rand. - hci::LinkKey key(common::RandomUInt128(), common::Random<uint64_t>(), - common::Random<uint16_t>()); + hci::LinkKey key(RandomUInt128(), Random<uint64_t>(), Random<uint16_t>()); // Assign the link key to make it available when the master initiates // encryption. The security properties of the LTK are based on the current @@ -655,7 +647,7 @@ void PairingState::OnPairingRandom(const UInt128& random) { } } -void PairingState::OnLongTermKey(const common::UInt128& ltk) { +void PairingState::OnLongTermKey(const UInt128& ltk) { if (!legacy_state_) { bt_log(TRACE, "sm", "ignoring LTK received while not in legacy pairing"); return; @@ -736,7 +728,7 @@ void PairingState::OnMasterIdentification(uint16_t ediv, uint64_t random) { OnExpectedKeyReceived(); } -void PairingState::OnIdentityResolvingKey(const common::UInt128& irk) { +void PairingState::OnIdentityResolvingKey(const UInt128& irk) { if (!legacy_state_) { bt_log(TRACE, "sm", "ignoring IRK received while not in legacy pairing!"); return; @@ -770,8 +762,7 @@ void PairingState::OnIdentityResolvingKey(const common::UInt128& irk) { // Wait to receive identity address } -void PairingState::OnIdentityAddress( - const common::DeviceAddress& identity_address) { +void PairingState::OnIdentityAddress(const DeviceAddress& identity_address) { if (!legacy_state_) { bt_log(TRACE, "sm", "ignoring identity address received while not in legacy pairing"); diff --git a/src/connectivity/bluetooth/core/bt-host/sm/pairing_state.h b/src/connectivity/bluetooth/core/bt-host/sm/pairing_state.h index 64afe2841a220a7695ecf5cdf576817fa36b5b15..b1cff4726f861e413c98f70a9ea13f8facfbef90 100644 --- a/src/connectivity/bluetooth/core/bt-host/sm/pairing_state.h +++ b/src/connectivity/bluetooth/core/bt-host/sm/pairing_state.h @@ -198,21 +198,21 @@ class PairingState final : public Bearer::Listener { bool has_peer_rand; bool sent_local_confirm; bool sent_local_rand; - common::UInt128 tk; - common::UInt128 local_confirm; - common::UInt128 peer_confirm; - common::UInt128 local_rand; - common::UInt128 peer_rand; - common::StaticByteBuffer<kPairingRequestSize> preq; - common::StaticByteBuffer<kPairingRequestSize> pres; + UInt128 tk; + UInt128 local_confirm; + UInt128 peer_confirm; + UInt128 local_rand; + UInt128 peer_rand; + StaticByteBuffer<kPairingRequestSize> preq; + StaticByteBuffer<kPairingRequestSize> pres; // Data from the peer tracked during Phase 3. Parts of LTK are received in // separate events. bool has_ltk; bool has_irk; - common::UInt128 ltk_bytes; // LTK without ediv/rand - common::UInt128 irk; - common::DeviceAddress identity_address; + UInt128 ltk_bytes; // LTK without ediv/rand + UInt128 irk; + DeviceAddress identity_address; }; // Represents a pending request to update the security level. @@ -243,8 +243,7 @@ class PairingState final : public Bearer::Listener { // 2. Generate the local confirm/rand values. // 3. If initiator, start the exchange, otherwise wait for the peer to send // its confirm value. - void BeginLegacyPairingPhase2(const common::ByteBuffer& preq, - const common::ByteBuffer& pres); + void BeginLegacyPairingPhase2(const ByteBuffer& preq, const ByteBuffer& pres); void LegacySendConfirmValue(); void LegacySendRandomValue(); @@ -269,14 +268,14 @@ class PairingState final : public Bearer::Listener { // Bearer::Listener overrides: void OnPairingFailed(Status status) override; void OnFeatureExchange(const PairingFeatures& features, - const common::ByteBuffer& preq, - const common::ByteBuffer& pres) override; - void OnPairingConfirm(const common::UInt128& confirm) override; - void OnPairingRandom(const common::UInt128& random) override; - void OnLongTermKey(const common::UInt128& ltk) override; + const ByteBuffer& preq, + const ByteBuffer& pres) override; + void OnPairingConfirm(const UInt128& confirm) override; + void OnPairingRandom(const UInt128& random) override; + void OnLongTermKey(const UInt128& ltk) override; void OnMasterIdentification(uint16_t ediv, uint64_t random) override; - void OnIdentityResolvingKey(const common::UInt128& irk) override; - void OnIdentityAddress(const common::DeviceAddress& address) override; + void OnIdentityResolvingKey(const UInt128& irk) override; + void OnIdentityAddress(const DeviceAddress& address) override; void OnSecurityRequest(AuthReqField auth_req) override; bool HasIdentityInformation() override; @@ -291,8 +290,8 @@ class PairingState final : public Bearer::Listener { // Returns pointers to the initiator and responder addresses. This can be // called after pairing Phase 1. - void LEPairingAddresses(const common::DeviceAddress** out_initiator, - const common::DeviceAddress** out_responder); + void LEPairingAddresses(const DeviceAddress** out_initiator, + const DeviceAddress** out_responder); // The ID that will be assigned to the next pairing state. unsigned int next_pairing_id_; diff --git a/src/connectivity/bluetooth/core/bt-host/sm/pairing_state_unittest.cc b/src/connectivity/bluetooth/core/bt-host/sm/pairing_state_unittest.cc index d0e36b198ac227631655eff228cc6cf6beb3cc22..80059796caf015e3d0fd9417013422d1ed978673 100644 --- a/src/connectivity/bluetooth/core/bt-host/sm/pairing_state_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/sm/pairing_state_unittest.cc @@ -14,11 +14,6 @@ namespace bt { -using common::ByteBuffer; -using common::DeviceAddress; -using common::StaticByteBuffer; -using common::UInt128; - namespace sm { namespace { @@ -150,11 +145,10 @@ class SMP_PairingStateTest : public l2cap::testing::FakeChannelTest, case kIdentityAddressInformation: { const auto& params = reader.payload<IdentityAddressInformationParams>(); id_addr_info_count_++; - id_addr_info_ = - common::DeviceAddress(params.type == AddressType::kStaticRandom - ? DeviceAddress::Type::kLERandom - : DeviceAddress::Type::kLEPublic, - params.bd_addr); + id_addr_info_ = DeviceAddress(params.type == AddressType::kStaticRandom + ? DeviceAddress::Type::kLERandom + : DeviceAddress::Type::kLEPublic, + params.bd_addr); break; } default: @@ -425,7 +419,7 @@ class SMP_InitiatorPairingTest : public SMP_PairingStateTest { UInt128* out_random, uint32_t tk = 0) { ZX_DEBUG_ASSERT(out_confirm); ZX_DEBUG_ASSERT(out_random); - *out_random = common::RandomUInt128(); + *out_random = RandomUInt128(); GenerateConfirmValue(*out_random, out_confirm, false /* peer_initiator */, tk); } @@ -2087,7 +2081,7 @@ TEST_F(SMP_ResponderPairingTest, // Still waiting for initiator's keys. EXPECT_EQ(0, pairing_data_callback_count()); - const auto kIrk = common::RandomUInt128(); + const auto kIrk = RandomUInt128(); ReceiveIdentityResolvingKey(kIrk); ReceiveIdentityAddress(kPeerAddr); RunLoopUntilIdle(); @@ -2136,7 +2130,7 @@ TEST_F(SMP_ResponderPairingTest, // Still waiting for master's keys. EXPECT_EQ(0, pairing_data_callback_count()); - const auto kIrk = common::RandomUInt128(); + const auto kIrk = RandomUInt128(); ReceiveIdentityResolvingKey(kIrk); ReceiveIdentityAddress(kPeerAddr); RunLoopUntilIdle(); diff --git a/src/connectivity/bluetooth/core/bt-host/sm/smp.h b/src/connectivity/bluetooth/core/bt-host/sm/smp.h index 95aea2098126cac06702072696e0f49a9ccf2b7d..9fb6b71f970b61d3f0df23f203c398148f40c873 100644 --- a/src/connectivity/bluetooth/core/bt-host/sm/smp.h +++ b/src/connectivity/bluetooth/core/bt-host/sm/smp.h @@ -5,13 +5,13 @@ #ifndef SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_SM_SMP_H_ #define SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_SM_SMP_H_ -#include <cstdint> - #include <zircon/compiler.h> +#include <cstdint> + +#include "lib/zx/time.h" #include "src/connectivity/bluetooth/core/bt-host/common/device_address.h" #include "src/connectivity/bluetooth/core/bt-host/common/uint128.h" -#include "lib/zx/time.h" // This file defines constants that are used by the Security Manager Protocol // (SMP) that operates over the L2CAP SMP channel. @@ -222,12 +222,12 @@ using PairingResponseParams = PairingRequestParams; // ====================================== // Pairing Confirm (Vol 3, Part H, 3.5.3) constexpr Code kPairingConfirm = 0x03; -using PairingConfirmValue = common::UInt128; +using PairingConfirmValue = UInt128; // ===================================== // Pairing Random (Vol 3, Part H, 3.5.4) constexpr Code kPairingRandom = 0x04; -using PairingRandomValue = common::UInt128; +using PairingRandomValue = UInt128; // ===================================== // Pairing Failed (Vol 3, Part H, 3.5.5) @@ -237,7 +237,7 @@ using PairingFailedParams = ErrorCode; // ============================================= // Encryption Information (LE Legacy Pairing only; Vol 3, Part H, 3.6.2) constexpr Code kEncryptionInformation = 0x06; -using EncryptionInformationParams = common::UInt128; +using EncryptionInformationParams = UInt128; // ==================================================================== // Master Identification (LE Legacy Pairing only; Vol 3, Part H, 3.6.3) @@ -250,20 +250,20 @@ struct MasterIdentificationParams { // =========================================== // Identity Information (Vol 3, Part H, 3.6.4) constexpr Code kIdentityInformation = 0x08; -using IRK = common::UInt128; +using IRK = UInt128; // =================================================== // Identity Address Information (Vol 3, Part H, 3.6.5) constexpr Code kIdentityAddressInformation = 0x09; struct IdentityAddressInformationParams { AddressType type; - common::DeviceAddressBytes bd_addr; + DeviceAddressBytes bd_addr; } __PACKED; // ========================================== // Signing Information (Vol 3, Part H, 3.6.6) constexpr Code kSigningInformation = 0x0A; -using CSRK = common::UInt128; +using CSRK = UInt128; // ======================================= // Security Request (Vol 3, Part H, 3.6.7) @@ -282,7 +282,7 @@ struct PairingPublicKeyParams { // ====================================================================== // Pairing DHKey Check (LE Secure Connections only; Vol 3, Part H, 3.5.7) constexpr Code kPairingDHKeyCheck = 0x0D; -using PairingDHKeyCheckValueE = common::UInt128; +using PairingDHKeyCheckValueE = UInt128; // ============================================ // Keypress Notification (Vol 3, Part H, 3.5.8) diff --git a/src/connectivity/bluetooth/core/bt-host/sm/status.cc b/src/connectivity/bluetooth/core/bt-host/sm/status.cc index bc1c7824f0b9ae9f8832cd5ef3a2207bfbf30238..bb5ff53dfc0e2fafafab17df66dde6d299aab861 100644 --- a/src/connectivity/bluetooth/core/bt-host/sm/status.cc +++ b/src/connectivity/bluetooth/core/bt-host/sm/status.cc @@ -5,7 +5,6 @@ #include "status.h" namespace bt { -namespace common { namespace { std::string ErrorToString(sm::ErrorCode ecode) { @@ -52,5 +51,4 @@ std::string ProtocolErrorTraits<sm::ErrorCode>::ToString(sm::ErrorCode ecode) { static_cast<unsigned int>(ecode)); } -} // namespace common } // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/sm/status.h b/src/connectivity/bluetooth/core/bt-host/sm/status.h index d092c7b3dee1aecd5ee189096fe16ae2591616bc..91ede95355df69d529475a57dc5ee57cb17bed87 100644 --- a/src/connectivity/bluetooth/core/bt-host/sm/status.h +++ b/src/connectivity/bluetooth/core/bt-host/sm/status.h @@ -11,18 +11,15 @@ #include "src/connectivity/bluetooth/core/bt-host/sm/smp.h" namespace bt { -namespace common { template <> struct ProtocolErrorTraits<sm::ErrorCode> { static std::string ToString(sm::ErrorCode ecode); }; -} // namespace common - namespace sm { -using Status = common::Status<ErrorCode>; +using Status = Status<ErrorCode>; using StatusCallback = fit::function<void(Status)>; diff --git a/src/connectivity/bluetooth/core/bt-host/sm/types.cc b/src/connectivity/bluetooth/core/bt-host/sm/types.cc index e3eb55206d58ec2b71c791c0c4deb0b777a43751..976e93a1b9a37a008419878f6b7b3339a7db7228 100644 --- a/src/connectivity/bluetooth/core/bt-host/sm/types.cc +++ b/src/connectivity/bluetooth/core/bt-host/sm/types.cc @@ -85,7 +85,7 @@ std::string SecurityProperties::ToString() const { LTK::LTK(const SecurityProperties& security, const hci::LinkKey& key) : security_(security), key_(key) {} -Key::Key(const SecurityProperties& security, const common::UInt128& value) +Key::Key(const SecurityProperties& security, const UInt128& value) : security_(security), value_(value) {} } // namespace sm diff --git a/src/connectivity/bluetooth/core/bt-host/sm/types.h b/src/connectivity/bluetooth/core/bt-host/sm/types.h index 218e2a52fa1aba02c50a440111cb2bcf8eb1bfcb..b24dc4f7badd5798572798a749c81a67fe88b033 100644 --- a/src/connectivity/bluetooth/core/bt-host/sm/types.h +++ b/src/connectivity/bluetooth/core/bt-host/sm/types.h @@ -121,10 +121,10 @@ class LTK final { class Key final { public: Key() = default; - Key(const SecurityProperties& security, const common::UInt128& value); + Key(const SecurityProperties& security, const UInt128& value); const SecurityProperties& security() const { return security_; } - const common::UInt128& value() const { return value_; } + const UInt128& value() const { return value_; } bool operator==(const Key& other) const { return security() == other.security() && value() == other.value(); @@ -132,13 +132,13 @@ class Key final { private: SecurityProperties security_; - common::UInt128 value_; + UInt128 value_; }; // Container for LE pairing data. struct PairingData final { // The identity address. - std::optional<common::DeviceAddress> identity_address; + std::optional<DeviceAddress> identity_address; // The long term key used for link encryption. std::optional<sm::LTK> ltk; @@ -157,8 +157,8 @@ struct PairingData final { // Container for identity information for distribution. struct IdentityInfo { - common::UInt128 irk; - common::DeviceAddress address; + UInt128 irk; + DeviceAddress address; }; } // namespace sm diff --git a/src/connectivity/bluetooth/core/bt-host/sm/util.cc b/src/connectivity/bluetooth/core/bt-host/sm/util.cc index 5cf1cf19c6ad49a1ef0ecdf84b1419143a4e1aaf..d77bbbca89efc9d8a553103e2f9defe71c0485f1 100644 --- a/src/connectivity/bluetooth/core/bt-host/sm/util.cc +++ b/src/connectivity/bluetooth/core/bt-host/sm/util.cc @@ -11,16 +11,6 @@ namespace bt { -using common::BufferView; -using common::ByteBuffer; -using common::DeviceAddress; -using common::DeviceAddressBytes; -using common::MutableBufferView; -using common::StaticByteBuffer; -using common::UInt128; - -using common::kDeviceAddressSize; - namespace sm { namespace util { namespace { @@ -168,8 +158,8 @@ PairingMethod SelectPairingMethod(bool sec_conn, bool local_oob, bool peer_oob, return PairingMethod::kJustWorks; } -void Encrypt(const common::UInt128& key, const common::UInt128& plaintext_data, - common::UInt128* out_encrypted_data) { +void Encrypt(const UInt128& key, const UInt128& plaintext_data, + UInt128* out_encrypted_data) { // Swap the bytes since "the most significant octet of key corresponds to // key[0], the most significant octet of plaintextData corresponds to in[0] // and the most significant octet of encryptedData corresponds to out[0] using @@ -206,7 +196,7 @@ void C1(const UInt128& tk, const UInt128& rand, const ByteBuffer& preq, // Calculate p2 = padding || ia || ra BufferView ia = initiator_addr.value().bytes(); BufferView ra = responder_addr.value().bytes(); - std::memcpy(p2.data(), ra.data(), ra.size()); // Lowest 6 bytes + std::memcpy(p2.data(), ra.data(), ra.size()); // Lowest 6 bytes std::memcpy(p2.data() + ra.size(), ia.data(), ia.size()); // Next 6 bytes std::memset(p2.data() + ra.size() + ia.size(), 0, p2.size() - ra.size() - ia.size()); // Pad 0s for the remainder diff --git a/src/connectivity/bluetooth/core/bt-host/sm/util.h b/src/connectivity/bluetooth/core/bt-host/sm/util.h index a203584ad9df466df84000b751e03c7b7320271d..bd8bcf15de88d2b68fa5f2db40e61e5d881bf01d 100644 --- a/src/connectivity/bluetooth/core/bt-host/sm/util.h +++ b/src/connectivity/bluetooth/core/bt-host/sm/util.h @@ -36,8 +36,8 @@ PairingMethod SelectPairingMethod(bool secure_connections, bool local_oob, bool local_initiator); // Implements the "Security Function 'e'" defined in Vol 3, Part H, 2.2.1. -void Encrypt(const common::UInt128& key, const common::UInt128& plaintext_data, - common::UInt128* out_encrypted_data); +void Encrypt(const UInt128& key, const UInt128& plaintext_data, + UInt128* out_encrypted_data); // Implements the "Confirm Value Generation" or "c1" function for LE Legacy // Pairing described in Vol 3, Part H, 2.2.3. @@ -52,11 +52,9 @@ void Encrypt(const common::UInt128& key, const common::UInt128& plaintext_data, // the connection. // // The generated confirm value will be returned in |out_confirm_value|. -void C1(const common::UInt128& tk, const common::UInt128& rand, - const common::ByteBuffer& preq, const common::ByteBuffer& pres, - const common::DeviceAddress& initiator_addr, - const common::DeviceAddress& responder_addr, - common::UInt128* out_confirm_value); +void C1(const UInt128& tk, const UInt128& rand, const ByteBuffer& preq, + const ByteBuffer& pres, const DeviceAddress& initiator_addr, + const DeviceAddress& responder_addr, UInt128* out_confirm_value); // Implements the "Key Generation Function s1" to generate the STK for LE Legacy // Pairing described in Vol 3, Part H, 2.2.4. @@ -64,8 +62,8 @@ void C1(const common::UInt128& tk, const common::UInt128& rand, // |tk|: 128-bit TK value // |r1|: 128-bit random value generated by the responder. // |r2|: 128-bit random value generated by the initiator. -void S1(const common::UInt128& tk, const common::UInt128& r1, - const common::UInt128& r2, common::UInt128* out_stk); +void S1(const UInt128& tk, const UInt128& r1, const UInt128& r2, + UInt128* out_stk); // Implements the "Random Address Hash Function ah" to resolve RPAs. Described // in Vol 3, Part H, 222. @@ -74,19 +72,18 @@ void S1(const common::UInt128& tk, const common::UInt128& r1, // |r|: 24-bit random part of a RPA. // // Returns 24 bit hash value. -uint32_t Ah(const common::UInt128& k, uint32_t r); +uint32_t Ah(const UInt128& k, uint32_t r); // Returns true if the given |irk| can resolve the given |rpa| using the method // described in Vol 6, Part B, 1.3.2.3. -bool IrkCanResolveRpa(const common::UInt128& irk, - const common::DeviceAddress& rpa); +bool IrkCanResolveRpa(const UInt128& irk, const DeviceAddress& rpa); // Generates a RPA using the given IRK based on the method described in Vol 6, // Part B, 1.3.2.2. -common::DeviceAddress GenerateRpa(const common::UInt128& irk); +DeviceAddress GenerateRpa(const UInt128& irk); // Generates a static or non-resolvable private random device address. -common::DeviceAddress GenerateRandomAddress(bool is_static); +DeviceAddress GenerateRandomAddress(bool is_static); } // namespace util } // namespace sm diff --git a/src/connectivity/bluetooth/core/bt-host/sm/util_unittest.cc b/src/connectivity/bluetooth/core/bt-host/sm/util_unittest.cc index f3e10ee5e3ab0f4e69fe2c8cb3bcfdb772d33801..df581e0ad9b4a88d9e06ce4198ec7c9a7efbc940 100644 --- a/src/connectivity/bluetooth/core/bt-host/sm/util_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/sm/util_unittest.cc @@ -5,17 +5,10 @@ #include "util.h" #include "gtest/gtest.h" - #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" namespace bt { -using common::ContainersEqual; -using common::CreateStaticByteBuffer; -using common::DeviceAddress; -using common::RandomUInt128; -using common::UInt128; - namespace sm { namespace util { namespace { diff --git a/src/connectivity/bluetooth/core/bt-host/testing/fake_controller.cc b/src/connectivity/bluetooth/core/bt-host/testing/fake_controller.cc index 903d0ef69f96329b72b426b7087bd798d06255b5..77568c8eedad1fdcdec7be722db73b552c90a430 100644 --- a/src/connectivity/bluetooth/core/bt-host/testing/fake_controller.cc +++ b/src/connectivity/bluetooth/core/bt-host/testing/fake_controller.cc @@ -17,11 +17,6 @@ namespace bt { -using common::BufferView; -using common::ByteBuffer; -using common::DeviceAddress; -using common::StaticByteBuffer; - namespace testing { namespace { @@ -40,14 +35,14 @@ bool CheckBit(NUM_TYPE num_type, ENUM_TYPE bit) { return (num_type & static_cast<NUM_TYPE>(bit)); } -hci::LEPeerAddressType ToPeerAddrType(common::DeviceAddress::Type type) { +hci::LEPeerAddressType ToPeerAddrType(DeviceAddress::Type type) { hci::LEPeerAddressType result = hci::LEPeerAddressType::kAnonymous; switch (type) { - case common::DeviceAddress::Type::kLEPublic: + case DeviceAddress::Type::kLEPublic: result = hci::LEPeerAddressType::kPublic; break; - case common::DeviceAddress::Type::kLERandom: + case DeviceAddress::Type::kLERandom: result = hci::LEPeerAddressType::kRandom; break; default: @@ -240,7 +235,7 @@ void FakeController::SetLEConnectionParametersCallback( le_conn_params_cb_dispatcher_ = dispatcher; } -FakePeer* FakeController::FindByAddress(const common::DeviceAddress& addr) { +FakePeer* FakeController::FindByAddress(const DeviceAddress& addr) { for (auto& dev : peers_) { if (dev->address() == addr) return dev.get(); @@ -263,10 +258,10 @@ uint8_t FakeController::NextL2CAPCommandId() { void FakeController::RespondWithCommandComplete(hci::OpCode opcode, const ByteBuffer& params) { - common::DynamicByteBuffer buffer(sizeof(hci::CommandCompleteEventParams) + - params.size()); - common::MutablePacketView<hci::CommandCompleteEventParams> event( - &buffer, params.size()); + DynamicByteBuffer buffer(sizeof(hci::CommandCompleteEventParams) + + params.size()); + MutablePacketView<hci::CommandCompleteEventParams> event(&buffer, + params.size()); event.mutable_header()->num_hci_command_packets = settings_.num_hci_command_packets; @@ -285,8 +280,8 @@ void FakeController::RespondWithSuccess(hci::OpCode opcode) { void FakeController::RespondWithCommandStatus(hci::OpCode opcode, hci::StatusCode status) { - common::StaticByteBuffer<sizeof(hci::CommandStatusEventParams)> buffer; - common::MutablePacketView<hci::CommandStatusEventParams> event(&buffer); + StaticByteBuffer<sizeof(hci::CommandStatusEventParams)> buffer; + MutablePacketView<hci::CommandStatusEventParams> event(&buffer); event.mutable_header()->status = status; event.mutable_header()->num_hci_command_packets = @@ -298,8 +293,8 @@ void FakeController::RespondWithCommandStatus(hci::OpCode opcode, void FakeController::SendEvent(hci::EventCode event_code, const ByteBuffer& payload) { - common::DynamicByteBuffer buffer(sizeof(hci::EventHeader) + payload.size()); - common::MutablePacketView<hci::EventHeader> event(&buffer, payload.size()); + DynamicByteBuffer buffer(sizeof(hci::EventHeader) + payload.size()); + MutablePacketView<hci::EventHeader> event(&buffer, payload.size()); event.mutable_header()->event_code = event_code; event.mutable_header()->parameter_total_size = payload.size(); @@ -310,8 +305,7 @@ void FakeController::SendEvent(hci::EventCode event_code, void FakeController::SendLEMetaEvent(hci::EventCode subevent_code, const ByteBuffer& payload) { - common::DynamicByteBuffer buffer(sizeof(hci::LEMetaEventParams) + - payload.size()); + DynamicByteBuffer buffer(sizeof(hci::LEMetaEventParams) + payload.size()); buffer[0] = subevent_code; buffer.Write(payload, 1); @@ -322,8 +316,8 @@ void FakeController::SendACLPacket(hci::ConnectionHandle handle, const ByteBuffer& payload) { ZX_DEBUG_ASSERT(payload.size() <= hci::kMaxACLPayloadSize); - common::DynamicByteBuffer buffer(sizeof(hci::ACLDataHeader) + payload.size()); - common::MutablePacketView<hci::ACLDataHeader> acl(&buffer, payload.size()); + DynamicByteBuffer buffer(sizeof(hci::ACLDataHeader) + payload.size()); + MutablePacketView<hci::ACLDataHeader> acl(&buffer, payload.size()); acl.mutable_header()->handle_and_flags = htole16(handle); acl.mutable_header()->data_total_length = @@ -339,8 +333,8 @@ void FakeController::SendL2CAPBFrame(hci::ConnectionHandle handle, ZX_DEBUG_ASSERT(payload.size() <= hci::kMaxACLPayloadSize - sizeof(l2cap::BasicHeader)); - common::DynamicByteBuffer buffer(sizeof(l2cap::BasicHeader) + payload.size()); - common::MutablePacketView<l2cap::BasicHeader> bframe(&buffer, payload.size()); + DynamicByteBuffer buffer(sizeof(l2cap::BasicHeader) + payload.size()); + MutablePacketView<l2cap::BasicHeader> bframe(&buffer, payload.size()); bframe.mutable_header()->length = htole16(payload.size()); bframe.mutable_header()->channel_id = htole16(channel_id); @@ -352,10 +346,8 @@ void FakeController::SendL2CAPBFrame(hci::ConnectionHandle handle, void FakeController::SendL2CAPCFrame(hci::ConnectionHandle handle, bool is_le, l2cap::CommandCode code, uint8_t id, const ByteBuffer& payload) { - common::DynamicByteBuffer buffer(sizeof(l2cap::CommandHeader) + - payload.size()); - common::MutablePacketView<l2cap::CommandHeader> cframe(&buffer, - payload.size()); + DynamicByteBuffer buffer(sizeof(l2cap::CommandHeader) + payload.size()); + MutablePacketView<l2cap::CommandHeader> cframe(&buffer, payload.size()); cframe.mutable_header()->code = code; cframe.mutable_header()->id = id; @@ -382,7 +374,7 @@ void FakeController::SendNumberOfCompletedPacketsEvent( SendEvent(hci::kNumberOfCompletedPacketsEventCode, buffer); } -void FakeController::ConnectLowEnergy(const common::DeviceAddress& addr, +void FakeController::ConnectLowEnergy(const DeviceAddress& addr, hci::ConnectionRole role) { async::PostTask(dispatcher(), [addr, role, this] { FakePeer* dev = FindByAddress(addr); @@ -431,7 +423,7 @@ void FakeController::ConnectLowEnergy(const common::DeviceAddress& addr, } void FakeController::L2CAPConnectionParameterUpdate( - const common::DeviceAddress& addr, + const DeviceAddress& addr, const hci::LEPreferredConnectionParameters& params) { async::PostTask(dispatcher(), [addr, params, this] { FakePeer* dev = FindByAddress(addr); @@ -463,7 +455,7 @@ void FakeController::L2CAPConnectionParameterUpdate( }); } -void FakeController::Disconnect(const common::DeviceAddress& addr) { +void FakeController::Disconnect(const DeviceAddress& addr) { async::PostTask(dispatcher(), [addr, this] { FakePeer* dev = FindByAddress(addr); if (!dev || !dev->connected()) { @@ -559,7 +551,7 @@ void FakeController::NotifyAdvertisingState() { advertising_state_cb_.share()); } -void FakeController::NotifyConnectionState(const common::DeviceAddress& addr, +void FakeController::NotifyConnectionState(const DeviceAddress& addr, bool connected, bool canceled) { if (!conn_state_cb_) return; @@ -572,8 +564,7 @@ void FakeController::NotifyConnectionState(const common::DeviceAddress& addr, } void FakeController::NotifyLEConnectionParameters( - const common::DeviceAddress& addr, - const hci::LEConnectionParameters& params) { + const DeviceAddress& addr, const hci::LEConnectionParameters& params) { if (!le_conn_params_cb_) return; @@ -693,11 +684,11 @@ void FakeController::OnLECreateConnectionCommandReceived( return; } - common::DeviceAddress::Type addr_type = + DeviceAddress::Type addr_type = hci::AddressTypeFromHCI(params.peer_address_type); - ZX_DEBUG_ASSERT(addr_type != common::DeviceAddress::Type::kBREDR); + ZX_DEBUG_ASSERT(addr_type != DeviceAddress::Type::kBREDR); - const common::DeviceAddress peer_address(addr_type, params.peer_address); + const DeviceAddress peer_address(addr_type, params.peer_address); hci::StatusCode status = hci::StatusCode::kSuccess; // Find the peer that matches the requested address. @@ -863,7 +854,7 @@ void FakeController::OnDisconnectCommandReceived( } void FakeController::OnCommandPacketReceived( - const common::PacketView<hci::CommandHeader>& command_packet) { + const PacketView<hci::CommandHeader>& command_packet) { hci::OpCode opcode = le16toh(command_packet.header().opcode); if (MaybeRespondWithDefaultStatus(opcode)) return; @@ -907,8 +898,8 @@ void FakeController::OnCommandPacketReceived( } const auto& in_params = command_packet.payload<hci::LESetRandomAddressCommandParams>(); - le_random_address_ = common::DeviceAddress( - common::DeviceAddress::Type::kLERandom, in_params.random_address); + le_random_address_ = DeviceAddress(DeviceAddress::Type::kLERandom, + in_params.random_address); RespondWithSuccess(opcode); break; @@ -1043,8 +1034,7 @@ void FakeController::OnCommandPacketReceived( case hci::kReadLocalName: { hci::ReadLocalNameReturnParams params; params.status = hci::StatusCode::kSuccess; - auto mut_view = - common::MutableBufferView(params.local_name, hci::kMaxNameLength); + auto mut_view = MutableBufferView(params.local_name, hci::kMaxNameLength); mut_view.Write((uint8_t*)(local_name_.c_str()), hci::kMaxNameLength); RespondWithCommandComplete(hci::kReadLocalName, BufferView(¶ms, sizeof(params))); @@ -1091,7 +1081,7 @@ void FakeController::OnCommandPacketReceived( params.status = hci::StatusCode::kSuccess; params.inquiry_mode = inquiry_mode_; RespondWithCommandComplete(hci::kReadInquiryMode, - common::BufferView(¶ms, sizeof(params))); + BufferView(¶ms, sizeof(params))); break; } case hci::kWriteInquiryMode: { @@ -1129,7 +1119,7 @@ void FakeController::OnCommandPacketReceived( } RespondWithCommandComplete(hci::kReadSimplePairingMode, - common::BufferView(¶ms, sizeof(params))); + BufferView(¶ms, sizeof(params))); break; } case hci::kWriteSimplePairingMode: { @@ -1141,7 +1131,7 @@ void FakeController::OnCommandPacketReceived( hci::SimpleReturnParams params; params.status = hci::StatusCode::kInvalidHCICommandParameters; RespondWithCommandComplete(hci::kWriteSimplePairingMode, - common::BufferView(¶ms, sizeof(params))); + BufferView(¶ms, sizeof(params))); break; } @@ -1345,7 +1335,7 @@ void FakeController::OnCommandPacketReceived( hci::InquiryCompleteEventParams params; params.status = hci::kSuccess; SendEvent(hci::kInquiryCompleteEventCode, - common::BufferView(¶ms, sizeof(params))); + BufferView(¶ms, sizeof(params))); }, zx::msec(in_params.inquiry_length * 1280)); break; diff --git a/src/connectivity/bluetooth/core/bt-host/testing/fake_controller.h b/src/connectivity/bluetooth/core/bt-host/testing/fake_controller.h index 1f4d134f3c39a6e67ba43069e76ca349691ab56b..abcf9ba077ff900c9ab7b72e78a0abed2ff58369 100644 --- a/src/connectivity/bluetooth/core/bt-host/testing/fake_controller.h +++ b/src/connectivity/bluetooth/core/bt-host/testing/fake_controller.h @@ -61,7 +61,7 @@ class FakeController : public FakeControllerBase, uint64_t le_event_mask; // BD_ADDR (BR/EDR) or Public Device Address (LE) - common::DeviceAddress bd_addr; + DeviceAddress bd_addr; // Local supported features and commands. uint64_t lmp_features_page0; @@ -95,11 +95,9 @@ class FakeController : public FakeControllerBase, struct LEAdvertisingState final { LEAdvertisingState(); - common::BufferView advertised_view() const { - return common::BufferView(data, data_length); - } - common::BufferView scan_rsp_view() const { - return common::BufferView(scan_rsp_data, scan_rsp_length); + BufferView advertised_view() const { return BufferView(data, data_length); } + BufferView scan_rsp_view() const { + return BufferView(scan_rsp_data, scan_rsp_length); } bool enabled; @@ -118,7 +116,7 @@ class FakeController : public FakeControllerBase, LEConnectParams() = default; hci::LEOwnAddressType own_address_type; - common::DeviceAddress peer_address; + DeviceAddress peer_address; }; // Constructor initializes the controller with the minimal default settings @@ -147,7 +145,7 @@ class FakeController : public FakeControllerBase, return le_connect_params_; } - const std::optional<common::DeviceAddress>& le_random_address() const { + const std::optional<DeviceAddress>& le_random_address() const { return le_random_address_; } @@ -167,58 +165,55 @@ class FakeController : public FakeControllerBase, async_dispatcher_t* dispatcher); // Sets a callback to be invoked on connection events. - using ConnectionStateCallback = fit::function<void( - const common::DeviceAddress&, bool connected, bool canceled)>; + using ConnectionStateCallback = + fit::function<void(const DeviceAddress&, bool connected, bool canceled)>; void SetConnectionStateCallback(ConnectionStateCallback callback, async_dispatcher_t* dispatcher); // Sets a callback to be invoked when LE connection parameters are updated for // a fake device. using LEConnectionParametersCallback = fit::function<void( - const common::DeviceAddress&, const hci::LEConnectionParameters&)>; + const DeviceAddress&, const hci::LEConnectionParameters&)>; void SetLEConnectionParametersCallback( LEConnectionParametersCallback callback, async_dispatcher_t* dispatcher); // Sends a HCI event with the given parameters. - void SendEvent(hci::EventCode event_code, const common::ByteBuffer& payload); + void SendEvent(hci::EventCode event_code, const ByteBuffer& payload); // Sends a LE Meta event with the given parameters. - void SendLEMetaEvent(hci::EventCode subevent_code, - const common::ByteBuffer& payload); + void SendLEMetaEvent(hci::EventCode subevent_code, const ByteBuffer& payload); // Sends an ACL data packet with the given parameters. - void SendACLPacket(hci::ConnectionHandle handle, - const common::ByteBuffer& payload); + void SendACLPacket(hci::ConnectionHandle handle, const ByteBuffer& payload); // Sends a L2CAP basic frame. void SendL2CAPBFrame(hci::ConnectionHandle handle, - l2cap::ChannelId channel_id, - const common::ByteBuffer& payload); + l2cap::ChannelId channel_id, const ByteBuffer& payload); // Sends a L2CAP control frame over a signaling channel. If |is_le| is true, // then the LE signaling channel will be used. void SendL2CAPCFrame(hci::ConnectionHandle handle, bool is_le, l2cap::CommandCode code, uint8_t id, - const common::ByteBuffer& payload); + const ByteBuffer& payload); void SendNumberOfCompletedPacketsEvent(hci::ConnectionHandle conn, uint16_t num); // Sets up a LE link to the device with the given |addr|. FakeController will // report a connection event in which it is in the given |role|. - void ConnectLowEnergy(const common::DeviceAddress& addr, + void ConnectLowEnergy(const DeviceAddress& addr, hci::ConnectionRole role = hci::ConnectionRole::kSlave); // Tells a fake device to initiate the L2CAP Connection Parameter Update // procedure using the given |params|. Has no effect if a connected fake // device with the given |addr| is not found. void L2CAPConnectionParameterUpdate( - const common::DeviceAddress& addr, + const DeviceAddress& addr, const hci::LEPreferredConnectionParameters& params); // Marks the FakePeer with address |address| as disconnected and sends a HCI // Disconnection Complete event for all of its links. - void Disconnect(const common::DeviceAddress& addr); + void Disconnect(const DeviceAddress& addr); private: // Returns the current thread's task dispatcher. @@ -228,7 +223,7 @@ class FakeController : public FakeControllerBase, // Finds and returns the FakePeer with the given parameters or nullptr if no // such device exists. - FakePeer* FindByAddress(const common::DeviceAddress& addr); + FakePeer* FindByAddress(const DeviceAddress& addr); FakePeer* FindByConnHandle(hci::ConnectionHandle handle); // Returns the next available L2CAP signaling channel command ID. @@ -236,8 +231,7 @@ class FakeController : public FakeControllerBase, // Sends a HCI_Command_Complete event in response to the command with |opcode| // and using the given data as the parameter payload. - void RespondWithCommandComplete(hci::OpCode opcode, - const common::ByteBuffer& params); + void RespondWithCommandComplete(hci::OpCode opcode, const ByteBuffer& params); // Sends a HCI_Command_Complete event with "Success" status in response to the // command with |opcode|. @@ -262,7 +256,7 @@ class FakeController : public FakeControllerBase, void NotifyAdvertisingState(); // Notifies |conn_state_cb_| with the given parameters. - void NotifyConnectionState(const common::DeviceAddress& addr, bool connected, + void NotifyConnectionState(const DeviceAddress& addr, bool connected, bool canceled = false); // Called when a HCI_Create_Connection command is received. @@ -270,7 +264,7 @@ class FakeController : public FakeControllerBase, const hci::CreateConnectionCommandParams& params); // Notifies |le_conn_params_cb_| - void NotifyLEConnectionParameters(const common::DeviceAddress& addr, + void NotifyLEConnectionParameters(const DeviceAddress& addr, const hci::LEConnectionParameters& params); // Called when a HCI_LE_Create_Connection command is received. @@ -286,9 +280,8 @@ class FakeController : public FakeControllerBase, // FakeControllerBase overrides: void OnCommandPacketReceived( - const common::PacketView<hci::CommandHeader>& command_packet) override; - void OnACLDataPacketReceived( - const common::ByteBuffer& acl_data_packet) override; + const PacketView<hci::CommandHeader>& command_packet) override; + void OnACLDataPacketReceived(const ByteBuffer& acl_data_packet) override; Settings settings_; LEScanState le_scan_state_; @@ -296,7 +289,7 @@ class FakeController : public FakeControllerBase, // Used for Advertising, Create Connection, and Active Scanning // Set by HCI_LE_Set_Random_Address - std::optional<common::DeviceAddress> le_random_address_; + std::optional<DeviceAddress> le_random_address_; // Used for BR/EDR Scans uint8_t bredr_scan_state_; @@ -317,7 +310,7 @@ class FakeController : public FakeControllerBase, // Variables used for // HCI_BREDR_Create_Connection/HCI_BREDR_Create_Connection_Cancel. bool bredr_connect_pending_; - common::DeviceAddress pending_bredr_connect_addr_; + DeviceAddress pending_bredr_connect_addr_; fxl::CancelableClosure pending_bredr_connect_rsp_; // ID used for L2CAP LE signaling channel commands. diff --git a/src/connectivity/bluetooth/core/bt-host/testing/fake_controller_base.cc b/src/connectivity/bluetooth/core/bt-host/testing/fake_controller_base.cc index f4180f6166cc27de66ec44bae51c861b8855a837..f602758a2b3f1de2cc03b01e4cf509900dd2f52b 100644 --- a/src/connectivity/bluetooth/core/bt-host/testing/fake_controller_base.cc +++ b/src/connectivity/bluetooth/core/bt-host/testing/fake_controller_base.cc @@ -5,8 +5,8 @@ #include "fake_controller_base.h" #include <lib/async/default.h> -#include <zircon/status.h> #include <zircon/device/bt-hci.h> +#include <zircon/status.h> #include "src/connectivity/bluetooth/core/bt-host/common/log.h" #include "src/connectivity/bluetooth/core/bt-host/hci/acl_data_packet.h" @@ -74,7 +74,7 @@ void FakeControllerBase::Stop() { } zx_status_t FakeControllerBase::SendCommandChannelPacket( - const common::ByteBuffer& packet) { + const ByteBuffer& packet) { zx_status_t status = cmd_channel_.write(0, packet.data(), packet.size(), nullptr, 0); if (status != ZX_OK) { @@ -89,7 +89,7 @@ zx_status_t FakeControllerBase::SendCommandChannelPacket( } zx_status_t FakeControllerBase::SendACLDataChannelPacket( - const common::ByteBuffer& packet) { + const ByteBuffer& packet) { zx_status_t status = acl_channel_.write(0, packet.data(), packet.size(), nullptr, 0); if (status != ZX_OK) { @@ -103,11 +103,9 @@ zx_status_t FakeControllerBase::SendACLDataChannelPacket( return ZX_OK; } -void FakeControllerBase::SendSnoopChannelPacket( - const common::ByteBuffer& packet, - bt_hci_snoop_type_t packet_type, - bool is_received) { - +void FakeControllerBase::SendSnoopChannelPacket(const ByteBuffer& packet, + bt_hci_snoop_type_t packet_type, + bool is_received) { if (snoop_channel_.is_valid()) { uint8_t snoop_buffer[packet.size() + 1]; uint8_t flags = bt_hci_snoop_flags(packet_type, is_received); @@ -117,12 +115,12 @@ void FakeControllerBase::SendSnoopChannelPacket( zx_status_t status = snoop_channel_.write(0, snoop_buffer, packet.size() + 1, nullptr, 0); if (status != ZX_OK) { - bt_log(WARN, "fake-hci", "cleaning up snoop channel after failed write: %s", + bt_log(WARN, "fake-hci", + "cleaning up snoop channel after failed write: %s", zx_status_get_string(status)); CloseSnoopChannel(); } } - } void FakeControllerBase::CloseCommandChannel() { @@ -147,16 +145,15 @@ void FakeControllerBase::CloseSnoopChannel() { } } -void FakeControllerBase::HandleCommandPacket( - async_dispatcher_t* dispatcher, - async::WaitBase* wait, - zx_status_t wait_status, - const zx_packet_signal_t* signal) { - common::StaticByteBuffer<hci::kMaxCommandPacketPayloadSize> buffer; +void FakeControllerBase::HandleCommandPacket(async_dispatcher_t* dispatcher, + async::WaitBase* wait, + zx_status_t wait_status, + const zx_packet_signal_t* signal) { + StaticByteBuffer<hci::kMaxCommandPacketPayloadSize> buffer; uint32_t read_size; zx_status_t status = cmd_channel_.read(0u, buffer.mutable_data(), nullptr, - hci::kMaxCommandPacketPayloadSize, - 0, &read_size, nullptr); + hci::kMaxCommandPacketPayloadSize, 0, + &read_size, nullptr); ZX_DEBUG_ASSERT(status == ZX_OK || status == ZX_ERR_PEER_CLOSED); if (status < 0) { if (status == ZX_ERR_PEER_CLOSED) { @@ -172,8 +169,8 @@ void FakeControllerBase::HandleCommandPacket( if (read_size < sizeof(hci::CommandHeader)) { bt_log(ERROR, "fake-hci", "malformed command packet received"); } else { - common::MutableBufferView view(buffer.mutable_data(), read_size); - common::PacketView<hci::CommandHeader> packet( + MutableBufferView view(buffer.mutable_data(), read_size); + PacketView<hci::CommandHeader> packet( &view, read_size - sizeof(hci::CommandHeader)); SendSnoopChannelPacket(packet.data(), BT_HCI_SNOOP_TYPE_CMD, false); OnCommandPacketReceived(packet); @@ -187,17 +184,14 @@ void FakeControllerBase::HandleCommandPacket( } } -void FakeControllerBase::HandleACLPacket( - async_dispatcher_t* dispatcher, - async::WaitBase* wait, - zx_status_t wait_status, - const zx_packet_signal_t* signal) { - common::StaticByteBuffer<hci::kMaxACLPayloadSize + sizeof(hci::ACLDataHeader)> - buffer; +void FakeControllerBase::HandleACLPacket(async_dispatcher_t* dispatcher, + async::WaitBase* wait, + zx_status_t wait_status, + const zx_packet_signal_t* signal) { + StaticByteBuffer<hci::kMaxACLPayloadSize + sizeof(hci::ACLDataHeader)> buffer; uint32_t read_size; - zx_status_t status = - acl_channel_.read(0u, buffer.mutable_data(), nullptr, buffer.size(), 0, - &read_size, nullptr); + zx_status_t status = acl_channel_.read(0u, buffer.mutable_data(), nullptr, + buffer.size(), 0, &read_size, nullptr); ZX_DEBUG_ASSERT(status == ZX_OK || status == ZX_ERR_PEER_CLOSED); if (status < 0) { if (status == ZX_ERR_PEER_CLOSED) { @@ -211,7 +205,7 @@ void FakeControllerBase::HandleACLPacket( return; } - common::BufferView view(buffer.data(), read_size); + BufferView view(buffer.data(), read_size); SendSnoopChannelPacket(view, BT_HCI_SNOOP_TYPE_ACL, false); OnACLDataPacketReceived(view); diff --git a/src/connectivity/bluetooth/core/bt-host/testing/fake_controller_base.h b/src/connectivity/bluetooth/core/bt-host/testing/fake_controller_base.h index ee88596c8d8a4e5abeab2424b56dc7f3aa6b1072..fae4c8b0c82ab45566f3f36e8da51d34b78317b8 100644 --- a/src/connectivity/bluetooth/core/bt-host/testing/fake_controller_base.h +++ b/src/connectivity/bluetooth/core/bt-host/testing/fake_controller_base.h @@ -30,12 +30,12 @@ class FakeControllerBase { // Sends the given packet over this FakeController's command channel endpoint. // Retuns the result of the write operation on the command channel. - zx_status_t SendCommandChannelPacket(const common::ByteBuffer& packet); + zx_status_t SendCommandChannelPacket(const ByteBuffer& packet); // Sends the given packet over this FakeController's ACL data channel // endpoint. // Retuns the result of the write operation on the channel. - zx_status_t SendACLDataChannelPacket(const common::ByteBuffer& packet); + zx_status_t SendACLDataChannelPacket(const ByteBuffer& packet); // Immediately closes the command channel endpoint. void CloseCommandChannel(); @@ -66,11 +66,10 @@ class FakeControllerBase { // Called when there is an incoming command packet. virtual void OnCommandPacketReceived( - const common::PacketView<hci::CommandHeader>& command_packet) = 0; + const PacketView<hci::CommandHeader>& command_packet) = 0; // Called when there is an outgoing ACL data packet. - virtual void OnACLDataPacketReceived( - const common::ByteBuffer& acl_data_packet) = 0; + virtual void OnACLDataPacketReceived(const ByteBuffer& acl_data_packet) = 0; private: // Read and handle packets received over the channels. @@ -84,7 +83,7 @@ class FakeControllerBase { // Sends the given packet over this FakeController's Snoop channel // endpoint. // Retuns the result of the write operation on the channel. - void SendSnoopChannelPacket(const common::ByteBuffer& packet, + void SendSnoopChannelPacket(const ByteBuffer& packet, bt_hci_snoop_type_t packet_type, bool is_received); diff --git a/src/connectivity/bluetooth/core/bt-host/testing/fake_gatt_server.cc b/src/connectivity/bluetooth/core/bt-host/testing/fake_gatt_server.cc index c3d378a02cd9c341f72ce84833e67852d8d65e47..4266c3960494262b199608aedbd328fdefc2fd49 100644 --- a/src/connectivity/bluetooth/core/bt-host/testing/fake_gatt_server.cc +++ b/src/connectivity/bluetooth/core/bt-host/testing/fake_gatt_server.cc @@ -7,20 +7,15 @@ #include <endian.h> #include <zircon/assert.h> +#include "fake_controller.h" +#include "fake_peer.h" #include "src/connectivity/bluetooth/core/bt-host/att/packet.h" #include "src/connectivity/bluetooth/core/bt-host/common/log.h" #include "src/connectivity/bluetooth/core/bt-host/gatt/gatt_defs.h" -#include "fake_controller.h" -#include "fake_peer.h" - namespace bt { namespace testing { -using common::ByteBuffer; -using common::CreateStaticByteBuffer; -using common::StaticByteBuffer; - FakeGattServer::FakeGattServer(FakePeer* dev) : dev_(dev) { ZX_DEBUG_ASSERT(dev_); } diff --git a/src/connectivity/bluetooth/core/bt-host/testing/fake_gatt_server.h b/src/connectivity/bluetooth/core/bt-host/testing/fake_gatt_server.h index 48819f1aafdae98f6784ca362654665f62f96810..6891519cde2e0ebc453a3012e17fb67466486fac 100644 --- a/src/connectivity/bluetooth/core/bt-host/testing/fake_gatt_server.h +++ b/src/connectivity/bluetooth/core/bt-host/testing/fake_gatt_server.h @@ -20,13 +20,13 @@ class FakeGattServer final { explicit FakeGattServer(FakePeer* dev); // Handle the ATT |pdu| received over link with handle |conn|. - void HandlePdu(hci::ConnectionHandle conn, const common::ByteBuffer& pdu); + void HandlePdu(hci::ConnectionHandle conn, const ByteBuffer& pdu); private: void HandleReadByGrpType(hci::ConnectionHandle conn, - const common::ByteBuffer& params); + const ByteBuffer& params); - void Send(hci::ConnectionHandle conn, const common::ByteBuffer& pdu); + void Send(hci::ConnectionHandle conn, const ByteBuffer& pdu); void SendErrorRsp(hci::ConnectionHandle conn, att::OpCode opcode, att::Handle handle, att::ErrorCode ecode); diff --git a/src/connectivity/bluetooth/core/bt-host/testing/fake_peer.cc b/src/connectivity/bluetooth/core/bt-host/testing/fake_peer.cc index 879f3b9d5b143fec3079638fb109e714b8b07b22..f4387842260ea27bb0ccf51412409e08678a9727 100644 --- a/src/connectivity/bluetooth/core/bt-host/testing/fake_peer.cc +++ b/src/connectivity/bluetooth/core/bt-host/testing/fake_peer.cc @@ -14,8 +14,6 @@ namespace bt { -using common::ByteBuffer; - namespace testing { namespace { @@ -32,8 +30,8 @@ void WriteRandomRSSI(int8_t* out_mem) { } // namespace -FakePeer::FakePeer(const common::DeviceAddress& address, bool connectable, - bool scannable) +FakePeer::FakePeer(const DeviceAddress& address, bool connectable, + bool scannable) : ctrl_(nullptr), address_(address), connected_(false), @@ -47,22 +45,22 @@ FakePeer::FakePeer(const common::DeviceAddress& address, bool connectable, should_batch_reports_(false), gatt_server_(this) {} -void FakePeer::SetAdvertisingData(const common::ByteBuffer& data) { +void FakePeer::SetAdvertisingData(const ByteBuffer& data) { ZX_DEBUG_ASSERT(data.size() <= hci::kMaxLEAdvertisingDataLength); - adv_data_ = common::DynamicByteBuffer(data); + adv_data_ = DynamicByteBuffer(data); } void FakePeer::SetScanResponse(bool should_batch_reports, - const common::ByteBuffer& data) { + const ByteBuffer& data) { ZX_DEBUG_ASSERT(scannable_); ZX_DEBUG_ASSERT(data.size() <= hci::kMaxLEAdvertisingDataLength); - scan_rsp_ = common::DynamicByteBuffer(data); + scan_rsp_ = DynamicByteBuffer(data); should_batch_reports_ = should_batch_reports; } -common::DynamicByteBuffer FakePeer::CreateInquiryResponseEvent( +DynamicByteBuffer FakePeer::CreateInquiryResponseEvent( hci::InquiryMode mode) const { - ZX_DEBUG_ASSERT(address_.type() == common::DeviceAddress::Type::kBREDR); + ZX_DEBUG_ASSERT(address_.type() == DeviceAddress::Type::kBREDR); size_t param_size; if (mode == hci::InquiryMode::kStandard) { @@ -73,8 +71,8 @@ common::DynamicByteBuffer FakePeer::CreateInquiryResponseEvent( sizeof(hci::InquiryResultRSSI); } - common::DynamicByteBuffer buffer(sizeof(hci::EventHeader) + param_size); - common::MutablePacketView<hci::EventHeader> event(&buffer, param_size); + DynamicByteBuffer buffer(sizeof(hci::EventHeader) + param_size); + MutablePacketView<hci::EventHeader> event(&buffer, param_size); event.mutable_header()->parameter_total_size = param_size; // TODO(jamuraa): simultate clock offset and RSSI @@ -106,7 +104,7 @@ common::DynamicByteBuffer FakePeer::CreateInquiryResponseEvent( return buffer; } -common::DynamicByteBuffer FakePeer::CreateAdvertisingReportEvent( +DynamicByteBuffer FakePeer::CreateAdvertisingReportEvent( bool include_scan_rsp) const { size_t param_size = sizeof(hci::LEMetaEventParams) + sizeof(hci::LEAdvertisingReportSubeventParams) + @@ -118,8 +116,8 @@ common::DynamicByteBuffer FakePeer::CreateAdvertisingReportEvent( sizeof(int8_t); } - common::DynamicByteBuffer buffer(sizeof(hci::EventHeader) + param_size); - common::MutablePacketView<hci::EventHeader> event(&buffer, param_size); + DynamicByteBuffer buffer(sizeof(hci::EventHeader) + param_size); + MutablePacketView<hci::EventHeader> event(&buffer, param_size); event.mutable_header()->event_code = hci::kLEMetaEventCode; event.mutable_header()->parameter_total_size = param_size; @@ -142,7 +140,7 @@ common::DynamicByteBuffer FakePeer::CreateAdvertisingReportEvent( } else { report->event_type = hci::LEAdvertisingEventType::kAdvNonConnInd; } - if (address_.type() == common::DeviceAddress::Type::kLERandom) { + if (address_.type() == DeviceAddress::Type::kLERandom) { report->address_type = address_resolved_ ? hci::LEAddressType::kRandomIdentity : hci::LEAddressType::kRandom; @@ -166,15 +164,15 @@ common::DynamicByteBuffer FakePeer::CreateAdvertisingReportEvent( return buffer; } -common::DynamicByteBuffer FakePeer::CreateScanResponseReportEvent() const { +DynamicByteBuffer FakePeer::CreateScanResponseReportEvent() const { ZX_DEBUG_ASSERT(scannable_); size_t param_size = sizeof(hci::LEMetaEventParams) + sizeof(hci::LEAdvertisingReportSubeventParams) + sizeof(hci::LEAdvertisingReportData) + scan_rsp_.size() + sizeof(int8_t); - common::DynamicByteBuffer buffer(sizeof(hci::EventHeader) + param_size); - common::MutablePacketView<hci::EventHeader> event(&buffer, param_size); + DynamicByteBuffer buffer(sizeof(hci::EventHeader) + param_size); + MutablePacketView<hci::EventHeader> event(&buffer, param_size); event.mutable_header()->event_code = hci::kLEMetaEventCode; event.mutable_header()->parameter_total_size = param_size; @@ -221,10 +219,9 @@ void FakePeer::WriteScanResponseReport( hci::LEAdvertisingReportData* report) const { ZX_DEBUG_ASSERT(scannable_); report->event_type = hci::LEAdvertisingEventType::kScanRsp; - report->address_type = - (address_.type() == common::DeviceAddress::Type::kLERandom) - ? hci::LEAddressType::kRandom - : hci::LEAddressType::kPublic; + report->address_type = (address_.type() == DeviceAddress::Type::kLERandom) + ? hci::LEAddressType::kRandom + : hci::LEAddressType::kPublic; report->address = address_.value(); report->length_data = scan_rsp_.size(); std::memcpy(report->data, scan_rsp_.data(), scan_rsp_.size()); @@ -233,8 +230,7 @@ void FakePeer::WriteScanResponseReport( reinterpret_cast<int8_t*>(report->data + report->length_data)); } -void FakePeer::OnRxL2CAP(hci::ConnectionHandle conn, - const common::ByteBuffer& pdu) { +void FakePeer::OnRxL2CAP(hci::ConnectionHandle conn, const ByteBuffer& pdu) { if (pdu.size() < sizeof(l2cap::BasicHeader)) { bt_log(WARN, "fake-hci", "malformed L2CAP packet!"); return; diff --git a/src/connectivity/bluetooth/core/bt-host/testing/fake_peer.h b/src/connectivity/bluetooth/core/bt-host/testing/fake_peer.h index 65ac729f912e7ac32535b7cb63a2b8db9b84ac4e..13ffbe960b00061bf6f724c03be57c7cbe34dcc6 100644 --- a/src/connectivity/bluetooth/core/bt-host/testing/fake_peer.h +++ b/src/connectivity/bluetooth/core/bt-host/testing/fake_peer.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_TESTING_FAKE_DEVICE_H_ -#define SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_TESTING_FAKE_DEVICE_H_ +#ifndef SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_TESTING_FAKE_PEER_H_ +#define SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_TESTING_FAKE_PEER_H_ #include <fbl/macros.h> @@ -29,10 +29,10 @@ class FakePeer { // false. This is OK since we use |scannable| to drive the receipt of Scan // Response PDUs: we use this to test the condition in which the advertisement // is scannable but the host never receives a scan response. - explicit FakePeer(const common::DeviceAddress& address, - bool connectable = true, bool scannable = true); + explicit FakePeer(const DeviceAddress& address, bool connectable = true, + bool scannable = true); - void SetAdvertisingData(const common::ByteBuffer& data); + void SetAdvertisingData(const ByteBuffer& data); // Mark this device for directed advertising. CreateAdvertisingReportEvent // will return directed advertisements only. @@ -47,32 +47,29 @@ class FakePeer { bool has_inquiry_response() { // All BR/EDR devices have inquiry responses. - return address().type() == common::DeviceAddress::Type::kBREDR; + return address().type() == DeviceAddress::Type::kBREDR; } // |should_batch_reports| indicates to the FakeController that the SCAN_IND // report should be included in the same HCI LE Advertising Report Event // payload that includes the original advertising data (see comments for // should_batch_reports()). - void SetScanResponse(bool should_batch_reports, - const common::ByteBuffer& data); + void SetScanResponse(bool should_batch_reports, const ByteBuffer& data); // Generates and returns a LE Advertising Report Event payload. If // |include_scan_rsp| is true, then the returned PDU will contain two reports // including the SCAN_IND report. - common::DynamicByteBuffer CreateAdvertisingReportEvent( - bool include_scan_rsp) const; + DynamicByteBuffer CreateAdvertisingReportEvent(bool include_scan_rsp) const; // Generates a LE Advertising Report Event payload containing the scan // response. - common::DynamicByteBuffer CreateScanResponseReportEvent() const; + DynamicByteBuffer CreateScanResponseReportEvent() const; // Generates a Inquiry Response Event payload containing a inquiry result // response. - common::DynamicByteBuffer CreateInquiryResponseEvent( - hci::InquiryMode mode) const; + DynamicByteBuffer CreateInquiryResponseEvent(hci::InquiryMode mode) const; - const common::DeviceAddress& address() const { return address_; } + const DeviceAddress& address() const { return address_; } // Indicates whether or not this device should include the scan response and // the advertising data in the same HCI LE Advertising Report Event. This is @@ -94,7 +91,7 @@ class FakePeer { bool connected() const { return connected_; } void set_connected(bool connected) { connected_ = connected; } - void set_class_of_device(common::DeviceClass class_of_device) { + void set_class_of_device(DeviceClass class_of_device) { class_of_device_ = class_of_device; } @@ -141,12 +138,12 @@ class FakePeer { void WriteScanResponseReport(hci::LEAdvertisingReportData* report) const; - void OnRxL2CAP(hci::ConnectionHandle conn, const common::ByteBuffer& pdu); + void OnRxL2CAP(hci::ConnectionHandle conn, const ByteBuffer& pdu); // The FakeController that this FakePeer has been assigned to. FakeController* ctrl_; // weak - common::DeviceAddress address_; + DeviceAddress address_; bool connected_; bool connectable_; bool scannable_; @@ -160,14 +157,14 @@ class FakePeer { hci::LEConnectionParameters le_params_; bool should_batch_reports_; - common::DynamicByteBuffer adv_data_; - common::DynamicByteBuffer scan_rsp_; + DynamicByteBuffer adv_data_; + DynamicByteBuffer scan_rsp_; // Open connection handles. HandleSet logical_links_; // Class of device - common::DeviceClass class_of_device_; + DeviceClass class_of_device_; FakeGattServer gatt_server_; @@ -177,4 +174,4 @@ class FakePeer { } // namespace testing } // namespace bt -#endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_TESTING_FAKE_DEVICE_H_ +#endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_TESTING_FAKE_PEER_H_ diff --git a/src/connectivity/bluetooth/core/bt-host/testing/run_all_unittests.cc b/src/connectivity/bluetooth/core/bt-host/testing/run_all_unittests.cc index a9fe0dd10ca1dadb3963743388c003a1ac92f024..bdc362c2885f4f50f4a22e258d426f71761ebed4 100644 --- a/src/connectivity/bluetooth/core/bt-host/testing/run_all_unittests.cc +++ b/src/connectivity/bluetooth/core/bt-host/testing/run_all_unittests.cc @@ -2,18 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "gtest/gtest.h" - #include <ddk/driver.h> +#include "gtest/gtest.h" #include "src/connectivity/bluetooth/core/bt-host/common/log.h" - #include "src/lib/fxl/command_line.h" #include "src/lib/fxl/log_settings_command_line.h" BT_DECLARE_FAKE_DRIVER(); -using bt::common::LogSeverity; +using bt::LogSeverity; namespace { @@ -50,7 +48,7 @@ int main(int argc, char** argv) { } // Set all library log messages to use printf instead ddk logging. - bt::common::UsePrintf(FxlLogToBtLogLevel(log_settings.min_log_level)); + bt::UsePrintf(FxlLogToBtLogLevel(log_settings.min_log_level)); testing::InitGoogleTest(&argc, argv); diff --git a/src/connectivity/bluetooth/core/bt-host/testing/test_controller.cc b/src/connectivity/bluetooth/core/bt-host/testing/test_controller.cc index ab6681e5303713460df1b38415e3701fe82994ce..5588edeb2c9689756e6b3bfad44fe9866d3d6931 100644 --- a/src/connectivity/bluetooth/core/bt-host/testing/test_controller.cc +++ b/src/connectivity/bluetooth/core/bt-host/testing/test_controller.cc @@ -8,34 +8,31 @@ #include <zircon/status.h> #include "gtest/gtest.h" - #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" namespace bt { namespace testing { CommandTransaction::CommandTransaction( - const common::ByteBuffer& expected, - const std::vector<const common::ByteBuffer*>& replies) + const ByteBuffer& expected, const std::vector<const ByteBuffer*>& replies) : prefix_(false), expected_(expected) { for (const auto* buffer : replies) { - replies_.push(common::DynamicByteBuffer(*buffer)); + replies_.push(DynamicByteBuffer(*buffer)); } } CommandTransaction::CommandTransaction( - hci::OpCode expected_opcode, - const std::vector<const common::ByteBuffer*>& replies) + hci::OpCode expected_opcode, const std::vector<const ByteBuffer*>& replies) : prefix_(true) { hci::OpCode le_opcode = htole16(expected_opcode); - const common::BufferView expected(&le_opcode, sizeof(expected_opcode)); - expected_ = common::DynamicByteBuffer(expected); + const BufferView expected(&le_opcode, sizeof(expected_opcode)); + expected_ = DynamicByteBuffer(expected); for (const auto* buffer : replies) { - replies_.push(common::DynamicByteBuffer(*buffer)); + replies_.push(DynamicByteBuffer(*buffer)); } } -bool CommandTransaction::Match(const common::BufferView& cmd) { +bool CommandTransaction::Match(const BufferView& cmd) { return ContainersEqual(expected_, (prefix_ ? cmd.view(0, expected_.size()) : cmd)); } @@ -55,8 +52,7 @@ void TestController::QueueCommandTransaction(CommandTransaction transaction) { } void TestController::QueueCommandTransaction( - const common::ByteBuffer& expected, - const std::vector<const common::ByteBuffer*>& replies) { + const ByteBuffer& expected, const std::vector<const ByteBuffer*>& replies) { QueueCommandTransaction(CommandTransaction(expected, replies)); } @@ -99,7 +95,7 @@ void TestController::ClearTransactionCallback() { } void TestController::OnCommandPacketReceived( - const common::PacketView<hci::CommandHeader>& command_packet) { + const PacketView<hci::CommandHeader>& command_packet) { uint16_t opcode = command_packet.header().opcode; uint8_t ogf = hci::GetOGF(opcode); uint16_t ocf = hci::GetOCF(opcode); @@ -123,7 +119,7 @@ void TestController::OnCommandPacketReceived( cmd_transactions_.pop(); if (transaction_callback_) { - common::DynamicByteBuffer rx(command_packet.data()); + DynamicByteBuffer rx(command_packet.data()); async::PostTask( transaction_dispatcher_, [rx = std::move(rx), f = transaction_callback_.share()] { f(rx); }); @@ -131,11 +127,11 @@ void TestController::OnCommandPacketReceived( } void TestController::OnACLDataPacketReceived( - const common::ByteBuffer& acl_data_packet) { + const ByteBuffer& acl_data_packet) { if (!data_callback_) return; - common::DynamicByteBuffer packet_copy(acl_data_packet); + DynamicByteBuffer packet_copy(acl_data_packet); async::PostTask(data_dispatcher_, [packet_copy = std::move(packet_copy), cb = data_callback_.share()]() mutable { cb(packet_copy); }); diff --git a/src/connectivity/bluetooth/core/bt-host/testing/test_controller.h b/src/connectivity/bluetooth/core/bt-host/testing/test_controller.h index ef2493ddab7062b32853d6199bc28e2a21aeca4b..38ce6821d83429fe3548421a417f471417e5421b 100644 --- a/src/connectivity/bluetooth/core/bt-host/testing/test_controller.h +++ b/src/connectivity/bluetooth/core/bt-host/testing/test_controller.h @@ -24,26 +24,26 @@ namespace testing { class CommandTransaction final { public: CommandTransaction() = default; - CommandTransaction(const common::ByteBuffer& expected, - const std::vector<const common::ByteBuffer*>& replies); + CommandTransaction(const ByteBuffer& expected, + const std::vector<const ByteBuffer*>& replies); // Match by opcode only. CommandTransaction(hci::OpCode expected_opcode, - const std::vector<const common::ByteBuffer*>& replies); + const std::vector<const ByteBuffer*>& replies); // Move constructor and assignment operator. CommandTransaction(CommandTransaction&& other) = default; CommandTransaction& operator=(CommandTransaction&& other) = default; // Returns true if the transaction matches the given HCI command packet. - bool Match(const common::BufferView& cmd); + bool Match(const BufferView& cmd); private: friend class TestController; bool prefix_ = false; - common::DynamicByteBuffer expected_; - std::queue<common::DynamicByteBuffer> replies_; + DynamicByteBuffer expected_; + std::queue<DynamicByteBuffer> replies_; DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(CommandTransaction); }; @@ -62,21 +62,20 @@ class TestController : public FakeControllerBase { // fatal assertion. On a match, TestController will send back the replies // provided in the transaction. void QueueCommandTransaction(CommandTransaction transaction); - void QueueCommandTransaction( - const common::ByteBuffer& expected, - const std::vector<const common::ByteBuffer*>& replies); + void QueueCommandTransaction(const ByteBuffer& expected, + const std::vector<const ByteBuffer*>& replies); // Callback to invoke when a packet is received over the data channel. Care // should be taken to ensure that a callback with a reference to test case // variables is not invoked when tearing down. - using DataCallback = fit::function<void(const common::ByteBuffer& packet)>; + using DataCallback = fit::function<void(const ByteBuffer& packet)>; void SetDataCallback(DataCallback callback, async_dispatcher_t* dispatcher); void ClearDataCallback(); // Callback invoked when a transaction completes. Care should be taken to // ensure that a callback with a reference to test case variables is not // invoked when tearing down. - using TransactionCallback = fit::function<void(const common::ByteBuffer& rx)>; + using TransactionCallback = fit::function<void(const ByteBuffer& rx)>; void SetTransactionCallback(TransactionCallback callback, async_dispatcher_t* dispatcher); void SetTransactionCallback(fit::closure callback, @@ -86,9 +85,8 @@ class TestController : public FakeControllerBase { private: // FakeControllerBase overrides: void OnCommandPacketReceived( - const common::PacketView<hci::CommandHeader>& command_packet) override; - void OnACLDataPacketReceived( - const common::ByteBuffer& acl_data_packet) override; + const PacketView<hci::CommandHeader>& command_packet) override; + void OnACLDataPacketReceived(const ByteBuffer& acl_data_packet) override; std::queue<CommandTransaction> cmd_transactions_; DataCallback data_callback_; diff --git a/src/connectivity/bluetooth/core/bt-host/testing/test_packets.cc b/src/connectivity/bluetooth/core/bt-host/testing/test_packets.cc index 3f76d3b3bc903888d56ba7a3da1a1a2df9f697ba..a2e578ba9e3cee8b0871ca2e1a3ca03f78bf6f5d 100644 --- a/src/connectivity/bluetooth/core/bt-host/testing/test_packets.cc +++ b/src/connectivity/bluetooth/core/bt-host/testing/test_packets.cc @@ -10,14 +10,6 @@ namespace bt { namespace testing { -using common::CreateStaticByteBuffer; -using common::DeviceAddress; -using common::DynamicByteBuffer; -using common::LowerBits; -using common::MutableByteBufferPtr; -using common::StaticByteBuffer; -using common::UpperBits; - DynamicByteBuffer CreateConnectionPacket(DeviceAddress address) { auto addr = address.value().bytes(); return DynamicByteBuffer(CreateStaticByteBuffer( @@ -26,10 +18,10 @@ DynamicByteBuffer CreateConnectionPacket(DeviceAddress address) { addr[0], addr[1], addr[2], addr[3], addr[4], addr[5], // peer address LowerBits(hci::kEnableAllPacketTypes), // allowable packet types UpperBits(hci::kEnableAllPacketTypes), // allowable packet types - 0x02, // page_scan_repetition_mode (R2) - 0x00, // reserved - 0x00, 0x00, // clock_offset - 0x00 // allow_role_switch (don't) + 0x02, // page_scan_repetition_mode (R2) + 0x00, // reserved + 0x00, 0x00, // clock_offset + 0x00 // allow_role_switch (don't) )); } diff --git a/src/connectivity/bluetooth/core/bt-host/testing/test_packets.h b/src/connectivity/bluetooth/core/bt-host/testing/test_packets.h index 2539a663321f653834f488c2af92d918e551e02b..ab2545b89075f27e001cd38afae652f6a7584abd 100644 --- a/src/connectivity/bluetooth/core/bt-host/testing/test_packets.h +++ b/src/connectivity/bluetooth/core/bt-host/testing/test_packets.h @@ -16,30 +16,23 @@ namespace testing { // This allows easily defining expected packets to be sent or received for // given transactions such as connection establishment or discovery -common::DynamicByteBuffer CreateConnectionPacket(common::DeviceAddress address); -common::DynamicByteBuffer ConnectionCompletePacket( - common::DeviceAddress address, hci::ConnectionHandle conn); -common::DynamicByteBuffer DisconnectPacket(hci::ConnectionHandle conn); -common::DynamicByteBuffer DisconnectionCompletePacket( +DynamicByteBuffer CreateConnectionPacket(DeviceAddress address); +DynamicByteBuffer ConnectionCompletePacket(DeviceAddress address, + hci::ConnectionHandle conn); +DynamicByteBuffer DisconnectPacket(hci::ConnectionHandle conn); +DynamicByteBuffer DisconnectionCompletePacket(hci::ConnectionHandle conn); +DynamicByteBuffer RemoteNameRequestPacket(DeviceAddress address); +DynamicByteBuffer RemoteNameRequestCompletePacket(DeviceAddress address); +DynamicByteBuffer ReadRemoteVersionInfoPacket(hci::ConnectionHandle conn); +DynamicByteBuffer ReadRemoteVersionInfoCompletePacket( hci::ConnectionHandle conn); -common::DynamicByteBuffer RemoteNameRequestPacket( - common::DeviceAddress address); -common::DynamicByteBuffer RemoteNameRequestCompletePacket( - common::DeviceAddress address); -common::DynamicByteBuffer ReadRemoteVersionInfoPacket( - hci::ConnectionHandle conn); -common::DynamicByteBuffer ReadRemoteVersionInfoCompletePacket( - hci::ConnectionHandle conn); -common::DynamicByteBuffer ReadRemoteSupportedFeaturesPacket( - hci::ConnectionHandle conn); -common::DynamicByteBuffer ReadRemoteSupportedFeaturesCompletePacket( - hci::ConnectionHandle conn); -common::DynamicByteBuffer ReadRemoteExtended1Packet(hci::ConnectionHandle conn); -common::DynamicByteBuffer ReadRemoteExtended1CompletePacket( - hci::ConnectionHandle conn); -common::DynamicByteBuffer ReadRemoteExtended2Packet(hci::ConnectionHandle conn); -common::DynamicByteBuffer ReadRemoteExtended2CompletePacket( +DynamicByteBuffer ReadRemoteSupportedFeaturesPacket(hci::ConnectionHandle conn); +DynamicByteBuffer ReadRemoteSupportedFeaturesCompletePacket( hci::ConnectionHandle conn); +DynamicByteBuffer ReadRemoteExtended1Packet(hci::ConnectionHandle conn); +DynamicByteBuffer ReadRemoteExtended1CompletePacket(hci::ConnectionHandle conn); +DynamicByteBuffer ReadRemoteExtended2Packet(hci::ConnectionHandle conn); +DynamicByteBuffer ReadRemoteExtended2CompletePacket(hci::ConnectionHandle conn); } // namespace testing } // namespace bt diff --git a/src/connectivity/bluetooth/hci/atheros/device.cc b/src/connectivity/bluetooth/hci/atheros/device.cc index 47ae1b3af581deb69938820ffd0c5444d119c047..81132e2562ef32903c188a8fabe6b6a28c4759ff 100644 --- a/src/connectivity/bluetooth/hci/atheros/device.cc +++ b/src/connectivity/bluetooth/hci/atheros/device.cc @@ -5,22 +5,21 @@ #include "device.h" #include <ddk/protocol/usb.h> -#include <usb/usb.h> -#include <usb/usb-request.h> #include <fbl/auto_lock.h> #include <fbl/string_printf.h> +#include <fuchsia/hardware/bluetooth/c/fidl.h> #include <lib/zx/vmo.h> #include <usb/usb-request.h> +#include <usb/usb.h> #include <zircon/process.h> #include <zircon/status.h> -#include <fuchsia/hardware/bluetooth/c/fidl.h> #include "logging.h" namespace btatheros { -using ::bt::common::BufferView; -using ::bt::common::PacketView; +using ::bt::BufferView; +using ::bt::PacketView; // hard coded for Qualcomm Atheros chipset 0CF3:E300 static constexpr size_t GET_TARGET_VERSION = 0x09; @@ -84,9 +83,9 @@ zx_status_t Device::LoadNVM(const qca_version& version) { size_t size = std::min(count, NVM_HDR); size_t sent = 0; - result = usb_control_out(&usb_, USB_TYPE_VENDOR, DFU_DOWNLOAD, 0, 0, - ZX_TIME_INFINITE, - (void*)file.view(0, size).data(), size); + result = + usb_control_out(&usb_, USB_TYPE_VENDOR, DFU_DOWNLOAD, 0, 0, + ZX_TIME_INFINITE, (void*)file.view(0, size).data(), size); if (result != ZX_OK) { return result; } @@ -94,8 +93,8 @@ zx_status_t Device::LoadNVM(const qca_version& version) { usb_request_t* req; result = usb_request_alloc(&req, size, bulk_out_addr_, parent_req_size_); if (result != ZX_OK) { - zxlogf(ERROR, "LoadNVM: Failed to allocate usb request: %d\n", result); - return result; + zxlogf(ERROR, "LoadNVM: Failed to allocate usb request: %d\n", result); + return result; } count -= size; @@ -145,14 +144,14 @@ zx_status_t Device::LoadRAM(const qca_version& version) { BufferView file(reinterpret_cast<void*>(fw_addr), fw_size); - result = usb_control_out(&usb_, USB_TYPE_VENDOR, DFU_DOWNLOAD, 0, 0, - ZX_TIME_INFINITE, - (void*)file.view(0, size).data(), size); + result = + usb_control_out(&usb_, USB_TYPE_VENDOR, DFU_DOWNLOAD, 0, 0, + ZX_TIME_INFINITE, (void*)file.view(0, size).data(), size); usb_request_t* req; result = usb_request_alloc(&req, size, bulk_out_addr_, parent_req_size_); if (result != ZX_OK) { - zxlogf(ERROR, "LoadRAM: Failed to allocate usb request: %d\n", result); - return result; + zxlogf(ERROR, "LoadRAM: Failed to allocate usb request: %d\n", result); + return result; } count -= size; @@ -195,8 +194,9 @@ zx_status_t Device::LoadFirmware() { struct qca_version ver; size_t actual_read; - result = usb_control_in(&usb_, USB_TYPE_VENDOR | USB_DIR_IN, GET_TARGET_VERSION, - 0, 0, ZX_TIME_INFINITE, &ver, sizeof(ver), &actual_read); + result = + usb_control_in(&usb_, USB_TYPE_VENDOR | USB_DIR_IN, GET_TARGET_VERSION, 0, + 0, ZX_TIME_INFINITE, &ver, sizeof(ver), &actual_read); if (result != ZX_OK) { errorf("couldn't get version"); @@ -204,8 +204,9 @@ zx_status_t Device::LoadFirmware() { } uint8_t status; - result = usb_control_in(&usb_, USB_TYPE_VENDOR | USB_DIR_IN, GET_STATUS, 0, 0, - ZX_TIME_INFINITE, &status, sizeof(status), &actual_read); + result = + usb_control_in(&usb_, USB_TYPE_VENDOR | USB_DIR_IN, GET_STATUS, 0, 0, + ZX_TIME_INFINITE, &status, sizeof(status), &actual_read); usb_desc_iter_t iter; result = usb_desc_iter_init(&usb_, &iter); diff --git a/src/connectivity/bluetooth/hci/fake/fake_device.cc b/src/connectivity/bluetooth/hci/fake/fake_device.cc index 0787b06d9b3bfd0c9824a09e3697b6f96755109d..0f9d1d17500c849330fabb39c9c7384fd1084ecb 100644 --- a/src/connectivity/bluetooth/hci/fake/fake_device.cc +++ b/src/connectivity/bluetooth/hci/fake/fake_device.cc @@ -2,20 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include <cstdio> -#include <future> -#include <thread> +#include "fake_device.h" #include <ddk/protocol/bt/hci.h> #include <lib/async/cpp/task.h> #include <zircon/status.h> #include <zircon/types.h> -#include "src/connectivity/bluetooth/core/bt-host/testing/fake_peer.h" +#include <cstdio> +#include <future> +#include <thread> -#include "fake_device.h" +#include "src/connectivity/bluetooth/core/bt-host/testing/fake_peer.h" -using ::bt::common::DeviceAddress; +using ::bt::DeviceAddress; using ::bt::testing::FakeController; using ::bt::testing::FakePeer; @@ -37,10 +37,8 @@ static zx_protocol_device_t bthci_fake_device_ops = { -> zx_status_t { return DEV(ctx)->GetProtocol(proto_id, out_proto); }, .unbind = [](void* ctx) { DEV(ctx)->Unbind(); }, .release = [](void* ctx) { DEV(ctx)->Release(); }, - .message = [](void* ctx, fidl_msg_t* msg, fidl_txn_t* txn) { - return DEV(ctx)->Message(msg, txn); - } -}; + .message = [](void* ctx, fidl_msg_t* msg, + fidl_txn_t* txn) { return DEV(ctx)->Message(msg, txn); }}; static bt_hci_protocol_ops_t hci_protocol_ops = { .open_command_channel = [](void* ctx, zx_handle_t chan) -> zx_status_t { @@ -77,7 +75,7 @@ zx_status_t Device::Bind() { // A Sample LE remote peer for le-scan to pick up. // TODO(BT-229): add tooling for adding/removing fake devices - const auto kAdvData0 = bt::common::CreateStaticByteBuffer( + const auto kAdvData0 = bt::CreateStaticByteBuffer( // Flags 0x02, 0x01, 0x02, @@ -93,7 +91,7 @@ zx_status_t Device::Bind() { // A Sample BR/EDR remote peer to interact with. peer = std::make_unique<FakePeer>(kAddress1, false, false); // A Toy Game - peer->set_class_of_device(bt::common::DeviceClass({0x14, 0x08, 0x00})); + peer->set_class_of_device(bt::DeviceClass({0x14, 0x08, 0x00})); fake_device_->AddPeer(std::move(peer)); // Add a LE peer that always fails to connect. diff --git a/src/connectivity/bluetooth/hci/intel/firmware_loader.cc b/src/connectivity/bluetooth/hci/intel/firmware_loader.cc index 4512f2ac3013944c0dae009f8250501e9788e715..5248a36e570d3d52d9d83d851fe38a4aaec0f9d7 100644 --- a/src/connectivity/bluetooth/hci/intel/firmware_loader.cc +++ b/src/connectivity/bluetooth/hci/intel/firmware_loader.cc @@ -3,28 +3,27 @@ // found in the LICENSE file. #include "firmware_loader.h" -#include "logging.h" #include <endian.h> +#include <fbl/string_printf.h> +#include <fbl/unique_fd.h> #include <fcntl.h> #include <string.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> +#include <zircon/status.h> #include <iostream> #include <limits> +#include "logging.h" #include "src/connectivity/bluetooth/core/bt-host/hci/control_packets.h" -#include <fbl/string_printf.h> -#include <fbl/unique_fd.h> -#include <zircon/status.h> - namespace btintel { -using ::bt::common::BufferView; -using ::bt::common::PacketView; +using ::bt::BufferView; +using ::bt::PacketView; FirmwareLoader::LoadStatus FirmwareLoader::LoadBseq(const void* firmware, const size_t& len) { diff --git a/src/connectivity/bluetooth/hci/intel/vendor_hci.cc b/src/connectivity/bluetooth/hci/intel/vendor_hci.cc index 367051008e6d70cdc48b9c649a5d5c7c173677dd..3e909f69e5b1ae05a698f56382ad8109a623f934 100644 --- a/src/connectivity/bluetooth/hci/intel/vendor_hci.cc +++ b/src/connectivity/bluetooth/hci/intel/vendor_hci.cc @@ -3,15 +3,15 @@ // found in the LICENSE file. #include "vendor_hci.h" -#include "logging.h" #include <fbl/algorithm.h> #include <lib/zx/object.h> #include <lib/zx/time.h> - #include <zircon/status.h> #include <zircon/syscalls.h> +#include "logging.h" + namespace btintel { using ::bt::hci::CommandPacket; @@ -96,7 +96,7 @@ void VendorHci::SendVendorReset() const { } bool VendorHci::SendSecureSend(uint8_t type, - const bt::common::BufferView& bytes) const { + const bt::BufferView& bytes) const { size_t left = bytes.size(); while (left > 0) { size_t frag_len = fbl::min(left, kMaxSecureSendArgLen); @@ -139,8 +139,8 @@ bool VendorHci::SendSecureSend(uint8_t type, } bool VendorHci::SendAndExpect( - const bt::common::PacketView<bt::hci::CommandHeader>& command, - std::deque<bt::common::BufferView> events) const { + const bt::PacketView<bt::hci::CommandHeader>& command, + std::deque<bt::BufferView> events) const { SendCommand(command); while (events.size() > 0) { @@ -208,7 +208,7 @@ bool VendorHci::ExitManufacturerMode(MfgDisableMode mode) { } void VendorHci::SendCommand( - const bt::common::PacketView<bt::hci::CommandHeader>& command) const { + const bt::PacketView<bt::hci::CommandHeader>& command) const { zx_status_t status = ctrl_->write(0, command.data().data(), command.size(), nullptr, 0); if (status < 0) { diff --git a/src/connectivity/bluetooth/hci/intel/vendor_hci.h b/src/connectivity/bluetooth/hci/intel/vendor_hci.h index 0d2d0a4331d923efd8aea76181edd565b19ae040..932bda8916a4a1be0fc21ecebea21a682701cd40 100644 --- a/src/connectivity/bluetooth/hci/intel/vendor_hci.h +++ b/src/connectivity/bluetooth/hci/intel/vendor_hci.h @@ -52,7 +52,7 @@ struct ReadBootParamsReturnParams { bt::hci::GenericEnableParam otp_lock; bt::hci::GenericEnableParam api_lock; bt::hci::GenericEnableParam debug_lock; - bt::common::DeviceAddressBytes otp_bdaddr; + bt::DeviceAddressBytes otp_bdaddr; uint8_t min_fw_build_num; uint8_t min_fw_build_week; uint8_t min_fw_build_year; @@ -110,11 +110,10 @@ class VendorHci { void SendVendorReset() const; - bool SendSecureSend(uint8_t type, const bt::common::BufferView& bytes) const; + bool SendSecureSend(uint8_t type, const bt::BufferView& bytes) const; - bool SendAndExpect( - const bt::common::PacketView<bt::hci::CommandHeader>& command, - std::deque<bt::common::BufferView> events) const; + bool SendAndExpect(const bt::PacketView<bt::hci::CommandHeader>& command, + std::deque<bt::BufferView> events) const; void EnterManufacturerMode(); @@ -131,8 +130,7 @@ class VendorHci { // True when we are in Manufacturer Mode bool manufacturer_; - void SendCommand( - const bt::common::PacketView<bt::hci::CommandHeader>& command) const; + void SendCommand(const bt::PacketView<bt::hci::CommandHeader>& command) const; std::unique_ptr<bt::hci::EventPacket> WaitForEventPacket( zx::duration timeout = zx::sec(5), diff --git a/src/connectivity/bluetooth/tools/bt-hci-tool/commands.cc b/src/connectivity/bluetooth/tools/bt-hci-tool/commands.cc index 892040fc2bf094be08a9e15cf24f1da82983d0f7..88292cc4976cbd4e789139f65e27be9cf6410eaa 100644 --- a/src/connectivity/bluetooth/tools/bt-hci-tool/commands.cc +++ b/src/connectivity/bluetooth/tools/bt-hci-tool/commands.cc @@ -124,7 +124,7 @@ void DisplayAdvertisingReport(const ::bt::hci::LEAdvertisingReportData& data, int8_t rssi, const std::string& name_filter, const std::string& addr_type_filter) { ::bt::gap::AdvertisingDataReader reader( - ::bt::common::BufferView(data.data, data.length_data)); + ::bt::BufferView(data.data, data.length_data)); // The AD fields that we'll parse out. uint8_t flags = 0; @@ -133,7 +133,7 @@ void DisplayAdvertisingReport(const ::bt::hci::LEAdvertisingReportData& data, bool tx_power_present = false; ::bt::gap::DataType type; - ::bt::common::BufferView adv_data_field; + ::bt::BufferView adv_data_field; while (reader.GetNextField(&type, &adv_data_field)) { switch (type) { case ::bt::gap::DataType::kFlags: @@ -226,8 +226,7 @@ bool HandleVersionInfo(const CommandData* cmd_data, << ::bt::hci::HCIVersionToString(params->hci_version) << std::endl; std::cout << " Manufacturer Name: " - << ::bt::common::GetManufacturerName( - le16toh(params->manufacturer_name)) + << ::bt::GetManufacturerName(le16toh(params->manufacturer_name)) << std::endl; complete_cb(); diff --git a/src/connectivity/bluetooth/tools/bt-hci-tool/main.cc b/src/connectivity/bluetooth/tools/bt-hci-tool/main.cc index 8d37d8ae01f8542b821da50de9ffb13be7df3ddd..f4a44dd5850957551b334aa2dbb868653c9559c1 100644 --- a/src/connectivity/bluetooth/tools/bt-hci-tool/main.cc +++ b/src/connectivity/bluetooth/tools/bt-hci-tool/main.cc @@ -2,29 +2,27 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include <cstdio> -#include <iostream> - -#include <fcntl.h> -#include <sys/stat.h> - #include <ddk/driver.h> #include <fbl/unique_fd.h> +#include <fcntl.h> #include <lib/async-loop/cpp/loop.h> #include <lib/fdio/directory.h> #include <lib/fdio/fdio.h> +#include <sys/stat.h> + +#include <cstdio> +#include <iostream> +#include "commands.h" +#include "lib/fit/defer.h" #include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" #include "src/connectivity/bluetooth/core/bt-host/common/log.h" #include "src/connectivity/bluetooth/core/bt-host/hci/device_wrapper.h" #include "src/connectivity/bluetooth/core/bt-host/hci/hci.h" #include "src/connectivity/bluetooth/core/bt-host/hci/transport.h" -#include "lib/fit/defer.h" -#include "src/lib/fxl/command_line.h" #include "src/connectivity/bluetooth/tools/lib/command_dispatcher.h" #include "src/lib/files/unique_fd.h" - -#include "commands.h" +#include "src/lib/fxl/command_line.h" namespace { @@ -48,11 +46,11 @@ int main(int argc, char* argv[]) { return EXIT_SUCCESS; } - auto severity = bt::common::LogSeverity::ERROR; + auto severity = bt::LogSeverity::ERROR; if (cl.HasOption("verbose", nullptr)) { - severity = bt::common::LogSeverity::TRACE; + severity = bt::LogSeverity::TRACE; } - bt::common::UsePrintf(severity); + bt::UsePrintf(severity); std::string hci_dev_path = kDefaultHCIDev; if (cl.GetOptionValue("dev", &hci_dev_path) && hci_dev_path.empty()) { diff --git a/src/connectivity/bluetooth/tools/bt-intel-tool/bt_intel.h b/src/connectivity/bluetooth/tools/bt-intel-tool/bt_intel.h index 68cee89f1c4d6d6c02ec84d40b7e331dc54964d8..4f870d48495825137d1b29626c38a7dfed5bf72a 100644 --- a/src/connectivity/bluetooth/tools/bt-intel-tool/bt_intel.h +++ b/src/connectivity/bluetooth/tools/bt-intel-tool/bt_intel.h @@ -42,7 +42,7 @@ struct IntelReadBootParamsReturnParams { ::bt::hci::GenericEnableParam otp_lock; ::bt::hci::GenericEnableParam api_lock; ::bt::hci::GenericEnableParam debug_lock; - ::bt::common::DeviceAddressBytes otp_bdaddr; + ::bt::DeviceAddressBytes otp_bdaddr; uint8_t min_fw_build_num; uint8_t min_fw_build_week; uint8_t min_fw_build_year; diff --git a/src/connectivity/bluetooth/tools/bt-intel-tool/command_channel.cc b/src/connectivity/bluetooth/tools/bt-intel-tool/command_channel.cc index 7c55c73ae8d6b1f9c642b40d3de04e30353e2dee..91490d604711dfb7f341ab96194a0218d7b5c73f 100644 --- a/src/connectivity/bluetooth/tools/bt-intel-tool/command_channel.cc +++ b/src/connectivity/bluetooth/tools/bt-intel-tool/command_channel.cc @@ -5,9 +5,6 @@ #include "command_channel.h" #include <fcntl.h> - -#include <iostream> - #include <lib/async-loop/cpp/loop.h> #include <lib/async/default.h> #include <lib/zx/event.h> @@ -15,11 +12,11 @@ #include <lib/zx/timer.h> #include <zircon/status.h> -#include "bt_intel.h" - -#include "src/lib/fxl/strings/string_printf.h" +#include <iostream> +#include "bt_intel.h" #include "src/connectivity/bluetooth/core/bt-host/hci/slab_allocators.h" +#include "src/lib/fxl/strings/string_printf.h" namespace { @@ -36,7 +33,7 @@ zx::channel GetCommandChannel(int fd) { } status = fuchsia_hardware_bluetooth_HciOpenCommandChannel( - fdio_unsafe_borrow_channel(hci_io), theirs.release()); + fdio_unsafe_borrow_channel(hci_io), theirs.release()); fdio_unsafe_release(hci_io); if (status != ZX_OK) { @@ -60,7 +57,7 @@ zx::channel GetAclChannel(int fd) { } status = fuchsia_hardware_bluetooth_HciOpenAclDataChannel( - fdio_unsafe_borrow_channel(hci_io), theirs.release()); + fdio_unsafe_borrow_channel(hci_io), theirs.release()); fdio_unsafe_release(hci_io); if (status != ZX_OK) { @@ -113,7 +110,7 @@ void CommandChannel::SetEventCallback(EventCallback callback) { } void CommandChannel::SendCommand( - const ::bt::common::PacketView<::bt::hci::CommandHeader>& command) { + const ::bt::PacketView<::bt::hci::CommandHeader>& command) { zx::channel* channel = &cmd_channel_; // Bootloader Secure Send commands are sent and responded to via the bulk // endpoint (ACL channel) @@ -130,7 +127,7 @@ void CommandChannel::SendCommand( } void CommandChannel::SendCommandSync( - const ::bt::common::PacketView<::bt::hci::CommandHeader>& command, + const ::bt::PacketView<::bt::hci::CommandHeader>& command, EventCallback callback) { bool received = false; auto previous_cb = std::move(event_callback_); diff --git a/src/connectivity/bluetooth/tools/bt-intel-tool/command_channel.h b/src/connectivity/bluetooth/tools/bt-intel-tool/command_channel.h index 4832bccb85d17c2a2c6dffe0896802ada88600cf..f9bf85b621b062482da584613987d84c603c5f0f 100644 --- a/src/connectivity/bluetooth/tools/bt-intel-tool/command_channel.h +++ b/src/connectivity/bluetooth/tools/bt-intel-tool/command_channel.h @@ -36,14 +36,13 @@ class CommandChannel { // Sends the command in |command| to the controller. The channel must // be Ready when this is called. - void SendCommand( - const ::bt::common::PacketView<::bt::hci::CommandHeader>& command); + void SendCommand(const ::bt::PacketView<::bt::hci::CommandHeader>& command); // Sends the command in |command| to the controller and waits for // an Event, which is delivered to |callback| before this function // returns. void SendCommandSync( - const ::bt::common::PacketView<::bt::hci::CommandHeader>& command, + const ::bt::PacketView<::bt::hci::CommandHeader>& command, EventCallback callback); private: diff --git a/src/connectivity/bluetooth/tools/bt-intel-tool/intel_firmware_loader.cc b/src/connectivity/bluetooth/tools/bt-intel-tool/intel_firmware_loader.cc index 016ed7020b435763a21b94cb1e61e3d2c1d5b151..1ef9fcd32e61d05f503955e0d53d2a0a8fa6246a 100644 --- a/src/connectivity/bluetooth/tools/bt-intel-tool/intel_firmware_loader.cc +++ b/src/connectivity/bluetooth/tools/bt-intel-tool/intel_firmware_loader.cc @@ -5,30 +5,28 @@ #include "intel_firmware_loader.h" #include <endian.h> -#include <fcntl.h> -#include <string.h> -#include <sys/mman.h> -#include <sys/stat.h> -#include <unistd.h> - -#include <iostream> -#include <limits> - #include <fbl/string_printf.h> #include <fbl/unique_fd.h> +#include <fcntl.h> #include <lib/async-loop/cpp/loop.h> #include <lib/async/default.h> #include <lib/zx/event.h> #include <lib/zx/time.h> #include <lib/zx/timer.h> +#include <string.h> +#include <sys/mman.h> +#include <sys/stat.h> +#include <unistd.h> #include <zircon/status.h> -#include "bt_intel.h" +#include <iostream> +#include <limits> +#include "bt_intel.h" #include "src/lib/fxl/strings/string_printf.h" -using ::bt::common::BufferView; -using ::bt::common::PacketView; +using ::bt::BufferView; +using ::bt::PacketView; namespace bt_intel { diff --git a/src/connectivity/bluetooth/tools/bt-intel-tool/intel_firmware_loader.h b/src/connectivity/bluetooth/tools/bt-intel-tool/intel_firmware_loader.h index cc6dc897e235e05a8af456897a9a77119e4361fd..238a60f9d17db50547d274ae76d225c7763f1e3f 100644 --- a/src/connectivity/bluetooth/tools/bt-intel-tool/intel_firmware_loader.h +++ b/src/connectivity/bluetooth/tools/bt-intel-tool/intel_firmware_loader.h @@ -9,9 +9,8 @@ #include <deque> -#include "src/connectivity/bluetooth/core/bt-host/hci/control_packets.h" - #include "command_channel.h" +#include "src/connectivity/bluetooth/core/bt-host/hci/control_packets.h" namespace bt_intel { @@ -51,8 +50,8 @@ class IntelFirmwareLoader { // Returns true if the events returned matched the expected |event_bytes|, // false otherwise. bool RunCommandAndExpect( - const ::bt::common::PacketView<::bt::hci::CommandHeader>& command, - std::deque<::bt::common::BufferView>& event_bytes); + const ::bt::PacketView<::bt::hci::CommandHeader>& command, + std::deque<::bt::BufferView>& event_bytes); // The command channel to use CommandChannel* channel_; diff --git a/src/connectivity/bluetooth/tools/bt-intel-tool/main.cc b/src/connectivity/bluetooth/tools/bt-intel-tool/main.cc index 439249a79f28ae500b743784b21e7c47921317e5..4337d8c81fdd62b553abcbd769051823c5815bba 100644 --- a/src/connectivity/bluetooth/tools/bt-intel-tool/main.cc +++ b/src/connectivity/bluetooth/tools/bt-intel-tool/main.cc @@ -2,25 +2,23 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include <cstdio> -#include <iostream> - +#include <ddk/driver.h> #include <fcntl.h> +#include <lib/async-loop/cpp/loop.h> #include <sys/stat.h> -#include <ddk/driver.h> -#include <lib/async-loop/cpp/loop.h> +#include <cstdio> +#include <iostream> +#include "command_channel.h" +#include "commands.h" #include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" #include "src/connectivity/bluetooth/core/bt-host/common/log.h" #include "src/connectivity/bluetooth/core/bt-host/hci/device_wrapper.h" #include "src/connectivity/bluetooth/core/bt-host/hci/hci.h" #include "src/connectivity/bluetooth/core/bt-host/hci/transport.h" -#include "src/lib/fxl/command_line.h" #include "src/connectivity/bluetooth/tools/lib/command_dispatcher.h" - -#include "command_channel.h" -#include "commands.h" +#include "src/lib/fxl/command_line.h" namespace { @@ -48,11 +46,11 @@ int main(int argc, char* argv[]) { return EXIT_SUCCESS; } - auto severity = bt::common::LogSeverity::ERROR; + auto severity = bt::LogSeverity::ERROR; if (cl.HasOption("verbose", nullptr)) { - severity = bt::common::LogSeverity::TRACE; + severity = bt::LogSeverity::TRACE; } - bt::common::UsePrintf(severity); + bt::UsePrintf(severity); std::string hci_dev_path = kDefaultHCIDev; if (cl.GetOptionValue("dev", &hci_dev_path) && hci_dev_path.empty()) {