1 // Copyright 2023 The Pigweed Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 4 // use this file except in compliance with the License. You may obtain a copy of 5 // the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 // License for the specific language governing permissions and limitations under 13 // the License. 14 15 #pragma once 16 #include "pw_bluetooth_sapphire/internal/host/common/macros.h" 17 #include "pw_bluetooth_sapphire/internal/host/l2cap/channel.h" 18 19 namespace bt::l2cap { 20 21 // A Channel wrapper that automatically deactivates a channel when it gets 22 // deleted. 23 class ScopedChannel final { 24 public: 25 explicit ScopedChannel(Channel::WeakPtr channel); 26 ScopedChannel() = default; 27 ScopedChannel(ScopedChannel&& other); 28 ~ScopedChannel(); 29 30 // Returns true if there is an open underlying channel. is_active()31 [[nodiscard]] bool is_active() const { return chan_.is_alive(); } 32 33 // Resets the underlying channel to the one that is provided. Any previous 34 // channel will be deactivated. 35 void Reset(Channel::WeakPtr new_channel); 36 decltype(nullptr)37 ScopedChannel& operator=(decltype(nullptr)) { 38 Close(); 39 return *this; 40 } 41 explicit operator bool() const { return is_active(); } 42 get()43 const Channel::WeakPtr& get() const { return chan_; } 44 Channel* operator->() const { return &chan_.get(); } 45 46 // Returns a copy of the underlying Channel reference without releasing 47 // ownership. The channel will still be deactivated when this goes out 48 // of scope. share()49 inline Channel::WeakPtr share() const { return chan_; } 50 51 private: 52 void Close(); 53 54 Channel::WeakPtr chan_; 55 56 BT_DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(ScopedChannel); 57 }; 58 59 } // namespace bt::l2cap 60