string_escape.h 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright (c) 2011 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. // This file defines utility functions for escaping strings suitable for JSON.
  5. #ifndef BASE_JSON_STRING_ESCAPE_H_
  6. #define BASE_JSON_STRING_ESCAPE_H_
  7. #include <string>
  8. #include "base/base_export.h"
  9. #include "base/strings/string_piece.h"
  10. namespace base {
  11. // Appends to |dest| an escaped version of |str|. Valid UTF-8 code units and
  12. // characters will pass through from the input to the output. Invalid code
  13. // units and characters will be replaced with the U+FFFD replacement character.
  14. // This function returns true if no replacement was necessary and false if
  15. // there was a lossy replacement. On return, |dest| will contain a valid UTF-8
  16. // JSON string.
  17. //
  18. // Non-printing control characters will be escaped as \uXXXX sequences for
  19. // readability.
  20. //
  21. // If |put_in_quotes| is true, then a leading and trailing double-quote mark
  22. // will be appended to |dest| as well.
  23. BASE_EXPORT bool EscapeJSONString(StringPiece str,
  24. bool put_in_quotes,
  25. std::string* dest);
  26. // Performs a similar function to the UTF-8 StringPiece version above,
  27. // converting UTF-16 code units to UTF-8 code units and escaping non-printing
  28. // control characters. On return, |dest| will contain a valid UTF-8 JSON string.
  29. BASE_EXPORT bool EscapeJSONString(StringPiece16 str,
  30. bool put_in_quotes,
  31. std::string* dest);
  32. // Helper functions that wrap the above two functions but return the value
  33. // instead of appending. |put_in_quotes| is always true.
  34. BASE_EXPORT std::string GetQuotedJSONString(StringPiece str);
  35. BASE_EXPORT std::string GetQuotedJSONString(StringPiece16 str);
  36. // Given an arbitrary byte string |str|, this will escape all non-ASCII bytes
  37. // as \uXXXX escape sequences. This function is *NOT* meant to be used with
  38. // Unicode strings and does not validate |str| as one.
  39. //
  40. // CAVEAT CALLER: The output of this function may not be valid JSON, since
  41. // JSON requires escape sequences to be valid UTF-16 code units. This output
  42. // will be mangled if passed to to the base::JSONReader, since the reader will
  43. // interpret it as UTF-16 and convert it to UTF-8.
  44. //
  45. // The output of this function takes the *appearance* of JSON but is not in
  46. // fact valid according to RFC 8259.
  47. BASE_EXPORT std::string EscapeBytesAsInvalidJSONString(StringPiece str,
  48. bool put_in_quotes);
  49. } // namespace base
  50. #endif // BASE_JSON_STRING_ESCAPE_H_