From 5f389ef0a4442269c8773639059c5892ca285535 Mon Sep 17 00:00:00 2001 From: Lynix Date: Sun, 8 May 2022 15:50:29 +0200 Subject: [PATCH] Core/File: Add ReadWhole --- include/Nazara/Core/File.hpp | 2 ++ src/Nazara/Core/File.cpp | 20 ++++++++++++++++++++ src/Nazara/Shader/ShaderLangParser.cpp | 20 +++----------------- 3 files changed, 25 insertions(+), 17 deletions(-) diff --git a/include/Nazara/Core/File.hpp b/include/Nazara/Core/File.hpp index a487eed4a..7529a818f 100644 --- a/include/Nazara/Core/File.hpp +++ b/include/Nazara/Core/File.hpp @@ -15,6 +15,7 @@ #include #include #include +#include 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> ReadWhole(const std::filesystem::path& path); private: void FlushStream() override; diff --git a/src/Nazara/Core/File.cpp b/src/Nazara/Core/File.cpp index c009aff8b..d8196887a 100644 --- a/src/Nazara/Core/File.cpp +++ b/src/Nazara/Core/File.cpp @@ -267,6 +267,26 @@ namespace Nz File& File::operator=(File&& file) noexcept = default; + std::optional> 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(file.GetSize()); + std::vector 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 * diff --git a/src/Nazara/Shader/ShaderLangParser.cpp b/src/Nazara/Shader/ShaderLangParser.cpp index db6a170cd..9a3eed375 100644 --- a/src/Nazara/Shader/ShaderLangParser.cpp +++ b/src/Nazara/Shader/ShaderLangParser.cpp @@ -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(file.GetSize()); - if (length == 0) + std::optional> source = File::ReadWhole(sourcePath); + if (!source.has_value()) return {}; - std::vector source(length); - if (file.Read(&source[0], length) != length) - { - NazaraError("Failed to read shader file"); - return {}; - } - - return Parse(std::string_view(reinterpret_cast(source.data()), source.size()), sourcePath.generic_u8string()); + return Parse(std::string_view(reinterpret_cast(source->data()), source->size()), sourcePath.generic_u8string()); } }