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