xref: /aosp_15_r20/external/cronet/base/json/string_escape.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2011 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // This file defines utility functions for escaping strings suitable for JSON.
6 
7 #ifndef BASE_JSON_STRING_ESCAPE_H_
8 #define BASE_JSON_STRING_ESCAPE_H_
9 
10 #include <string>
11 #include <string_view>
12 
13 #include "base/base_export.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(std::string_view str,
30                                   bool put_in_quotes,
31                                   std::string* dest);
32 
33 // Performs a similar function to the UTF-8 std::string_view 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(std::u16string_view 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(std::string_view str);
43 BASE_EXPORT std::string GetQuotedJSONString(std::u16string_view 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 8259.
56 BASE_EXPORT std::string EscapeBytesAsInvalidJSONString(std::string_view str,
57                                                        bool put_in_quotes);
58 
59 }  // namespace base
60 
61 #endif  // BASE_JSON_STRING_ESCAPE_H_
62