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 #pragma once 15 16 #include <cstddef> 17 18 #include "pw_varint/varint.h" 19 20 namespace pw::hdlc { 21 22 inline constexpr std::byte kFlag = std::byte{0x7E}; 23 inline constexpr std::byte kEscape = std::byte{0x7D}; 24 inline constexpr std::byte kEscapeConstant = std::byte{0x20}; 25 26 inline constexpr std::array<std::byte, 2> kEscapedFlag = {kEscape, 27 std::byte{0x5E}}; 28 inline constexpr std::array<std::byte, 2> kEscapedEscape = {kEscape, 29 std::byte{0x5D}}; 30 31 inline constexpr varint::Format kAddressFormat = 32 varint::Format::kOneTerminatedLeastSignificant; 33 NeedsEscaping(std::byte b)34constexpr bool NeedsEscaping(std::byte b) { 35 return (b == kFlag || b == kEscape); 36 } 37 Escape(std::byte b)38constexpr std::byte Escape(std::byte b) { return b ^ kEscapeConstant; } 39 40 // Class that manages the 1-byte control field of an HDLC U-frame. 41 class UFrameControl { 42 public: UnnumberedInformation()43 static constexpr UFrameControl UnnumberedInformation() { 44 return UFrameControl(kUnnumberedInformation); 45 } 46 data()47 constexpr std::byte data() const { return data_; } 48 49 private: 50 // Types of HDLC U-frames and their bit patterns. 51 enum Type : uint8_t { 52 kUnnumberedInformation = 0x00, 53 }; 54 UFrameControl(Type type)55 constexpr UFrameControl(Type type) 56 : data_(kUFramePattern | std::byte{type}) {} 57 58 // U-frames are identified by having the bottom two control bits set. 59 static constexpr std::byte kUFramePattern = std::byte{0x03}; 60 61 std::byte data_; 62 }; 63 64 } // namespace pw::hdlc 65