01: /**************************************************************************/
02: /* B O S S A */
03: /* A simple imperative object-oriented research language */
04: /* (c) Daniel Bonniot 1999 */
05: /* */
06: /* This program is free software; you can redistribute it and/or modify */
07: /* it under the terms of the GNU General Public License as published by */
08: /* the Free Software Foundation; either version 2 of the License, or */
09: /* (at your option) any later version. */
10: /* */
11: /**************************************************************************/package nice.tools.code;
12:
13: import bossa.util.*;
14:
15: /**
16: String escaping.
17:
18: @author bonniot
19: */
20:
21: public abstract class Strings {
22: /**
23: Encodes a string to make it a valid java identifier.
24:
25: Any offending character is replaced by '$$' followed by its
26: (uni)code in Hexadecimal.
27: */
28: public static String escape(String s) {
29: if (s == null)
30: return null;
31:
32: if (s.length() == 0 || s.equals("<init>")
33: || s.equals("<clinit>"))
34: return s;
35:
36: char[] chars = s.toCharArray();
37: StringBuffer res = new StringBuffer();
38:
39: if (!Character.isJavaIdentifierStart(chars[0])) {
40: res.append("$$");
41: appendHexRepr(res, (int) chars[0]);
42: } else
43: res.append(chars[0]);
44:
45: for (int i = 1; i < chars.length; i++)
46: if (//chars[i]!='.' &&
47: !Character.isJavaIdentifierPart(chars[i])) {
48: res.append("$$");
49: appendHexRepr(res, (int) chars[i]);
50: } else
51: res.append(chars[i]);
52:
53: return res.toString();
54: }
55:
56: private static void appendHexRepr(StringBuffer sb, int n) {
57: String num = Integer.toHexString(n);
58: for (int pad = num.length(); pad < 4; pad++)
59: sb.append("0");
60: sb.append(num);
61: }
62:
63: public static String unescape(String s) {
64: if (s == null)
65: return null;
66:
67: char[] chars = s.toCharArray();
68: StringBuffer res = new StringBuffer();
69:
70: for (int i = 0; i < chars.length; i++)
71: if (chars[i] == '$' && chars[i + 1] == '$') {
72: res.append((char) Integer.parseInt(s.substring(i + 2,
73: i + 6), 16));
74: i += 5;
75: } else
76: res.append(chars[i]);
77:
78: return res.toString();
79: }
80: }
|