| // 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_RIEGELI_H_ | |
| #define THIRD_PARTY_CREDENTIO_UTILS_RIEGELI_H_ | |
| #include <cstddef> | |
| #include <cstdint> | |
| #include <limits> | |
| #include <string> | |
| #include "absl/status/status.h" | |
| #include "absl/status/statusor.h" | |
| #include "absl/strings/str_cat.h" | |
| #include "riegeli/bytes/reader.h" | |
| #include "riegeli/bytes/writer.h" | |
| #include "riegeli/endian/endian_reading.h" | |
| #include "riegeli/endian/endian_writing.h" | |
| namespace credentio { | |
| // Reads a single value of type `T` from the source in big endian order, adds | |
| // the adjustment value and writes it to the destination. Returns the adjusted | |
| // number. An error is returned if the adjusted value is too large to fit in a | |
| // `T` or if either reading or writing fails. | |
| template <typename T> | |
| absl::StatusOr<T> CopyBigEndian(riegeli::Reader& source, | |
| riegeli::Writer& destination, | |
| uint64_t adjustment = 0) { | |
| T offset; | |
| if (!riegeli::ReadBigEndian<T>(source, offset)) { | |
| return source.StatusOrAnnotate(absl::DataLossError( | |
| absl::StrCat("Failed to read unsigned integer of size: ", sizeof(T)))); | |
| } | |
| T space_remaining = std::numeric_limits<T>::max() - offset; | |
| if (space_remaining < adjustment) { | |
| return absl::DataLossError("The adjusted offset is too large to fit"); | |
| } | |
| offset += adjustment; | |
| if (!riegeli::WriteBigEndian<T>(offset, destination)) { | |
| return destination.status(); | |
| } | |
| return offset; | |
| } | |
| // Reads a null terminated string from the source into the output string. | |
| // Returns false if the read or seek fails or if no null terminator was | |
| // encountered within the given max_length. Returns true otherwise. | |
| bool ReadNullTerminatedString(riegeli::Reader& reader, size_t max_length, | |
| std::string& output); | |
| } // namespace credentio | |
| #endif // THIRD_PARTY_CREDENTIO_UTILS_RIEGELI_H_ |