1 #pragma once
2 
3 #include <mbgl/util/optional.hpp>
4 
5 #include <map>
6 #include <string>
7 #include <algorithm>
8 
9 namespace mbgl {
10 namespace util {
11 
12 const static std::string tokenReservedChars = "{}";
13 
14 // Replaces {tokens} in a string by calling the lookup function.
15 template <typename Lookup>
replaceTokens(const std::string & source,const Lookup & lookup)16 std::string replaceTokens(const std::string &source, const Lookup &lookup) {
17     std::string result;
18     result.reserve(source.size());
19 
20     auto pos = source.begin();
21     const auto end = source.end();
22 
23     while (pos != end) {
24         auto brace = std::find(pos, end, '{');
25         result.append(pos, brace);
26         pos = brace;
27         if (pos != end) {
28             for (brace++; brace != end && tokenReservedChars.find(*brace) == std::string::npos; brace++);
29             if (brace != end && *brace == '}') {
30                 std::string key { pos + 1, brace };
31                 if (optional<std::string> replacement = lookup(key)) {
32                     result.append(*replacement);
33                 } else {
34                     result.append("{");
35                     result.append(key);
36                     result.append("}");
37                 }
38                 pos = brace + 1;
39             } else {
40                 result.append(pos, brace);
41                 pos = brace;
42             }
43         }
44     }
45 
46     return result;
47 }
48 
49 } // end namespace util
50 } // end namespace mbgl
51