blob: 5b85e9c3e0249cbb13d524c1dfb6c8252b049304 [file] [log] [blame]
license.botf003cfe2008-08-24 09:55:55 +09001// 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.commit3f4a7322008-07-27 06:49:38 +09004
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) {
17 switch (c) {
18 case '\b':
19 dst->append("\\b");
20 break;
21 case '\f':
22 dst->append("\\f");
23 break;
24 case '\n':
25 dst->append("\\n");
26 break;
27 case '\r':
28 dst->append("\\r");
29 break;
30 case '\t':
31 dst->append("\\t");
32 break;
33 case '\v':
34 dst->append("\\v");
35 break;
36 case '\\':
37 dst->append("\\\\");
38 break;
39 case '"':
40 dst->append("\\\"");
41 break;
42 default:
43 return false;
44 }
45 return true;
46}
47
48void JavascriptDoubleQuote(const std::wstring& str,
49 bool put_in_quotes,
50 std::string* dst) {
51 if (put_in_quotes)
52 dst->push_back('"');
53
54 for (std::wstring::const_iterator it = str.begin(); it != str.end(); ++it) {
55 wchar_t c = *it;
56 if (!JavascriptSingleEscapeChar(c, dst)) {
57 if (c > 255) {
58 // Non-ascii values need to be unicode dst->
59 // TODO(tc): Some unicode values are handled specially. See
60 // spidermonkey code.
61 StringAppendF(dst, "\\u%04X", c);
62 } else if (c < 32 || c > 126) {
63 // Spidermonkey hex escapes these values.
64 StringAppendF(dst, "\\x%02X", c);
65 } else {
66 dst->push_back(static_cast<char>(c));
67 }
68 }
69 }
70
71 if (put_in_quotes)
72 dst->push_back('"');
73}
74
75void JavascriptDoubleQuote(const std::string& str,
76 bool put_in_quotes,
77 std::string* dst) {
78 if (put_in_quotes)
79 dst->push_back('"');
80
81 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) {
82 unsigned char c = *it;
83 if (!JavascriptSingleEscapeChar(c, dst)) {
84 // Hex encode if the character is non-printable 7bit ascii
85 if (c < 32 || c == 127) {
86 StringAppendF(dst, "\\x%02X", c);
87 } else {
88 dst->push_back(static_cast<char>(c));
89 }
90 }
91 }
92
93 if (put_in_quotes)
94 dst->push_back('"');
95}
96
97} // namespace string_escape
license.botf003cfe2008-08-24 09:55:55 +090098