1 /*
2 * Copyright 2005 [ini4j] Development Team
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.ini4j;
18
19 class Convert
20 {
21 private static final char HEX[] = "0123456789abcdef".toCharArray();
22
23 protected static String escape(String line)
24 {
25 int len = line.length();
26 StringBuilder buffer = new StringBuilder(len*2);
27
28 for(int i = 0 ; i < len; i++)
29 {
30 char c = line.charAt(i);
31 int idx = "\\\t\n\f".indexOf(c);
32
33 if ( idx >= 0 )
34 {
35 buffer.append('\\');
36 buffer.append( "\\tnf".charAt(idx));
37 }
38 else
39 {
40 if ((c < 0x0020) || (c > 0x007e))
41 {
42 buffer.append("\\u");
43 buffer.append( HEX[(c >>> 12) & 0x0f] );
44 buffer.append( HEX[(c >>> 8) & 0x0f] );
45 buffer.append( HEX[(c >>> 4) & 0x0f] );
46 buffer.append( HEX[c & 0x0f] );
47 }
48 else
49 {
50 buffer.append(c);
51 }
52 }
53 }
54 return buffer.toString();
55 }
56
57 protected static String unescape(String line)
58 {
59 int n = line.length();
60 StringBuilder buffer = new StringBuilder(n);
61
62 for(int i = 0; i < n; )
63 {
64 char c = line.charAt(i++);
65
66 if ( c == '\\' )
67 {
68 c = line.charAt(i++);
69
70 if ( c == 'u' )
71 {
72 try
73 {
74 c = (char) Integer.parseInt(line.substring(i,i+=4), 16);
75 }
76 catch (RuntimeException x)
77 {
78 throw new IllegalArgumentException("Malformed \\uxxxx encoding.");
79 }
80 }
81 else
82 {
83 int idx = "\\tnf".indexOf(c);
84
85 if ( idx >= 0 )
86 {
87 c = "\\\t\n\f".charAt(idx);
88 }
89 }
90 }
91
92 buffer.append(c);
93 }
94
95 return buffer.toString();
96 }
97 }