xref: /aosp_15_r20/external/pigweed/pw_router/static_router.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2021 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_router/static_router.h"
16 
17 #include <algorithm>
18 
19 namespace pw::router {
20 
RoutePacket(ConstByteSpan packet,PacketParser & parser)21 Status StaticRouter::RoutePacket(ConstByteSpan packet, PacketParser& parser) {
22   if (!parser.Parse(packet)) {
23     parser_errors_.Increment();
24     return Status::DataLoss();
25   }
26 
27   std::optional<uint32_t> maybe_address = parser.GetDestinationAddress();
28   if (!maybe_address.has_value()) {
29     parser_errors_.Increment();
30     return Status::DataLoss();
31   }
32 
33   auto route = std::find_if(routes_.begin(), routes_.end(), [&](auto r) {
34     return r.address == *maybe_address;
35   });
36   if (route == routes_.end()) {
37     route_errors_.Increment();
38     return Status::NotFound();
39   }
40 
41   if (Status status = route->egress.SendPacket(packet, parser); !status.ok()) {
42     egress_errors_.Increment();
43     return Status::Unavailable();
44   }
45 
46   return OkStatus();
47 }
48 
49 }  // namespace pw::router
50