C/C++ API Reference
Loading...
Searching...
No Matches
bytes_utils.h
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
23namespace pw::protobuf {
24
26
27// Decodes a proto message bytes field to a uint32_t value. The caller must
28// advance the decoder and check the field number prior to calling this function
29// otherwise there is undefined behavior. E.g.
30//
31// Decoder decoder(buffer);
32// protobuf::Decoder decoder(request);
33// if (!decoder.Next().ok()) {
34// // HANDLE ERROR.
35// }
36// if (static_cast<MyProtoMessage::Fields>(decoder.FieldNumber()) !=
37// MyProtoMessage::Fields::kMyFields) {
38// // HANDLE ERROR.
39// }
40// Result<uint32_t> result = DecodeBytesToUint32(decoder);
41// if (result.ok()) {
42// // DO SOMETHING WITH result.value().
43// }
44//
45// Returns:
46// OK - Byte entry is successfully read.
47// DATA_LOSS: Invalid protobuf data.
48// INVALID_ARGUMENT - not able to read exactly 4 bytes.
49// FAILED_PRECONDITION - no bytes were read.
50inline Result<uint32_t> DecodeBytesToUint32(Decoder& decoder) {
51 ConstByteSpan bytes_read;
52 PW_TRY(decoder.ReadBytes(&bytes_read));
53 if (bytes_read.size() != sizeof(uint32_t)) {
55 }
56 uint32_t value;
57 if (!bytes::ReadInOrder(endian::little, bytes_read, value)) {
58 return Status::Internal();
59 }
60 return value;
61}
62
64
65} // namespace pw::protobuf
static constexpr Status InvalidArgument()
Definition: status.h:164
static constexpr Status Internal()
Definition: status.h:292
T ReadInOrder(endian order, const void *buffer)
Definition: endian.h:168
#define PW_TRY(expr)
Returns early if expr is a non-OK Status or Result.
Definition: try.h:27