merge encoders into Encode.java
[org.ibex.util.git] / src / org / ibex / util / Encode.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.util;
6
7 import java.io.*;
8 import java.util.zip.GZIPInputStream;
9 import java.util.zip.GZIPOutputStream;
10
11 /** General <tt>String</tt> and <tt>byte[]</tt> processing functions,
12  *  including Base64 and a safe filename transform.
13  *
14  *  @author adam@ibex.org
15  */
16 public final class Encode {
17     private static final char[] fn =
18         new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
19
20     public static String toFilename(String s) {
21         StringBuffer sb = new StringBuffer();
22         try {
23             byte[] b = s.getBytes("UTF-8");
24             for(int i=0; i<b.length; i++) {
25                 char c = (char)(b[i] & 0xff);
26                 if (c == File.separatorChar || c < 32 || c > 126 || c == '%' || (i == 0 && c == '.'))
27                     sb.append("%" + fn[(b[i] & 0xf0) >> 8] + fn[b[i] & 0xf]);
28                 else sb.append(c);
29             }
30             return sb.toString();
31         } catch (UnsupportedEncodingException uee) {
32             throw new Error("this should never happen; Java spec mandates UTF-8 support");
33         }
34     }
35
36     public static String fromFilename(String s) {
37         StringBuffer sb = new StringBuffer();
38         byte[] b = new byte[s.length() * 2];
39         int bytes = 0;
40         for(int i=0; i<s.length(); i++) {
41             char c = s.charAt(i);
42             if (c == '%') b[bytes++] = (byte)Integer.parseInt(("" + s.charAt(++i) + s.charAt(++i)), 16);
43             else b[bytes++] = (byte)c;
44         }
45         try {
46             return new String(b, 0, bytes, "UTF-8");
47         } catch (UnsupportedEncodingException uee) {
48             throw new Error("this should never happen; Java spec mandates UTF-8 support");
49         }
50     }
51
52
53     private static final byte[] encB64 = {
54         (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
55         (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
56         (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
57         (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
58         (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
59         (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
60         (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
61         (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1',
62         (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8',
63         (byte)'9', (byte)'+', (byte)'/'
64     };
65
66     // FIXME could be far more efficient
67     public static class Base64InputStream extends ByteArrayInputStream {
68         public Base64InputStream(String s) { super(fromBase64(s.getBytes())); }
69     }
70
71     public static byte[] toBase64(String data) { return toBase64(data.getBytes()); }
72
73     /** Encode the input data producong a base 64 encoded byte array.
74      *  @return A byte array containing the base 64 encoded data. */
75     public static byte[] toBase64(byte[] data) {
76         byte[]  bytes;
77                 
78         int modulus = data.length % 3;
79         if (modulus == 0) {
80             bytes = new byte[4 * data.length / 3];
81         } else {
82             bytes = new byte[4 * ((data.length / 3) + 1)];
83         }
84
85         int dataLength = (data.length - modulus);
86         int a1, a2, a3;
87         for (int i = 0, j = 0; i < dataLength; i += 3, j += 4) {
88             a1 = data[i] & 0xff;
89             a2 = data[i + 1] & 0xff;
90             a3 = data[i + 2] & 0xff;
91             
92             bytes[j] = encB64[(a1 >>> 2) & 0x3f];
93             bytes[j + 1] = encB64[((a1 << 4) | (a2 >>> 4)) & 0x3f];
94             bytes[j + 2] = encB64[((a2 << 2) | (a3 >>> 6)) & 0x3f];
95             bytes[j + 3] = encB64[a3 & 0x3f];
96         }
97
98         int b1, b2, b3;
99         int d1, d2;
100         switch (modulus) {
101                 case 0:         /* nothing left to do */
102                     break;
103                 case 1:
104                     d1 = data[data.length - 1] & 0xff;
105                     b1 = (d1 >>> 2) & 0x3f;
106                     b2 = (d1 << 4) & 0x3f;
107
108                     bytes[bytes.length - 4] = encB64[b1];
109                     bytes[bytes.length - 3] = encB64[b2];
110                     bytes[bytes.length - 2] = (byte)'=';
111                     bytes[bytes.length - 1] = (byte)'=';
112                     break;
113                 case 2:
114                     d1 = data[data.length - 2] & 0xff;
115                     d2 = data[data.length - 1] & 0xff;
116
117                     b1 = (d1 >>> 2) & 0x3f;
118                     b2 = ((d1 << 4) | (d2 >>> 4)) & 0x3f;
119                     b3 = (d2 << 2) & 0x3f;
120
121                     bytes[bytes.length - 4] = encB64[b1];
122                     bytes[bytes.length - 3] = encB64[b2];
123                     bytes[bytes.length - 2] = encB64[b3];
124                     bytes[bytes.length - 1] = (byte)'=';
125                     break;
126             }
127
128         return bytes;
129     }
130
131
132     private static final byte[] decB64 = new byte[128];
133     static {
134         for (int i = 'A'; i <= 'Z'; i++) decB64[i] = (byte)(i - 'A');
135         for (int i = 'a'; i <= 'z'; i++) decB64[i] = (byte)(i - 'a' + 26);
136         for (int i = '0'; i <= '9'; i++) decB64[i] = (byte)(i - '0' + 52);
137         decB64['+'] = 62;
138         decB64['/'] = 63;
139     }
140
141     /** Decode base 64 encoded input data.
142      *  @return A byte array representing the decoded data. */
143     public static byte[] fromBase64(byte[] data) {
144         byte[]  bytes;
145         byte    b1, b2, b3, b4;
146
147         if (data[data.length - 2] == '=') bytes = new byte[(((data.length / 4) - 1) * 3) + 1];
148         else if (data[data.length - 1] == '=') bytes = new byte[(((data.length / 4) - 1) * 3) + 2];
149         else bytes = new byte[((data.length / 4) * 3)];
150
151         for (int i = 0, j = 0; i < data.length - 4; i += 4, j += 3) {
152             b1 = decB64[data[i]];
153             b2 = decB64[data[i + 1]];
154             b3 = decB64[data[i + 2]];
155             b4 = decB64[data[i + 3]];
156             
157             bytes[j] = (byte)((b1 << 2) | (b2 >> 4));
158             bytes[j + 1] = (byte)((b2 << 4) | (b3 >> 2));
159             bytes[j + 2] = (byte)((b3 << 6) | b4);
160         }
161
162         if (data[data.length - 2] == '=') {
163             b1 = decB64[data[data.length - 4]];
164             b2 = decB64[data[data.length - 3]];
165             bytes[bytes.length - 1] = (byte)((b1 << 2) | (b2 >> 4));
166         } else if (data[data.length - 1] == '=') {
167             b1 = decB64[data[data.length - 4]];
168             b2 = decB64[data[data.length - 3]];
169             b3 = decB64[data[data.length - 2]];
170             bytes[bytes.length - 2] = (byte)((b1 << 2) | (b2 >> 4));
171             bytes[bytes.length - 1] = (byte)((b2 << 4) | (b3 >> 2));
172         } else {
173             b1 = decB64[data[data.length - 4]];
174             b2 = decB64[data[data.length - 3]];
175             b3 = decB64[data[data.length - 2]];
176             b4 = decB64[data[data.length - 1]];
177             bytes[bytes.length - 3] = (byte)((b1 << 2) | (b2 >> 4));
178             bytes[bytes.length - 2] = (byte)((b2 << 4) | (b3 >> 2));
179             bytes[bytes.length - 1] = (byte)((b3 << 6) | b4);
180         }
181         return bytes;
182     }
183
184     /** Decode a base 64 encoded String.
185      *  @return A byte array representing the decoded data. */
186     public static byte[] fromBase64(String data) {
187         byte[]  bytes;
188         byte    b1, b2, b3, b4;
189
190         if (data.charAt(data.length() - 2) == '=')
191             bytes = new byte[(((data.length() / 4) - 1) * 3) + 1];
192         else if (data.charAt(data.length() - 1) == '=')
193             bytes = new byte[(((data.length() / 4) - 1) * 3) + 2];
194         else
195             bytes = new byte[((data.length() / 4) * 3)];
196
197         for (int i = 0, j = 0; i < data.length() - 4; i += 4, j += 3) {
198             b1 = decB64[data.charAt(i)];
199             b2 = decB64[data.charAt(i + 1)];
200             b3 = decB64[data.charAt(i + 2)];
201             b4 = decB64[data.charAt(i + 3)];
202             
203             bytes[j] = (byte)((b1 << 2) | (b2 >> 4));
204             bytes[j + 1] = (byte)((b2 << 4) | (b3 >> 2));
205             bytes[j + 2] = (byte)((b3 << 6) | b4);
206         }
207
208         if (data.charAt(data.length() - 2) == '=') {
209             b1 = decB64[data.charAt(data.length() - 4)];
210             b2 = decB64[data.charAt(data.length() - 3)];
211             bytes[bytes.length - 1] = (byte)((b1 << 2) | (b2 >> 4));
212         } else if (data.charAt(data.length() - 1) == '=') {
213             b1 = decB64[data.charAt(data.length() - 4)];
214             b2 = decB64[data.charAt(data.length() - 3)];
215             b3 = decB64[data.charAt(data.length() - 2)];
216             bytes[bytes.length - 2] = (byte)((b1 << 2) | (b2 >> 4));
217             bytes[bytes.length - 1] = (byte)((b2 << 4) | (b3 >> 2));
218         } else {
219             b1 = decB64[data.charAt(data.length() - 4)];
220             b2 = decB64[data.charAt(data.length() - 3)];
221             b3 = decB64[data.charAt(data.length() - 2)];
222             b4 = decB64[data.charAt(data.length() - 1)];
223             bytes[bytes.length - 3] = (byte)((b1 << 2) | (b2 >> 4));
224             bytes[bytes.length - 2] = (byte)((b2 << 4) | (b3 >> 2));
225             bytes[bytes.length - 1] = (byte)((b3 << 6) | b4);
226         }
227         return bytes;
228     }
229
230
231     /** Packs 8-bit bytes into a String of 7-bit chars.
232      *  @throws IllegalArgumentException when <tt>len</tt> is not a multiple of 7.
233      *  @return A String representing the processed bytes. */
234     public static String toStringFrom8bit(byte[] b, int off, int len) throws IllegalArgumentException {
235         if (len % 7 != 0) throw new IllegalArgumentException("len must be a multiple of 7");
236         StringBuffer ret = new StringBuffer();
237         for(int i=off; i<off+len; i += 7) {
238             long l = 0;
239             for(int j=6; j>=0; j--) {
240                 l <<= 8;
241                 l |= (b[i + j] & 0xff);
242             }
243             for(int j=0; j<8; j++) {
244                 ret.append((char)(l & 0x7f));
245                 l >>= 7;
246             }
247         }
248         return ret.toString();
249     }
250
251     /** Packs a String of 7-bit chars into 8-bit bytes.
252      *  @throws IllegalArgumentException when <tt>s.length()</tt> is not a multiple of 8.
253      *  @return A byte array representing the processed String. */
254     public static byte[] fromStringTo8bit(String s) throws IllegalArgumentException {
255         if (s.length() % 8 != 0) throw new IllegalArgumentException("string length must be a multiple of 8");
256         byte[] ret = new byte[(s.length() / 8) * 7];
257         for(int i=0; i<s.length(); i += 8) {
258             long l = 0;
259             for(int j=7; j>=0; j--) {
260                 l <<= 7;
261                 l |= (s.charAt(i + j) & 0x7fL);
262             }
263             for(int j=0; j<7; j++) {
264                 ret[(i / 8) * 7 + j] = (byte)(l & 0xff);
265                 l >>= 8;
266             }
267         }
268         return ret;
269     }
270
271     public static class JavaSourceCode {
272
273         public static final int LINE_LENGTH = 80 / 4;
274         public static void main(String[] s) throws Exception { System.out.println(encode(s[0], s[1], System.in)); }
275
276         public static InputStream decode(String s) throws IOException {
277             return new GZIPInputStream(new StringInputStream(s)); }
278         
279         private static class StringInputStream extends InputStream {
280             private final String s;
281             private final int length;
282             private int pos = 0;
283             public StringInputStream(String s) { this.s = s; this.length = s.length(); }
284             public int read() {
285                 byte[] b = new byte[1];
286                 int numread = read(b, 0, 1);
287                 if (numread == -1) return -1;
288                 if (numread == 0) throw new Error();
289                 return b[0] & 0xff;
290             }
291             public int read(byte[] b, int off, int len) {
292                 for(int i=off; i<off+len; i++) {
293                     if (pos>=length) return i-off;
294                     //int out = s.charAt(pos++);
295                     b[i] = (byte)s.charAt(pos++);//(byte)(out > 127 ? 127-out : out);
296                 }
297                 return len;
298             }
299         }
300
301         public static String encode(String packageName, String className, InputStream is) throws IOException {
302
303             // compress first, since the encoded form has more entropy
304             ByteArrayOutputStream baos;
305             OutputStream os = new GZIPOutputStream(baos = new ByteArrayOutputStream());
306
307             byte[] buf = new byte[1024];
308             while(true) {
309                 int numread = is.read(buf, 0, buf.length);
310                 if (numread == -1) break;
311                 os.write(buf, 0, numread);
312             }
313             os.close();
314             buf = baos.toByteArray();
315             
316             StringBuffer ret = new StringBuffer();
317             ret.append("// generated by " + Encode.class.getName() + "\n\n");
318             ret.append("package " + packageName + ";\n\n");
319             ret.append("public class " + className + " {\n");
320             ret.append("    public static final String data = \n");
321             for(int pos = 0; pos<buf.length;) {
322                 ret.append("        \"");
323                 for(int i=0; i<LINE_LENGTH && pos<buf.length; i++) {
324                     String cs = Integer.toOctalString(buf[pos++] & 0xff);
325                     while(cs.length() < 3) cs = "0" + cs;
326                     ret.append("\\" + cs);
327                 }
328                 ret.append("\" +\n");
329             }
330             ret.append("    \"\";\n");
331             ret.append("}\n");
332             return ret.toString();
333         }
334
335     }
336
337 }
338