summaryrefslogtreecommitdiff
path: root/src/mbgl/util/token.hpp
blob: dea12f941243322468b6a032d7602b5f92d551b4 (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
#pragma once

#include <mbgl/util/optional.hpp>

#include <map>
#include <string>
#include <algorithm>

namespace mbgl {
namespace util {

const static std::string tokenReservedChars = "{}";

// Replaces {tokens} in a string by calling the lookup function.
template <typename Lookup>
std::string replaceTokens(const std::string &source, const Lookup &lookup) {
    std::string result;
    result.reserve(source.size());

    auto pos = source.begin();
    const auto end = source.end();

    while (pos != end) {
        auto brace = std::find(pos, end, '{');
        result.append(pos, brace);
        pos = brace;
        if (pos != end) {
            for (brace++; brace != end && tokenReservedChars.find(*brace) == std::string::npos; brace++);
            if (brace != end && *brace == '}') {
                std::string key { pos + 1, brace };
                if (optional<std::string> replacement = lookup(key)) {
                    result.append(*replacement);
                } else {
                    result.append("{");
                    result.append(key);
                    result.append("}");
                }
                pos = brace + 1;
            } else {
                result.append(pos, brace);
                pos = brace;
            }
        }
    }

    return result;
}

} // end namespace util
} // end namespace mbgl