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 "pw_bytes/endian.h" 17 #include "pw_bytes/span.h" 18 #include "pw_protobuf/decoder.h" 19 #include "pw_result/result.h" 20 #include "pw_status/status.h" 21 #include "pw_status/try.h" 22 23 namespace pw::protobuf { 24 25 // Decodes a proto message bytes field to a uint32_t value. The caller must 26 // advance the decoder and check the field number prior to calling this function 27 // otherwise there is undefined behavior. E.g. 28 // 29 // Decoder decoder(buffer); 30 // protobuf::Decoder decoder(request); 31 // if (!decoder.Next().ok()) { 32 // // HANDLE ERROR. 33 // } 34 // if (static_cast<MyProtoMessage::Fields>(decoder.FieldNumber()) != 35 // MyProtoMessage::Fields::kMyFields) { 36 // // HANDLE ERROR. 37 // } 38 // Result<uint32_t> result = DecodeBytesToUint32(decoder); 39 // if (result.ok()) { 40 // // DO SOMETHING WITH result.value(). 41 // } 42 // 43 // Returns: 44 // OK - Byte entry is successfully read. 45 // DATA_LOSS: Invalid protobuf data. 46 // INVALID_ARGUMENT - not able to read exactly 4 bytes. 47 // FAILED_PRECONDITION - no bytes were read. DecodeBytesToUint32(Decoder & decoder)48inline Result<uint32_t> DecodeBytesToUint32(Decoder& decoder) { 49 ConstByteSpan bytes_read; 50 PW_TRY(decoder.ReadBytes(&bytes_read)); 51 if (bytes_read.size() != sizeof(uint32_t)) { 52 return Status::InvalidArgument(); 53 } 54 uint32_t value; 55 if (!bytes::ReadInOrder(endian::little, bytes_read, value)) { 56 return Status::Internal(); 57 } 58 return value; 59 } 60 61 } // namespace pw::protobuf 62