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