diff --git a/include/merian/io/file_loader.hpp b/include/merian/io/file_loader.hpp index 1b6b0a2..169454f 100644 --- a/include/merian/io/file_loader.hpp +++ b/include/merian/io/file_loader.hpp @@ -1,6 +1,8 @@ #pragma once +#include "merian/utils/string.hpp" #include +#include #include #include #include @@ -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 static std::vector 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 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 search_cwd_parents(const std::filesystem::path& path); + static std::optional + search_cwd_parents(const std::filesystem::path& path); public: FileLoader(const std::set& search_paths = {"./"}) diff --git a/src/merian/io/file_loader.cpp b/src/merian/io/file_loader.cpp index fdcc877..b4046fe 100644 --- a/src/merian/io/file_loader.cpp +++ b/src/merian/io/file_loader.cpp @@ -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());