summaryrefslogtreecommitdiff
path: root/include/llmr/util/token.hpp
blob: 6795b97d1249d7d1ffd6efe669de76e6dc5ae737 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#ifndef LLMR_UTIL_TOKEN
#define LLMR_UTIL_TOKEN

#ifdef __linux__
#include <boost/regex.hpp>
namespace regex_impl = boost;
#else
#include <regex>
namespace regex_impl = std;
#endif

#include <map>

namespace llmr {
namespace util {

namespace detail {
const regex_impl::regex tokenRegex("\\{(\\w+)\\}");
const regex_impl::sregex_token_iterator tokensEnd = regex_impl::sregex_token_iterator();
}

template <typename Lookup>
std::string replaceTokens(const std::string &source, const Lookup &lookup) {
    std::string result;
    result.reserve(source.size());

    bool token = false;
    for (auto token_it = regex_impl::sregex_token_iterator(source.begin(), source.end(),
                                                           detail::tokenRegex, {-1, 1});
        token_it != detail::tokensEnd; ++token_it, token = !token) {
        if (!token_it->matched) {
            continue;
        }

        result += token ? lookup(token_it->str()) : token_it->str();
    }

    return result;
}

template <typename T>
inline std::string replaceTokens(const std::string &source, const std::map<std::string, T> &properties) {
    return replaceTokens(source, [&properties](const std::string &token) -> std::string {
        const auto it_prop = properties.find(token);
        return it_prop != properties.end() ? toString(it_prop->second) : "";
    });
}

} // end namespace util
} // end namespace llmr

#endif