Core/File: Add ReadWhole

This commit is contained in:
Lynix 2022-05-08 15:50:29 +02:00
parent 3c8b4c2587
commit 5f389ef0a4
3 changed files with 25 additions and 17 deletions

View File

@ -15,6 +15,7 @@
#include <ctime>
#include <filesystem>
#include <fstream>
#include <optional>
namespace Nz
{
@ -55,6 +56,7 @@ namespace Nz
static inline ByteArray ComputeHash(HashType hash, const std::filesystem::path& filePath);
static inline ByteArray ComputeHash(AbstractHash& hash, const std::filesystem::path& filePath);
static std::optional<std::vector<UInt8>> ReadWhole(const std::filesystem::path& path);
private:
void FlushStream() override;

View File

@ -267,6 +267,26 @@ namespace Nz
File& File::operator=(File&& file) noexcept = default;
std::optional<std::vector<UInt8>> File::ReadWhole(const std::filesystem::path& path)
{
File file(path);
if (!file.Open(OpenMode::ReadOnly | OpenMode::Unbuffered)) //< unbuffered since we will read all the file at once
{
NazaraError("Failed to open \"" + path.generic_u8string() + '"');
return std::nullopt;
}
std::size_t size = static_cast<std::size_t>(file.GetSize());
std::vector<UInt8> content(size);
if (size > 0 && file.Read(&content[0], size) != size)
{
NazaraError("Failed to read file");
return std::nullopt;
}
return content;
}
/*!
* \brief Flushes the stream
*

View File

@ -1554,24 +1554,10 @@ namespace Nz::ShaderLang
ShaderAst::ModulePtr ParseFromFile(const std::filesystem::path& sourcePath)
{
File file(sourcePath);
if (!file.Open(OpenMode::ReadOnly | OpenMode::Text))
{
NazaraError("Failed to open \"" + sourcePath.generic_u8string() + '"');
return {};
}
std::size_t length = static_cast<std::size_t>(file.GetSize());
if (length == 0)
std::optional<std::vector<UInt8>> source = File::ReadWhole(sourcePath);
if (!source.has_value())
return {};
std::vector<Nz::UInt8> source(length);
if (file.Read(&source[0], length) != length)
{
NazaraError("Failed to read shader file");
return {};
}
return Parse(std::string_view(reinterpret_cast<const char*>(source.data()), source.size()), sourcePath.generic_u8string());
return Parse(std::string_view(reinterpret_cast<const char*>(source->data()), source->size()), sourcePath.generic_u8string());
}
}