xref: /aosp_15_r20/external/pigweed/pw_rpc/channel_list.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2022 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 #include "pw_rpc/internal/channel_list.h"
16 
17 namespace pw::rpc::internal {
18 
Get(uint32_t channel_id) const19 const Channel* ChannelList::Get(uint32_t channel_id) const {
20   for (const Channel& channel : channels_) {
21     if (channel.id() == channel_id) {
22       return &channel;
23     }
24   }
25   return nullptr;
26 }
27 
Add(uint32_t channel_id,ChannelOutput & output)28 Status ChannelList::Add(uint32_t channel_id, ChannelOutput& output) {
29   if (Get(channel_id) != nullptr) {
30     return Status::AlreadyExists();
31   }
32 
33 #if PW_RPC_DYNAMIC_ALLOCATION
34   channels_.emplace_back(Channel(channel_id, &output));
35 #else
36   Channel* new_channel = Get(Channel::kUnassignedChannelId);
37   if (new_channel == nullptr) {
38     return Status::ResourceExhausted();
39   }
40 
41   new_channel->Configure(channel_id, output);
42 #endif  // PW_RPC_DYNAMIC_ALLOCATION
43 
44   return OkStatus();
45 }
46 
Remove(uint32_t channel_id)47 Status ChannelList::Remove(uint32_t channel_id) {
48   Channel* channel = Get(channel_id);
49 
50   if (channel == nullptr) {
51     return Status::NotFound();
52   }
53   channel->Close();
54 
55 #if PW_RPC_DYNAMIC_ALLOCATION
56   // Order isn't important, so move the channel to the back then pop it.
57   std::swap(*channel, channels_.back());
58   channels_.pop_back();
59 #endif  // PW_RPC_DYNAMIC_ALLOCATION
60 
61   return OkStatus();
62 }
63 
64 }  // namespace pw::rpc::internal
65