blob: aafee11fc705a3e4a63dbebee35ed11cf0bb5eb4 [file] [log] [blame]
license.botbf09a502008-08-24 00:55:551// 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.
initial.commitd7cae122008-07-26 21:49:384
5#include "base/string_escape.h"
6
7#include <string>
8
9#include "base/string_util.h"
10
11namespace 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|.
15template<typename CHAR>
16static bool JavascriptSingleEscapeChar(const CHAR c, std::string* dst) {
[email protected]d46d6f3b2008-10-01 17:26:0617 // WARNING: if you add a new case here, you need to update the reader as well.
initial.commitd7cae122008-07-26 21:49:3818 switch (c) {
19 case '\b':
20 dst->append("\\b");
21 break;
22 case '\f':
23 dst->append("\\f");
24 break;
25 case '\n':
26 dst->append("\\n");
27 break;
28 case '\r':
29 dst->append("\\r");
30 break;
31 case '\t':
32 dst->append("\\t");
33 break;
34 case '\v':
35 dst->append("\\v");
36 break;
37 case '\\':
38 dst->append("\\\\");
39 break;
40 case '"':
41 dst->append("\\\"");
42 break;
43 default:
44 return false;
45 }
46 return true;
47}
48
[email protected]e22191712009-02-25 19:17:4549void JavascriptDoubleQuote(const string16& str,
initial.commitd7cae122008-07-26 21:49:3850 bool put_in_quotes,
51 std::string* dst) {
52 if (put_in_quotes)
53 dst->push_back('"');
54
[email protected]e22191712009-02-25 19:17:4555 for (string16::const_iterator it = str.begin(); it != str.end(); ++it) {
56 char16 c = *it;
initial.commitd7cae122008-07-26 21:49:3857 if (!JavascriptSingleEscapeChar(c, dst)) {
58 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 StringAppendF(dst, "\\u%04X", c);
63 } else if (c < 32 || c > 126) {
64 // Spidermonkey hex escapes these values.
65 StringAppendF(dst, "\\x%02X", c);
66 } else {
67 dst->push_back(static_cast<char>(c));
68 }
69 }
70 }
71
72 if (put_in_quotes)
73 dst->push_back('"');
74}
75
76void JavascriptDoubleQuote(const std::string& str,
77 bool put_in_quotes,
78 std::string* dst) {
79 if (put_in_quotes)
80 dst->push_back('"');
81
82 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) {
83 unsigned char c = *it;
84 if (!JavascriptSingleEscapeChar(c, dst)) {
85 // Hex encode if the character is non-printable 7bit ascii
86 if (c < 32 || c == 127) {
87 StringAppendF(dst, "\\x%02X", c);
88 } else {
89 dst->push_back(static_cast<char>(c));
90 }
91 }
92 }
93
94 if (put_in_quotes)
95 dst->push_back('"');
96}
97
98} // namespace string_escape