| // Copyright 2026 Google LLC |
| // |
| // Licensed under the Apache License, Version 2.0 (the "License"); |
| // you may not use this file except in compliance with the License. |
| // You may obtain a copy of the License at |
| // |
| // https://www.apache.org/licenses/LICENSE-2.0 |
| // |
| // Unless required by applicable law or agreed to in writing, software |
| // distributed under the License is distributed on an "AS IS" BASIS, |
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| // See the License for the specific language governing permissions and |
| // limitations under the License. |
| // |
| |
| #ifndef THIRD_PARTY_CREDENTIO_UTILS_BYTE_READERS_H_ |
| #define THIRD_PARTY_CREDENTIO_UTILS_BYTE_READERS_H_ |
| |
| #include "absl/status/status.h" |
| #include "absl/status/status_macros.h" |
| #include "absl/status/statusor.h" |
| #include "absl/strings/str_format.h" |
| #include "absl/strings/string_view.h" |
| #include "riegeli/endian/endian_reading.h" |
| |
| namespace credentio { |
| |
| // Reads a big-endian unsigned integer of type `N` from the supplied segment. |
| // Returns an error if the segment is not large enough to contain the integer. |
| template <typename N> |
| absl::StatusOr<N> ReadUint(absl::string_view segment) { |
| if (segment.size() < sizeof(N)) { |
| return absl::InvalidArgumentError(absl::StrFormat( |
| "Segment of length %d is not large enough to contain a %d byte " |
| "unsigned integer", |
| segment.size(), sizeof(N))); |
| } |
| return riegeli::ReadBigEndian<N>(segment.data()); |
| } |
| |
| // Reads a big-endian unsigned integer of type `N` from the supplied segment and |
| // removes the bytes from the segment. Returns an error if the segment is not |
| // large enough to contain the integer and does not remove any bytes from the |
| // segment. |
| template <typename N> |
| absl::StatusOr<N> ConsumeUint(absl::string_view* segment) { |
| if (segment == nullptr) { |
| return absl::InvalidArgumentError("Segment is null"); |
| } |
| ABSL_ASSIGN_OR_RETURN(auto result, ReadUint<N>(*segment)); |
| segment->remove_prefix(sizeof(N)); |
| return result; |
| } |
| |
| // Skips `sizeof(N)` bytes from the supplied segment. Returns an error if the |
| // segment is not large enough to contain `sizeof(N)` bytes and does not remove |
| // any bytes from the segment. |
| template <typename N> |
| absl::Status SkipBytes(absl::string_view* segment) { |
| if (segment == nullptr) { |
| return absl::InvalidArgumentError("Segment is null"); |
| } |
| if (segment->size() < sizeof(N)) { |
| return absl::InvalidArgumentError(absl::StrFormat( |
| "Segment of length %d is not large enough to skip %d bytes", |
| segment->size(), sizeof(N))); |
| } |
| segment->remove_prefix(sizeof(N)); |
| return absl::OkStatus(); |
| } |
| |
| } // namespace credentio |
| |
| #endif // THIRD_PARTY_CREDENTIO_UTILS_BYTE_READERS_H_ |