string_escape.hpp 2.1 KB

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