Line data Source code
1 : // Copyright (C) 2012 The Android Open Source Project
2 : //
3 : // Licensed under the Apache License, Version 2.0 (the "License");
4 : // you may not use this file except in compliance with the License.
5 : // You may obtain a copy of the License at
6 : //
7 : // http://www.apache.org/licenses/LICENSE-2.0
8 : //
9 : // Unless required by applicable law or agreed to in writing, software
10 : // distributed under the License is distributed on an "AS IS" BASIS,
11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 : // See the License for the specific language governing permissions and
13 : // limitations under the License.
14 :
15 : package com.google.gerrit.server.ioutil;
16 :
17 0 : public class StringUtil {
18 : /**
19 : * An array of the string representations that should be used in place of the non-printable
20 : * characters in the beginning of the ASCII table when escaping a string. The index of each
21 : * element in the array corresponds to its ASCII value, i.e. the string representation of ASCII 0
22 : * is found in the first element of this array.
23 : */
24 1 : private static final String[] NON_PRINTABLE_CHARS = {
25 : "\\x00", "\\x01", "\\x02", "\\x03", "\\x04", "\\x05", "\\x06", "\\a",
26 : "\\b", "\\t", "\\n", "\\v", "\\f", "\\r", "\\x0e", "\\x0f",
27 : "\\x10", "\\x11", "\\x12", "\\x13", "\\x14", "\\x15", "\\x16", "\\x17",
28 : "\\x18", "\\x19", "\\x1a", "\\x1b", "\\x1c", "\\x1d", "\\x1e", "\\x1f",
29 : };
30 :
31 : /**
32 : * Escapes the input string so that all non-printable characters (0x00-0x1f) are represented as a
33 : * hex escape (\x00, \x01, ...) or as a C-style escape sequence (\a, \b, \t, \n, \v, \f, or \r).
34 : * Backslashes in the input string are doubled (\\).
35 : */
36 : public static String escapeString(String str) {
37 : // Allocate a buffer big enough to cover the case with a string needed
38 : // very excessive escaping without having to reallocate the buffer.
39 1 : final StringBuilder result = new StringBuilder(3 * str.length());
40 :
41 1 : for (int i = 0; i < str.length(); i++) {
42 1 : char c = str.charAt(i);
43 1 : if (c < NON_PRINTABLE_CHARS.length) {
44 1 : result.append(NON_PRINTABLE_CHARS[c]);
45 1 : } else if (c == '\\') {
46 1 : result.append("\\\\");
47 : } else {
48 1 : result.append(c);
49 : }
50 : }
51 1 : return result.toString();
52 : }
53 : }
|