Skip to content

Commit

Permalink
[wpiutil] Return wpi::expected from MemoryBuffer::GetFile (wpilibsuit…
Browse files Browse the repository at this point in the history
  • Loading branch information
KangarooKoala authored Sep 13, 2024
1 parent d44b651 commit 1f3ef01
Show file tree
Hide file tree
Showing 15 changed files with 87 additions and 103 deletions.
8 changes: 3 additions & 5 deletions apriltag/src/main/native/cpp/AprilTagFieldLayout.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,12 @@
using namespace frc;

AprilTagFieldLayout::AprilTagFieldLayout(std::string_view path) {
std::error_code ec;
std::unique_ptr<wpi::MemoryBuffer> fileBuffer =
wpi::MemoryBuffer::GetFile(path, ec);
if (fileBuffer == nullptr || ec) {
auto fileBuffer = wpi::MemoryBuffer::GetFile(path);
if (!fileBuffer) {
throw std::runtime_error(fmt::format("Cannot open file: {}", path));
}

wpi::json json = wpi::json::parse(fileBuffer->GetCharBuffer());
wpi::json json = wpi::json::parse(fileBuffer.value()->GetCharBuffer());

for (const auto& tag : json.at("tags").get<std::vector<AprilTag>>()) {
m_apriltags[tag.ID] = tag;
Expand Down
11 changes: 5 additions & 6 deletions cameraserver/multiCameraServer/src/main/native/cpp/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -94,18 +94,17 @@ bool ReadCameraConfig(const wpi::json& config) {

bool ReadConfig() {
// open config file
std::error_code ec;
std::unique_ptr<wpi::MemoryBuffer> fileBuffer =
wpi::MemoryBuffer::GetFile(configFile, ec);
if (fileBuffer == nullptr || ec) {
wpi::print(stderr, "could not open '{}': {}\n", configFile, ec.message());
auto fileBuffer = wpi::MemoryBuffer::GetFile(configFile);
if (!fileBuffer) {
wpi::print(stderr, "could not open '{}': {}\n", configFile,
fileBuffer.error().message());
return false;
}

// parse file
wpi::json j;
try {
j = wpi::json::parse(fileBuffer->GetCharBuffer());
j = wpi::json::parse(fileBuffer.value()->GetCharBuffer());
} catch (const wpi::json::parse_error& e) {
wpi::print(stderr, "config error in '{}': byte {}: {}\n", configFile,
e.byte, e.what());
Expand Down
13 changes: 6 additions & 7 deletions datalogtool/src/main/native/cpp/Exporter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -180,17 +180,16 @@ InputFile::~InputFile() {
}

static std::unique_ptr<InputFile> LoadDataLog(std::string_view filename) {
std::error_code ec;
auto buf = wpi::MemoryBuffer::GetFile(filename, ec);
std::string fn{filename};
if (ec) {
auto fileBuffer = wpi::MemoryBuffer::GetFile(filename);
if (!fileBuffer) {
return std::make_unique<InputFile>(
fn, fmt::format("Could not open file: {}", ec.message()));
filename,
fmt::format("Could not open file: {}", fileBuffer.error().message()));
}

wpi::log::DataLogReader reader{std::move(buf)};
wpi::log::DataLogReader reader{std::move(*fileBuffer)};
if (!reader.IsValid()) {
return std::make_unique<InputFile>(fn, "Not a valid datalog file");
return std::make_unique<InputFile>(filename, "Not a valid datalog file");
}

return std::make_unique<InputFile>(
Expand Down
62 changes: 28 additions & 34 deletions glass/src/lib/native/cpp/Context.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -128,50 +128,44 @@ static bool JsonToWindow(const wpi::json& jfile, const char* filename) {
}

static bool LoadWindowStorageImpl(const std::string& filename) {
std::error_code ec;
std::unique_ptr<wpi::MemoryBuffer> fileBuffer =
wpi::MemoryBuffer::GetFile(filename, ec);
if (fileBuffer == nullptr || ec) {
auto fileBuffer = wpi::MemoryBuffer::GetFile(filename);
if (!fileBuffer) {
ImGui::LogText("error opening %s: %s", filename.c_str(),
ec.message().c_str());
fileBuffer.error().message().c_str());
return false;
}
try {
return JsonToWindow(wpi::json::parse(fileBuffer.value()->GetCharBuffer()),
filename.c_str());
} catch (wpi::json::parse_error& e) {
ImGui::LogText("Error loading %s: %s", filename.c_str(), e.what());
return false;
} else {
try {
return JsonToWindow(wpi::json::parse(fileBuffer->GetCharBuffer()),
filename.c_str());
} catch (wpi::json::parse_error& e) {
ImGui::LogText("Error loading %s: %s", filename.c_str(), e.what());
return false;
}
}
}

static bool LoadStorageRootImpl(Context* ctx, const std::string& filename,
std::string_view rootName) {
std::error_code ec;
std::unique_ptr<wpi::MemoryBuffer> fileBuffer =
wpi::MemoryBuffer::GetFile(filename, ec);
if (fileBuffer == nullptr || ec) {
auto fileBuffer = wpi::MemoryBuffer::GetFile(filename);
if (!fileBuffer) {
ImGui::LogText("error opening %s: %s", filename.c_str(),
ec.message().c_str());
fileBuffer.error().message().c_str());
return false;
} else {
auto& storage = ctx->storageRoots[rootName];
bool createdStorage = false;
if (!storage) {
storage = std::make_unique<Storage>();
createdStorage = true;
}
try {
storage->FromJson(wpi::json::parse(fileBuffer->GetCharBuffer()),
filename.c_str());
} catch (wpi::json::parse_error& e) {
ImGui::LogText("Error loading %s: %s", filename.c_str(), e.what());
if (createdStorage) {
ctx->storageRoots.erase(rootName);
}
return false;
}
auto& storage = ctx->storageRoots[rootName];
bool createdStorage = false;
if (!storage) {
storage = std::make_unique<Storage>();
createdStorage = true;
}
try {
storage->FromJson(wpi::json::parse(fileBuffer.value()->GetCharBuffer()),
filename.c_str());
} catch (wpi::json::parse_error& e) {
ImGui::LogText("Error loading %s: %s", filename.c_str(), e.what());
if (createdStorage) {
ctx->storageRoots.erase(rootName);
}
return false;
}
return true;
}
Expand Down
12 changes: 5 additions & 7 deletions glass/src/lib/native/cpp/other/Field2D.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -540,16 +540,14 @@ bool FieldInfo::LoadJson(std::span<const char> is, std::string_view filename) {
}

void FieldInfo::LoadJsonFile(std::string_view jsonfile) {
std::error_code ec;
std::unique_ptr<wpi::MemoryBuffer> fileBuffer =
wpi::MemoryBuffer::GetFile(jsonfile, ec);
if (fileBuffer == nullptr || ec) {
auto fileBuffer = wpi::MemoryBuffer::GetFile(jsonfile);
if (!fileBuffer) {
std::fputs("GUI: could not open field JSON file\n", stderr);
return;
}
LoadJson(
{reinterpret_cast<const char*>(fileBuffer->begin()), fileBuffer->size()},
jsonfile);
LoadJson({reinterpret_cast<const char*>(fileBuffer.value()->begin()),
fileBuffer.value()->size()},
jsonfile);
}

bool FieldInfo::LoadImageImpl(const std::string& fn) {
Expand Down
15 changes: 5 additions & 10 deletions hal/src/main/native/athena/HAL.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -297,20 +297,15 @@ void HAL_GetSerialNumber(struct WPI_String* serialNumber) {

void InitializeRoboRioComments(void) {
if (!roboRioCommentsStringInitialized) {
std::error_code ec;
std::unique_ptr<wpi::MemoryBuffer> fileBuffer =
wpi::MemoryBuffer::GetFile("/etc/machine-info", ec);

std::string_view fileContents;
if (fileBuffer && !ec) {
fileContents =
std::string_view(reinterpret_cast<const char*>(fileBuffer->begin()),
fileBuffer->size());
} else {
auto fileBuffer = wpi::MemoryBuffer::GetFile("/etc/machine-info");
if (!fileBuffer) {
roboRioCommentsStringSize = 0;
roboRioCommentsStringInitialized = true;
return;
}
std::string_view fileContents{
reinterpret_cast<const char*>(fileBuffer.value()->begin()),
fileBuffer.value()->size()};
std::string_view searchString = "PRETTY_HOSTNAME=\"";

size_t start = fileContents.find(searchString);
Expand Down
12 changes: 6 additions & 6 deletions ntcore/src/main/native/cpp/NetworkServer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -351,15 +351,14 @@ void NetworkServer::HandleLocal() {
}

void NetworkServer::LoadPersistent() {
std::error_code ec;
std::unique_ptr<wpi::MemoryBuffer> fileBuffer =
wpi::MemoryBuffer::GetFile(m_persistentFilename, ec);
if (fileBuffer == nullptr || ec.value() != 0) {
auto fileBuffer = wpi::MemoryBuffer::GetFile(m_persistentFilename);
if (!fileBuffer) {
INFO(
"could not open persistent file '{}': {} "
"(this can be ignored if you aren't expecting persistent values)",
m_persistentFilename, ec.message());
m_persistentFilename, fileBuffer.error().message());
// backup file
std::error_code ec;
fs::copy_file(m_persistentFilename, m_persistentFilename + ".bak",
std::filesystem::copy_options::overwrite_existing, ec);
// try to write an empty file so it doesn't happen again
Expand All @@ -370,7 +369,8 @@ void NetworkServer::LoadPersistent() {
}
return;
}
m_persistentData = std::string{fileBuffer->begin(), fileBuffer->end()};
m_persistentData =
std::string{fileBuffer.value()->begin(), fileBuffer.value()->end()};
DEBUG4("read data: {}", m_persistentData);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,9 +125,8 @@ void HALSimHttpConnection::SendFileResponse(int code, std::string_view codeText,
}

// open file
std::unique_ptr<wpi::MemoryBuffer> fileBuffer =
wpi::MemoryBuffer::GetFile(filename, ec);
if (fileBuffer == nullptr || ec) {
auto fileBuffer = wpi::MemoryBuffer::GetFile(filename);
if (!fileBuffer) {
MySendError(404, "error opening file");
return;
}
Expand All @@ -143,7 +142,7 @@ void HALSimHttpConnection::SendFileResponse(int code, std::string_view codeText,
wpi::SmallVector<uv::Buffer, 4> bodyData;
wpi::raw_uv_ostream bodyOs{bodyData, 4096};

bodyOs << fileBuffer->GetBuffer();
bodyOs << fileBuffer.value()->GetBuffer();

SendData(bodyOs.bufs(), false);
if (!m_keepAlive) {
Expand Down
1 change: 0 additions & 1 deletion sysid/src/main/native/cpp/analysis/AnalysisManager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
#include <fmt/format.h>
#include <units/angle.h>
#include <wpi/MathExtras.h>
#include <wpi/MemoryBuffer.h>
#include <wpi/StringExtras.h>
#include <wpi/StringMap.h>

Expand Down
10 changes: 5 additions & 5 deletions sysid/src/main/native/cpp/view/LogLoader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,15 @@ void LogLoader::Display() {
if (!m_opener->result().empty()) {
m_filename = m_opener->result()[0];

std::error_code ec;
auto buf = wpi::MemoryBuffer::GetFile(m_filename, ec);
if (ec) {
auto fileBuffer = wpi::MemoryBuffer::GetFile(m_filename);
if (!fileBuffer) {
ImGui::OpenPopup("Error");
m_error = fmt::format("Could not open file: {}", ec.message());
m_error = fmt::format("Could not open file: {}",
fileBuffer.error().message());
return;
}

wpi::log::DataLogReader reader{std::move(buf)};
wpi::log::DataLogReader reader{std::move(*fileBuffer)};
if (!reader.IsValid()) {
ImGui::OpenPopup("Error");
m_error = "Not a valid datalog file";
Expand Down
8 changes: 3 additions & 5 deletions wpimath/src/main/native/cpp/trajectory/TrajectoryUtil.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,12 @@ void TrajectoryUtil::ToPathweaverJson(const Trajectory& trajectory,
}

Trajectory TrajectoryUtil::FromPathweaverJson(std::string_view path) {
std::error_code ec;
std::unique_ptr<wpi::MemoryBuffer> fileBuffer =
wpi::MemoryBuffer::GetFile(path, ec);
if (fileBuffer == nullptr || ec) {
auto fileBuffer = wpi::MemoryBuffer::GetFile(path);
if (!fileBuffer) {
throw std::runtime_error(fmt::format("Cannot open file: {}", path));
}

wpi::json json = wpi::json::parse(fileBuffer->GetCharBuffer());
wpi::json json = wpi::json::parse(fileBuffer.value()->GetCharBuffer());

return Trajectory{json.get<std::vector<Trajectory::State>>()};
}
Expand Down
4 changes: 2 additions & 2 deletions wpiutil/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ ext {
include '*.cpp'
}
exportedHeaders {
srcDirs 'src/main/native/include', 'src/main/native/thirdparty/llvm/include', 'src/main/native/thirdparty/json/include', 'src/main/native/thirdparty/fmtlib/include'
srcDirs 'src/main/native/include', 'src/main/native/thirdparty/fmtlib/include', 'src/main/native/thirdparty/json/include', 'src/main/native/thirdparty/llvm/include'
}
}
llvmCpp(CppSourceSet) {
Expand All @@ -41,7 +41,7 @@ ext {
include '**/*.cpp'
}
exportedHeaders {
srcDirs 'src/main/native/include', 'src/main/native/thirdparty/llvm/include', 'src/main/native/thirdparty/fmtlib/include'
srcDirs 'src/main/native/include', 'src/main/native/thirdparty/expected/include', 'src/main/native/thirdparty/fmtlib/include', 'src/main/native/thirdparty/llvm/include'
}
}
mpackCpp(CppSourceSet) {
Expand Down
9 changes: 5 additions & 4 deletions wpiutil/examples/printlog/printlog.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,13 @@ int main(int argc, const char** argv) {
wpi::print(stderr, "Usage: printlog <file>\n");
return EXIT_FAILURE;
}
std::error_code ec;
wpi::log::DataLogReader reader{wpi::MemoryBuffer::GetFile(argv[1], ec)};
if (ec) {
wpi::print(stderr, "could not open file: {}\n", ec.message());
auto fileBuffer = wpi::MemoryBuffer::GetFile(argv[1]);
if (!fileBuffer) {
wpi::print(stderr, "could not open file: {}\n",
fileBuffer.error().message());
return EXIT_FAILURE;
}
wpi::log::DataLogReader reader{std::move(*fileBuffer)};
if (!reader) {
wpi::print(stderr, "not a log file\n");
return EXIT_FAILURE;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -259,10 +259,14 @@ static std::unique_ptr<WritableMemoryBuffer> GetMemoryBufferForStream(
return GetMemBufferCopyImpl(buffer, bufferName, ec);
}

std::unique_ptr<MemoryBuffer> MemoryBuffer::GetFile(std::string_view filename,
std::error_code& ec,
int64_t fileSize) {
return GetFileAux<MemoryBuffer>(filename, ec, fileSize, fileSize, 0);
wpi::expected<std::unique_ptr<MemoryBuffer>, std::error_code>
MemoryBuffer::GetFile(std::string_view filename, int64_t fileSize) {
std::error_code ec;
auto ret = GetFileAux<MemoryBuffer>(filename, ec, fileSize, fileSize, 0);
if (ec) {
return wpi::unexpected{ec};
}
return ret;
}

template <typename MB>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#include <span>
#include <string_view>
#include <system_error>
#include <wpi/expected>

// Duplicated from fs.h to avoid a dependency
namespace fs {
Expand Down Expand Up @@ -77,9 +78,8 @@ class MemoryBuffer {
/// if successful, otherwise returning null. If FileSize is specified, this
/// means that the client knows that the file exists and that it has the
/// specified size.
static std::unique_ptr<MemoryBuffer> GetFile(std::string_view filename,
std::error_code& ec,
int64_t fileSize = -1);
static wpi::expected<std::unique_ptr<MemoryBuffer>, std::error_code>
GetFile(std::string_view filename, int64_t fileSize = -1);

/// Read all of the specified file into a MemoryBuffer as a stream
/// (i.e. until EOF reached). This is useful for special files that
Expand Down

0 comments on commit 1f3ef01

Please sign in to comment.