1 #pragma once
2
3 #include <string>
4 #include <nlohmann/detail/macro_scope.hpp>
5
6 namespace nlohmann
7 {
8 namespace detail
9 {
10
11 /*!
12 @brief replace all occurrences of a substring by another string
13
14 @param[in,out] s the string to manipulate; changed so that all
15 occurrences of @a f are replaced with @a t
16 @param[in] f the substring to replace with @a t
17 @param[in] t the string to replace @a f
18
19 @pre The search string @a f must not be empty. **This precondition is
20 enforced with an assertion.**
21
22 @since version 2.0.0
23 */
replace_substring(std::string & s,const std::string & f,const std::string & t)24 inline void replace_substring(std::string& s, const std::string& f,
25 const std::string& t)
26 {
27 JSON_ASSERT(!f.empty());
28 for (auto pos = s.find(f); // find first occurrence of f
29 pos != std::string::npos; // make sure f was found
30 s.replace(pos, f.size(), t), // replace with t, and
31 pos = s.find(f, pos + t.size())) // find next occurrence of f
32 {}
33 }
34
35 /*!
36 * @brief string escaping as described in RFC 6901 (Sect. 4)
37 * @param[in] s string to escape
38 * @return escaped string
39 *
40 * Note the order of escaping "~" to "~0" and "/" to "~1" is important.
41 */
escape(std::string s)42 inline std::string escape(std::string s)
43 {
44 replace_substring(s, "~", "~0");
45 replace_substring(s, "/", "~1");
46 return s;
47 }
48
49 /*!
50 * @brief string unescaping as described in RFC 6901 (Sect. 4)
51 * @param[in] s string to unescape
52 * @return unescaped string
53 *
54 * Note the order of escaping "~1" to "/" and "~0" to "~" is important.
55 */
unescape(std::string & s)56 static void unescape(std::string& s)
57 {
58 replace_substring(s, "~1", "/");
59 replace_substring(s, "~0", "~");
60 }
61
62 } // namespace detail
63 } // namespace nlohmann
64