blob: 7e4325b37324bff873974984b4684ab90ca03c00 [file] [edit]
// 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.
//
#include "utils/riegeli.h"
#include <algorithm>
#include <cstring>
#include <string>
#include "riegeli/base/arithmetic.h"
#include "riegeli/bytes/reader.h"
namespace credentio {
bool ReadNullTerminatedString(riegeli::Reader& reader, size_t max_length,
std::string& output) {
reader.Pull(max_length);
if (reader.available() == 0) {
// The data ends. Avoid undefined behavior in `std::memchr(nullptr, _, _)`
// if `reader.cursor() == nullptr`.
return false;
}
const char* const terminator = static_cast<const char*>(std::memchr(
reader.cursor(), '\0', std::min(reader.available(), max_length)));
if (terminator == nullptr) {
// No null terminator found within the max_length.
return false;
}
size_t length = riegeli::PtrDistance(reader.cursor(), terminator);
if (!reader.Read(length, output)) {
// Failed to read the string.
return false;
}
if (!reader.Skip(1)) {
// Failed to skip the null terminator.
return false;
}
return true;
}
} // namespace credentio