string_escape.hpp 1.7 KB

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