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