WPILibC++ 2024.3.2
string_escape.h
Go to the documentation of this file.
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
12
14namespace 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
26enforced with an assertion.**
27
28@since version 2.0.0
29*/
30template<typename StringType>
31inline 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 */
49template<typename StringType>
50inline 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 */
64template<typename StringType>
65static void unescape(StringType& s)
66{
67 replace_substring(s, StringType{"~1"}, StringType{"/"});
68 replace_substring(s, StringType{"~0"}, StringType{"~"});
69}
70
71} // namespace detail
#define WPI_JSON_NAMESPACE_END
Definition: abi_macros.h:59
#define WPI_JSON_NAMESPACE_BEGIN
Definition: abi_macros.h:53
#define JSON_ASSERT(x)
Definition: macro_scope.h:192
detail namespace with internal helper functions
Definition: xchar.h:20
static void unescape(StringType &s)
string unescaping as described in RFC 6901 (Sect. 4)
Definition: string_escape.h:65
void replace_substring(StringType &s, const StringType &f, const StringType &t)
replace all occurrences of a substring by another string
Definition: string_escape.h:31
StringType escape(StringType s)
string escaping as described in RFC 6901 (Sect. 4)
Definition: string_escape.h:50