1 : // Copyright (c) 2006-2008 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 : #include "base/string_escape.h"
6 :
7 : #include <string>
8 :
9 : #include "base/string_util.h"
10 :
11 : namespace string_escape {
12 :
13 : // Try to escape |c| as a "SingleEscapeCharacter" (\n, etc). If successful,
14 : // returns true and appends the escape sequence to |dst|.
15 : template<typename CHAR>
16 0 : static bool JavascriptSingleEscapeChar(const CHAR c, std::string* dst) {
17 : // WARNING: if you add a new case here, you need to update the reader as well.
18 0 : switch (c) {
19 : case '\b':
20 0 : dst->append("\\b");
21 0 : break;
22 : case '\f':
23 0 : dst->append("\\f");
24 0 : break;
25 : case '\n':
26 0 : dst->append("\\n");
27 0 : break;
28 : case '\r':
29 0 : dst->append("\\r");
30 0 : break;
31 : case '\t':
32 0 : dst->append("\\t");
33 0 : break;
34 : case '\v':
35 0 : dst->append("\\v");
36 0 : break;
37 : case '\\':
38 0 : dst->append("\\\\");
39 0 : break;
40 : case '"':
41 0 : dst->append("\\\"");
42 0 : break;
43 : default:
44 0 : return false;
45 : }
46 0 : return true;
47 : }
48 :
49 0 : void JavascriptDoubleQuote(const string16& str,
50 : bool put_in_quotes,
51 : std::string* dst) {
52 0 : if (put_in_quotes)
53 0 : dst->push_back('"');
54 :
55 0 : for (string16::const_iterator it = str.begin(); it != str.end(); ++it) {
56 0 : char16 c = *it;
57 0 : if (!JavascriptSingleEscapeChar(c, dst)) {
58 0 : if (c > 255) {
59 : // Non-ascii values need to be unicode dst->
60 : // TODO(tc): Some unicode values are handled specially. See
61 : // spidermonkey code.
62 0 : StringAppendF(dst, "\\u%04X", c);
63 0 : } else if (c < 32 || c > 126) {
64 : // Spidermonkey hex escapes these values.
65 0 : StringAppendF(dst, "\\x%02X", c);
66 : } else {
67 0 : dst->push_back(static_cast<char>(c));
68 : }
69 : }
70 : }
71 :
72 0 : if (put_in_quotes)
73 0 : dst->push_back('"');
74 0 : }
75 :
76 0 : void JavascriptDoubleQuote(const std::string& str,
77 : bool put_in_quotes,
78 : std::string* dst) {
79 0 : if (put_in_quotes)
80 0 : dst->push_back('"');
81 :
82 0 : for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) {
83 0 : unsigned char c = *it;
84 0 : if (!JavascriptSingleEscapeChar(c, dst)) {
85 : // Hex encode if the character is non-printable 7bit ascii
86 0 : if (c < 32 || c == 127) {
87 0 : StringAppendF(dst, "\\x%02X", c);
88 : } else {
89 0 : dst->push_back(static_cast<char>(c));
90 : }
91 : }
92 : }
93 :
94 0 : if (put_in_quotes)
95 0 : dst->push_back('"');
96 0 : }
97 :
98 : } // namespace string_escape
|