DryChem 1.0.0
A generic, compile-time C++ toolbox with no dependencies for the modern computational chemistry project.
Loading...
Searching...
No Matches
fileParser.hpp
Go to the documentation of this file.
1// Copyright (c) 2020-2025 Cody R. Drisko. All rights reserved.
2// Licensed under the MIT License. See the LICENSE file in the project root for more information.
3//
4// Name: fileParser.hpp
5// Author: crdrisko
6// Date: 11/18/2020-07:08:47
7// Description: The context class in the Strategy implementation of a file parser
8
9#ifndef DRYCHEM_COMMON_UTILITIES_INCLUDE_COMMON_UTILS_FILES_FILEPARSING_FILEPARSER_HPP
10#define DRYCHEM_COMMON_UTILITIES_INCLUDE_COMMON_UTILS_FILES_FILEPARSING_FILEPARSER_HPP
11
12#include <filesystem>
13#include <fstream>
14#include <functional>
15#include <iterator>
16#include <string>
17#include <type_traits>
18#include <utility>
19
21
23{
25 {
26 private:
27 const std::filesystem::path fileName;
28 mutable std::string fileContentCache;
29
35 void readFileContent() const
36 {
37 if (std::filesystem::is_regular_file(fileName))
38 {
39 std::ifstream inputFile {fileName};
40
41 fileContentCache.assign(std::istreambuf_iterator<char>(inputFile), std::istreambuf_iterator<char>());
42 }
43 else
44 throw FileNotFound {"Common-Utilities", __FILE__, __LINE__};
45 }
46
47 public:
48 explicit FileParser(const std::filesystem::path& fileName_) noexcept : fileName {fileName_} {}
49
50 std::filesystem::path getFileName() const noexcept { return fileName; }
51
67 template<typename F, typename... TArgs>
68 constexpr decltype(auto) parseDataFile(F&& f_, TArgs&&... args_) const
69 {
70 if (fileContentCache.empty())
71 this->readFileContent();
72
73 // Need to handle `void f(args...)` case differently from `auto f(args...)` case
74 if constexpr (std::is_void_v<std::invoke_result_t<F, std::string, TArgs...>>)
75 std::invoke(std::forward<F>(f_), std::cref(fileContentCache), std::forward<TArgs>(args_)...);
76 else
77 return std::invoke(std::forward<F>(f_), std::cref(fileContentCache), std::forward<TArgs>(args_)...);
78 }
79
80 void clearCache() noexcept { fileContentCache.clear(); }
81 };
82} // namespace CppUtils::Files
83
84#endif
Definition fileExceptions.hpp:25
void clearCache() noexcept
Definition fileParser.hpp:80
FileParser(const std::filesystem::path &fileName_) noexcept
Definition fileParser.hpp:48
std::string fileContentCache
Definition fileParser.hpp:28
const std::filesystem::path fileName
Definition fileParser.hpp:27
constexpr decltype(auto) parseDataFile(F &&f_, TArgs &&... args_) const
Definition fileParser.hpp:68
std::filesystem::path getFileName() const noexcept
Definition fileParser.hpp:50
void readFileContent() const
Definition fileParser.hpp:35
Definition fileParser.hpp:23