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 #include <mutex>
19 
20 namespace pw::router {
21 
RoutePacket(ConstByteSpan packet)22 Status StaticRouter::RoutePacket(ConstByteSpan packet) {
23   uint32_t address;
24 
25   {
26     // Only packet parsing is synchronized within the router; egresses must be
27     // synchronized externally.
28     std::lock_guard lock(mutex_);
29 
30     if (!parser_.Parse(packet)) {
31       parser_errors_.Increment();
32       return Status::DataLoss();
33     }
34 
35     std::optional<uint32_t> result = parser_.GetDestinationAddress();
36     if (!result.has_value()) {
37       parser_errors_.Increment();
38       return Status::DataLoss();
39     }
40 
41     address = result.value();
42   }
43 
44   auto route = std::find_if(routes_.begin(), routes_.end(), [&](auto r) {
45     return r.address == address;
46   });
47   if (route == routes_.end()) {
48     route_errors_.Increment();
49     return Status::NotFound();
50   }
51 
52   if (Status status = route->egress.SendPacket(packet); !status.ok()) {
53     egress_errors_.Increment();
54     return Status::Unavailable();
55   }
56 
57   return OkStatus();
58 }
59 
60 }  // namespace pw::router
61