• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_hdlc/wire_packet_parser.h"
16 
17 #include "pw_bytes/endian.h"
18 #include "pw_checksum/crc32.h"
19 #include "pw_hdlc/decoder.h"
20 #include "pw_hdlc/internal/protocol.h"
21 
22 namespace pw::hdlc {
23 
Parse(ConstByteSpan packet)24 bool WirePacketParser::Parse(ConstByteSpan packet) {
25   if (packet.size_bytes() < Frame::kMinSizeBytes) {
26     return false;
27   }
28 
29   if (packet.front() != kFlag || packet.back() != kFlag) {
30     return false;
31   }
32 
33   // Partially decode into a buffer with space only for the address and control
34   // fields of the frame. The decoder will verify the frame's FCS field.
35   std::array<std::byte, 16> buffer = {};
36   Decoder decoder(buffer);
37   Status status = Status::Unknown();
38 
39   decoder.Process(packet, [&status](const Result<Frame>& result) {
40     status = result.status();
41   });
42 
43   Result<Frame> result = Frame::Parse(buffer);
44   if (!result.ok()) {
45     return false;
46   }
47 
48   address_ = result.value().address();
49 
50   // RESOURCE_EXHAUSTED is expected as the buffer is too small for the packet.
51   return status.ok() || status.IsResourceExhausted();
52 }
53 
54 }  // namespace pw::hdlc
55