Inja 3.4.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 <string_view>
8#include <utility>
9
10#include "exceptions.hpp"
11
12namespace inja {
13
14namespace string_view {
15inline std::string_view slice(std::string_view view, size_t start, size_t end) {
16 start = std::min(start, view.size());
17 end = std::min(std::max(start, end), view.size());
18 return view.substr(start, end - start);
19}
20
21inline std::pair<std::string_view, std::string_view> split(std::string_view view, char Separator) {
22 size_t idx = view.find(Separator);
23 if (idx == std::string_view::npos) {
24 return std::make_pair(view, std::string_view());
25 }
26 return std::make_pair(slice(view, 0, idx), slice(view, idx + 1, std::string_view::npos));
27}
28
29inline bool starts_with(std::string_view view, std::string_view prefix) {
30 return (view.size() >= prefix.size() && view.compare(0, prefix.size(), prefix) == 0);
31}
32} // namespace string_view
33
34inline SourceLocation get_source_location(std::string_view content, size_t pos) {
35 // Get line and offset position (starts at 1:1)
36 auto sliced = string_view::slice(content, 0, pos);
37 std::size_t last_newline = sliced.rfind("\n");
38
39 if (last_newline == std::string_view::npos) {
40 return {1, sliced.length() + 1};
41 }
42
43 // Count newlines
44 size_t count_lines = 0;
45 size_t search_start = 0;
46 while (search_start <= sliced.size()) {
47 search_start = sliced.find("\n", search_start) + 1;
48 if (search_start == 0) {
49 break;
50 }
51 count_lines += 1;
52 }
53
54 return {count_lines + 1, sliced.length() - last_newline};
55}
56
57inline void replace_substring(std::string& s, const std::string& f, const std::string& t) {
58 if (f.empty()) {
59 return;
60 }
61 for (auto pos = s.find(f); // find first occurrence of f
62 pos != std::string::npos; // make sure f was found
63 s.replace(pos, f.size(), t), // replace with t, and
64 pos = s.find(f, pos + t.size())) // find next occurrence of f
65 {}
66}
67
68} // namespace inja
69
70#endif // INCLUDE_INJA_UTILS_HPP_