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