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