Inja 3.3.0
A Template Engine for Modern C++
Loading...
Searching...
No Matches
utils.hpp
1#ifndef INCLUDE_INJA_UTILS_HPP_
2#define INCLUDE_INJA_UTILS_HPP_
3
4#include <algorithm>
5#include <fstream>
6#include <string>
7#include <utility>
8
9#include "exceptions.hpp"
10#include "string_view.hpp"
11
12namespace inja {
13
14inline void open_file_or_throw(const std::string &path, std::ifstream &file) {
15 file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
16#ifndef INJA_NOEXCEPTION
17 try {
18 file.open(path);
19 } catch (const std::ios_base::failure & /*e*/) {
20 INJA_THROW(FileError("failed accessing file at '" + path + "'"));
21 }
22#else
23 file.open(path);
24#endif
25}
26
27namespace string_view {
28inline nonstd::string_view slice(nonstd::string_view view, size_t start, size_t end) {
29 start = std::min(start, view.size());
30 end = std::min(std::max(start, end), view.size());
31 return view.substr(start, end - start);
32}
33
34inline std::pair<nonstd::string_view, nonstd::string_view> split(nonstd::string_view view, char Separator) {
35 size_t idx = view.find(Separator);
36 if (idx == nonstd::string_view::npos) {
37 return std::make_pair(view, nonstd::string_view());
38 }
39 return std::make_pair(slice(view, 0, idx), slice(view, idx + 1, nonstd::string_view::npos));
40}
41
42inline bool starts_with(nonstd::string_view view, nonstd::string_view prefix) {
43 return (view.size() >= prefix.size() && view.compare(0, prefix.size(), prefix) == 0);
44}
45} // namespace string_view
46
47inline SourceLocation get_source_location(nonstd::string_view content, size_t pos) {
48 // Get line and offset position (starts at 1:1)
49 auto sliced = string_view::slice(content, 0, pos);
50 std::size_t last_newline = sliced.rfind("\n");
51
52 if (last_newline == nonstd::string_view::npos) {
53 return {1, sliced.length() + 1};
54 }
55
56 // Count newlines
57 size_t count_lines = 0;
58 size_t search_start = 0;
59 while (search_start <= sliced.size()) {
60 search_start = sliced.find("\n", search_start) + 1;
61 if (search_start == 0) {
62 break;
63 }
64 count_lines += 1;
65 }
66
67 return {count_lines + 1, sliced.length() - last_newline};
68}
69
70inline void replace_substring(std::string& s, const std::string& f,
71 const std::string& t)
72{
73 if (f.empty()) return;
74 for (auto pos = s.find(f); // find first occurrence of f
75 pos != std::string::npos; // make sure f was found
76 s.replace(pos, f.size(), t), // replace with t, and
77 pos = s.find(f, pos + t.size())) // find next occurrence of f
78 {}
79}
80
81} // namespace inja
82
83#endif // INCLUDE_INJA_UTILS_HPP_