1#ifndef INCLUDE_INJA_UTILS_HPP_
2#define INCLUDE_INJA_UTILS_HPP_
9#include "exceptions.hpp"
10#include "string_view.hpp"
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
19 }
catch (
const std::ios_base::failure & ) {
20 INJA_THROW(FileError(
"failed accessing file at '" + path +
"'"));
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);
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());
39 return std::make_pair(slice(view, 0, idx), slice(view, idx + 1, nonstd::string_view::npos));
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);
47inline SourceLocation get_source_location(nonstd::string_view content,
size_t pos) {
49 auto sliced = string_view::slice(content, 0, pos);
50 std::size_t last_newline = sliced.rfind(
"\n");
52 if (last_newline == nonstd::string_view::npos) {
53 return {1, sliced.length() + 1};
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) {
67 return {count_lines + 1, sliced.length() - last_newline};
70inline void replace_substring(std::string& s,
const std::string& f,
73 if (f.empty())
return;
74 for (
auto pos = s.find(f);
75 pos != std::string::npos;
76 s.replace(pos, f.size(), t),
77 pos = s.find(f, pos + t.size()))