Skip to content

Commit

Permalink
merian: FileLoader: load into vector, fix warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
LDAP committed Nov 6, 2024
1 parent b6725d0 commit 3866c88
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
27 changes: 26 additions & 1 deletion include/merian/io/file_loader.hpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#pragma once

#include "merian/utils/string.hpp"
#include <filesystem>
#include <fstream>
#include <optional>
#include <set>
#include <spdlog/spdlog.h>
Expand All @@ -14,9 +16,32 @@ class FileLoader {
static bool exists(const std::filesystem::path& path,
std::filesystem::file_status file_status = std::filesystem::file_status{});

template <typename T> static std::vector<T> load_file(const std::filesystem::path& path) {
if (!exists(path)) {
throw std::runtime_error{
fmt::format("failed to load {} (does not exist)", path.string())};
}

// Open the stream to 'lock' the file.
std::ifstream f(path, std::ios::in | std::ios::binary);
const std::size_t size = std::filesystem::file_size(path);

if (size % sizeof(T)) {
SPDLOG_WARN("loading {} B of data into a vector quantized to {} B", size, sizeof(T));
}

std::vector<T> result((size + sizeof(T) - 1) / sizeof(T), {});
f.read((char*)result.data(), (std::streamsize)size);

SPDLOG_DEBUG("load {} of data from {}", format_size(size), path.string());

return result;
}

static std::string load_file(const std::filesystem::path& path);

static std::optional<std::filesystem::path> search_cwd_parents(const std::filesystem::path& path);
static std::optional<std::filesystem::path>
search_cwd_parents(const std::filesystem::path& path);

public:
FileLoader(const std::set<std::filesystem::path>& search_paths = {"./"})
Expand Down
4 changes: 2 additions & 2 deletions src/merian/io/file_loader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ std::string FileLoader::load_file(const std::filesystem::path& path) {

// Open the stream to 'lock' the file.
std::ifstream f(path, std::ios::in | std::ios::binary);
const auto size = std::filesystem::file_size(path);
const std::size_t size = std::filesystem::file_size(path);

std::string result(size, '\0');
f.read(result.data(), size);
f.read(result.data(), (std::streamsize)size);

SPDLOG_DEBUG("load {} of data from {}", format_size(size), path.string());

Expand Down

0 comments on commit 3866c88

Please sign in to comment.