PageRenderTime 41ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 0ms

/demo/src/main/java/org/jboss/jdf/example/ticketmonster/util/Base64.java

https://github.com/Jiri-Kremser/ticket-monster
Java | 575 lines | 287 code | 81 blank | 207 comment | 116 complexity | 06ed6dba61d4ca0d1cecdad64d88684f MD5 | raw file
  1. package org.jboss.jdf.example.ticketmonster.util;
  2. import java.util.Arrays;
  3. /** A very fast and memory efficient class to encode and decode to and from BASE64 in full accordance
  4. * with RFC 2045.<br><br>
  5. * On Windows XP sp1 with 1.4.2_04 and later ;), this encoder and decoder is about 10 times faster
  6. * on small arrays (10 - 1000 bytes) and 2-3 times as fast on larger arrays (10000 - 1000000 bytes)
  7. * compared to <code>sun.misc.Encoder()/Decoder()</code>.<br><br>
  8. *
  9. * On byte arrays the encoder is about 20% faster than Jakarta Commons Base64 Codec for encode and
  10. * about 50% faster for decoding large arrays. This implementation is about twice as fast on very small
  11. * arrays (&lt 30 bytes). If source/destination is a <code>String</code> this
  12. * version is about three times as fast due to the fact that the Commons Codec result has to be recoded
  13. * to a <code>String</code> from <code>byte[]</code>, which is very expensive.<br><br>
  14. *
  15. * This encode/decode algorithm doesn't create any temporary arrays as many other codecs do, it only
  16. * allocates the resulting array. This produces less garbage and it is possible to handle arrays twice
  17. * as large as algorithms that create a temporary array. (E.g. Jakarta Commons Codec). It is unknown
  18. * whether Sun's <code>sun.misc.Encoder()/Decoder()</code> produce temporary arrays but since performance
  19. * is quite low it probably does.<br><br>
  20. *
  21. * The encoder produces the same output as the Sun one except that the Sun's encoder appends
  22. * a trailing line separator if the last character isn't a pad. Unclear why but it only adds to the
  23. * length and is probably a side effect. Both are in conformance with RFC 2045 though.<br>
  24. * Commons codec seem to always att a trailing line separator.<br><br>
  25. *
  26. * <b>Note!</b>
  27. * The encode/decode method pairs (types) come in three versions with the <b>exact</b> same algorithm and
  28. * thus a lot of code redundancy. This is to not create any temporary arrays for transcoding to/from different
  29. * format types. The methods not used can simply be commented out.<br><br>
  30. *
  31. * There is also a "fast" version of all decode methods that works the same way as the normal ones, but
  32. * har a few demands on the decoded input. Normally though, these fast verions should be used if the source if
  33. * the input is known and it hasn't bee tampered with.<br><br>
  34. *
  35. * If you find the code useful or you find a bug, please send me a note at base64 @ miginfocom . com.
  36. *
  37. * Licence (BSD):
  38. * ==============
  39. *
  40. * Copyright (c) 2004, Mikael Grev, MiG InfoCom AB. (base64 @ miginfocom . com)
  41. * All rights reserved.
  42. *
  43. * Redistribution and use in source and binary forms, with or without modification,
  44. * are permitted provided that the following conditions are met:
  45. * Redistributions of source code must retain the above copyright notice, this list
  46. * of conditions and the following disclaimer.
  47. * Redistributions in binary form must reproduce the above copyright notice, this
  48. * list of conditions and the following disclaimer in the documentation and/or other
  49. * materials provided with the distribution.
  50. * Neither the name of the MiG InfoCom AB nor the names of its contributors may be
  51. * used to endorse or promote products derived from this software without specific
  52. * prior written permission.
  53. *
  54. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  55. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  56. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  57. * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  58. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  59. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  60. * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  61. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  62. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
  63. * OF SUCH DAMAGE.
  64. *
  65. * @version 2.2
  66. * @author Mikael Grev
  67. * Date: 2004-aug-02
  68. * Time: 11:31:11
  69. */
  70. public class Base64
  71. {
  72. private static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
  73. private static final int[] IA = new int[256];
  74. static {
  75. Arrays.fill(IA, -1);
  76. for (int i = 0, iS = CA.length; i < iS; i++)
  77. IA[CA[i]] = i;
  78. IA['='] = 0;
  79. }
  80. // ****************************************************************************************
  81. // * char[] version
  82. // ****************************************************************************************
  83. /** Encodes a raw byte array into a BASE64 <code>char[]</code> representation i accordance with RFC 2045.
  84. * @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
  85. * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
  86. * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
  87. * little faster.
  88. * @return A BASE64 encoded array. Never <code>null</code>.
  89. */
  90. public final static char[] encodeToChar(byte[] sArr, boolean lineSep)
  91. {
  92. // Check special case
  93. int sLen = sArr != null ? sArr.length : 0;
  94. if (sLen == 0)
  95. return new char[0];
  96. int eLen = (sLen / 3) * 3; // Length of even 24-bits.
  97. int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count
  98. int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array
  99. char[] dArr = new char[dLen];
  100. // Encode even 24-bits
  101. for (int s = 0, d = 0, cc = 0; s < eLen;) {
  102. // Copy next three bytes into lower 24 bits of int, paying attension to sign.
  103. int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff);
  104. // Encode the int into four chars
  105. dArr[d++] = CA[(i >>> 18) & 0x3f];
  106. dArr[d++] = CA[(i >>> 12) & 0x3f];
  107. dArr[d++] = CA[(i >>> 6) & 0x3f];
  108. dArr[d++] = CA[i & 0x3f];
  109. // Add optional line separator
  110. if (lineSep && ++cc == 19 && d < dLen - 2) {
  111. dArr[d++] = '\r';
  112. dArr[d++] = '\n';
  113. cc = 0;
  114. }
  115. }
  116. // Pad and encode last bits if source isn't even 24 bits.
  117. int left = sLen - eLen; // 0 - 2.
  118. if (left > 0) {
  119. // Prepare the int
  120. int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0);
  121. // Set last four chars
  122. dArr[dLen - 4] = CA[i >> 12];
  123. dArr[dLen - 3] = CA[(i >>> 6) & 0x3f];
  124. dArr[dLen - 2] = left == 2 ? CA[i & 0x3f] : '=';
  125. dArr[dLen - 1] = '=';
  126. }
  127. return dArr;
  128. }
  129. /** Decodes a BASE64 encoded char array. All illegal characters will be ignored and can handle both arrays with
  130. * and without line separators.
  131. * @param sArr The source array. <code>null</code> or length 0 will return an empty array.
  132. * @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
  133. * (including '=') isn't divideable by 4. (I.e. definitely corrupted).
  134. */
  135. public final static byte[] decode(char[] sArr)
  136. {
  137. // Check special case
  138. int sLen = sArr != null ? sArr.length : 0;
  139. if (sLen == 0)
  140. return new byte[0];
  141. // Count illegal characters (including '\r', '\n') to know what size the returned array will be,
  142. // so we don't have to reallocate & copy it later.
  143. int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
  144. for (int i = 0; i < sLen; i++) // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
  145. if (IA[sArr[i]] < 0)
  146. sepCnt++;
  147. // Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
  148. if ((sLen - sepCnt) % 4 != 0)
  149. return null;
  150. int pad = 0;
  151. for (int i = sLen; i > 1 && IA[sArr[--i]] <= 0;)
  152. if (sArr[i] == '=')
  153. pad++;
  154. int len = ((sLen - sepCnt) * 6 >> 3) - pad;
  155. byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
  156. for (int s = 0, d = 0; d < len;) {
  157. // Assemble three bytes into an int from four "valid" characters.
  158. int i = 0;
  159. for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
  160. int c = IA[sArr[s++]];
  161. if (c >= 0)
  162. i |= c << (18 - j * 6);
  163. else
  164. j--;
  165. }
  166. // Add the bytes
  167. dArr[d++] = (byte) (i >> 16);
  168. if (d < len) {
  169. dArr[d++]= (byte) (i >> 8);
  170. if (d < len)
  171. dArr[d++] = (byte) i;
  172. }
  173. }
  174. return dArr;
  175. }
  176. /** Decodes a BASE64 encoded char array that is known to be resonably well formatted. The method is about twice as
  177. * fast as {@link #decode(char[])}. The preconditions are:<br>
  178. * + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
  179. * + Line separator must be "\r\n", as specified in RFC 2045
  180. * + The array must not contain illegal characters within the encoded string<br>
  181. * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
  182. * @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
  183. * @return The decoded array of bytes. May be of length 0.
  184. */
  185. public final static byte[] decodeFast(char[] sArr)
  186. {
  187. // Check special case
  188. int sLen = sArr.length;
  189. if (sLen == 0)
  190. return new byte[0];
  191. int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
  192. // Trim illegal chars from start
  193. while (sIx < eIx && IA[sArr[sIx]] < 0)
  194. sIx++;
  195. // Trim illegal chars from end
  196. while (eIx > 0 && IA[sArr[eIx]] < 0)
  197. eIx--;
  198. // get the padding count (=) (0, 1 or 2)
  199. int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end.
  200. int cCnt = eIx - sIx + 1; // Content count including possible separators
  201. int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0;
  202. int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
  203. byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
  204. // Decode all but the last 0 - 2 bytes.
  205. int d = 0;
  206. for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
  207. // Assemble three bytes into an int from four "valid" characters.
  208. int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]];
  209. // Add the bytes
  210. dArr[d++] = (byte) (i >> 16);
  211. dArr[d++] = (byte) (i >> 8);
  212. dArr[d++] = (byte) i;
  213. // If line separator, jump over it.
  214. if (sepCnt > 0 && ++cc == 19) {
  215. sIx += 2;
  216. cc = 0;
  217. }
  218. }
  219. if (d < len) {
  220. // Decode last 1-3 bytes (incl '=') into 1-3 bytes
  221. int i = 0;
  222. for (int j = 0; sIx <= eIx - pad; j++)
  223. i |= IA[sArr[sIx++]] << (18 - j * 6);
  224. for (int r = 16; d < len; r -= 8)
  225. dArr[d++] = (byte) (i >> r);
  226. }
  227. return dArr;
  228. }
  229. // ****************************************************************************************
  230. // * byte[] version
  231. // ****************************************************************************************
  232. /** Encodes a raw byte array into a BASE64 <code>byte[]</code> representation i accordance with RFC 2045.
  233. * @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
  234. * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
  235. * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
  236. * little faster.
  237. * @return A BASE64 encoded array. Never <code>null</code>.
  238. */
  239. public final static byte[] encodeToByte(byte[] sArr, boolean lineSep)
  240. {
  241. // Check special case
  242. int sLen = sArr != null ? sArr.length : 0;
  243. if (sLen == 0)
  244. return new byte[0];
  245. int eLen = (sLen / 3) * 3; // Length of even 24-bits.
  246. int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count
  247. int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array
  248. byte[] dArr = new byte[dLen];
  249. // Encode even 24-bits
  250. for (int s = 0, d = 0, cc = 0; s < eLen;) {
  251. // Copy next three bytes into lower 24 bits of int, paying attension to sign.
  252. int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff);
  253. // Encode the int into four chars
  254. dArr[d++] = (byte) CA[(i >>> 18) & 0x3f];
  255. dArr[d++] = (byte) CA[(i >>> 12) & 0x3f];
  256. dArr[d++] = (byte) CA[(i >>> 6) & 0x3f];
  257. dArr[d++] = (byte) CA[i & 0x3f];
  258. // Add optional line separator
  259. if (lineSep && ++cc == 19 && d < dLen - 2) {
  260. dArr[d++] = '\r';
  261. dArr[d++] = '\n';
  262. cc = 0;
  263. }
  264. }
  265. // Pad and encode last bits if source isn't an even 24 bits.
  266. int left = sLen - eLen; // 0 - 2.
  267. if (left > 0) {
  268. // Prepare the int
  269. int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0);
  270. // Set last four chars
  271. dArr[dLen - 4] = (byte) CA[i >> 12];
  272. dArr[dLen - 3] = (byte) CA[(i >>> 6) & 0x3f];
  273. dArr[dLen - 2] = left == 2 ? (byte) CA[i & 0x3f] : (byte) '=';
  274. dArr[dLen - 1] = '=';
  275. }
  276. return dArr;
  277. }
  278. /** Decodes a BASE64 encoded byte array. All illegal characters will be ignored and can handle both arrays with
  279. * and without line separators.
  280. * @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
  281. * @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
  282. * (including '=') isn't divideable by 4. (I.e. definitely corrupted).
  283. */
  284. public final static byte[] decode(byte[] sArr)
  285. {
  286. // Check special case
  287. int sLen = sArr.length;
  288. // Count illegal characters (including '\r', '\n') to know what size the returned array will be,
  289. // so we don't have to reallocate & copy it later.
  290. int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
  291. for (int i = 0; i < sLen; i++) // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
  292. if (IA[sArr[i] & 0xff] < 0)
  293. sepCnt++;
  294. // Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
  295. if ((sLen - sepCnt) % 4 != 0)
  296. return null;
  297. int pad = 0;
  298. for (int i = sLen; i > 1 && IA[sArr[--i] & 0xff] <= 0;)
  299. if (sArr[i] == '=')
  300. pad++;
  301. int len = ((sLen - sepCnt) * 6 >> 3) - pad;
  302. byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
  303. for (int s = 0, d = 0; d < len;) {
  304. // Assemble three bytes into an int from four "valid" characters.
  305. int i = 0;
  306. for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
  307. int c = IA[sArr[s++] & 0xff];
  308. if (c >= 0)
  309. i |= c << (18 - j * 6);
  310. else
  311. j--;
  312. }
  313. // Add the bytes
  314. dArr[d++] = (byte) (i >> 16);
  315. if (d < len) {
  316. dArr[d++]= (byte) (i >> 8);
  317. if (d < len)
  318. dArr[d++] = (byte) i;
  319. }
  320. }
  321. return dArr;
  322. }
  323. /** Decodes a BASE64 encoded byte array that is known to be resonably well formatted. The method is about twice as
  324. * fast as {@link #decode(byte[])}. The preconditions are:<br>
  325. * + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
  326. * + Line separator must be "\r\n", as specified in RFC 2045
  327. * + The array must not contain illegal characters within the encoded string<br>
  328. * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
  329. * @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
  330. * @return The decoded array of bytes. May be of length 0.
  331. */
  332. public final static byte[] decodeFast(byte[] sArr)
  333. {
  334. // Check special case
  335. int sLen = sArr.length;
  336. if (sLen == 0)
  337. return new byte[0];
  338. int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
  339. // Trim illegal chars from start
  340. while (sIx < eIx && IA[sArr[sIx] & 0xff] < 0)
  341. sIx++;
  342. // Trim illegal chars from end
  343. while (eIx > 0 && IA[sArr[eIx] & 0xff] < 0)
  344. eIx--;
  345. // get the padding count (=) (0, 1 or 2)
  346. int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end.
  347. int cCnt = eIx - sIx + 1; // Content count including possible separators
  348. int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0;
  349. int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
  350. byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
  351. // Decode all but the last 0 - 2 bytes.
  352. int d = 0;
  353. for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
  354. // Assemble three bytes into an int from four "valid" characters.
  355. int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]];
  356. // Add the bytes
  357. dArr[d++] = (byte) (i >> 16);
  358. dArr[d++] = (byte) (i >> 8);
  359. dArr[d++] = (byte) i;
  360. // If line separator, jump over it.
  361. if (sepCnt > 0 && ++cc == 19) {
  362. sIx += 2;
  363. cc = 0;
  364. }
  365. }
  366. if (d < len) {
  367. // Decode last 1-3 bytes (incl '=') into 1-3 bytes
  368. int i = 0;
  369. for (int j = 0; sIx <= eIx - pad; j++)
  370. i |= IA[sArr[sIx++]] << (18 - j * 6);
  371. for (int r = 16; d < len; r -= 8)
  372. dArr[d++] = (byte) (i >> r);
  373. }
  374. return dArr;
  375. }
  376. // ****************************************************************************************
  377. // * String version
  378. // ****************************************************************************************
  379. /** Encodes a raw byte array into a BASE64 <code>String</code> representation i accordance with RFC 2045.
  380. * @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
  381. * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
  382. * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
  383. * little faster.
  384. * @return A BASE64 encoded array. Never <code>null</code>.
  385. */
  386. public final static String encodeToString(byte[] sArr, boolean lineSep)
  387. {
  388. // Reuse char[] since we can't create a String incrementally anyway and StringBuffer/Builder would be slower.
  389. return new String(encodeToChar(sArr, lineSep));
  390. }
  391. /** Decodes a BASE64 encoded <code>String</code>. All illegal characters will be ignored and can handle both strings with
  392. * and without line separators.<br>
  393. * <b>Note!</b> It can be up to about 2x the speed to call <code>decode(str.toCharArray())</code> instead. That
  394. * will create a temporary array though. This version will use <code>str.charAt(i)</code> to iterate the string.
  395. * @param str The source string. <code>null</code> or length 0 will return an empty array.
  396. * @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
  397. * (including '=') isn't divideable by 4. (I.e. definitely corrupted).
  398. */
  399. public final static byte[] decode(String str)
  400. {
  401. // Check special case
  402. int sLen = str != null ? str.length() : 0;
  403. if (sLen == 0)
  404. return new byte[0];
  405. // Count illegal characters (including '\r', '\n') to know what size the returned array will be,
  406. // so we don't have to reallocate & copy it later.
  407. int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
  408. for (int i = 0; i < sLen; i++) // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
  409. if (IA[str.charAt(i)] < 0)
  410. sepCnt++;
  411. // Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
  412. if ((sLen - sepCnt) % 4 != 0)
  413. return null;
  414. // Count '=' at end
  415. int pad = 0;
  416. for (int i = sLen; i > 1 && IA[str.charAt(--i)] <= 0;)
  417. if (str.charAt(i) == '=')
  418. pad++;
  419. int len = ((sLen - sepCnt) * 6 >> 3) - pad;
  420. byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
  421. for (int s = 0, d = 0; d < len;) {
  422. // Assemble three bytes into an int from four "valid" characters.
  423. int i = 0;
  424. for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
  425. int c = IA[str.charAt(s++)];
  426. if (c >= 0)
  427. i |= c << (18 - j * 6);
  428. else
  429. j--;
  430. }
  431. // Add the bytes
  432. dArr[d++] = (byte) (i >> 16);
  433. if (d < len) {
  434. dArr[d++]= (byte) (i >> 8);
  435. if (d < len)
  436. dArr[d++] = (byte) i;
  437. }
  438. }
  439. return dArr;
  440. }
  441. /** Decodes a BASE64 encoded string that is known to be resonably well formatted. The method is about twice as
  442. * fast as {@link #decode(String)}. The preconditions are:<br>
  443. * + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
  444. * + Line separator must be "\r\n", as specified in RFC 2045
  445. * + The array must not contain illegal characters within the encoded string<br>
  446. * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
  447. * @param s The source string. Length 0 will return an empty array. <code>null</code> will throw an exception.
  448. * @return The decoded array of bytes. May be of length 0.
  449. */
  450. public final static byte[] decodeFast(String s)
  451. {
  452. // Check special case
  453. int sLen = s.length();
  454. if (sLen == 0)
  455. return new byte[0];
  456. int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
  457. // Trim illegal chars from start
  458. while (sIx < eIx && IA[s.charAt(sIx) & 0xff] < 0)
  459. sIx++;
  460. // Trim illegal chars from end
  461. while (eIx > 0 && IA[s.charAt(eIx) & 0xff] < 0)
  462. eIx--;
  463. // get the padding count (=) (0, 1 or 2)
  464. int pad = s.charAt(eIx) == '=' ? (s.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count '=' at end.
  465. int cCnt = eIx - sIx + 1; // Content count including possible separators
  466. int sepCnt = sLen > 76 ? (s.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0;
  467. int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
  468. byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
  469. // Decode all but the last 0 - 2 bytes.
  470. int d = 0;
  471. for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
  472. // Assemble three bytes into an int from four "valid" characters.
  473. int i = IA[s.charAt(sIx++)] << 18 | IA[s.charAt(sIx++)] << 12 | IA[s.charAt(sIx++)] << 6 | IA[s.charAt(sIx++)];
  474. // Add the bytes
  475. dArr[d++] = (byte) (i >> 16);
  476. dArr[d++] = (byte) (i >> 8);
  477. dArr[d++] = (byte) i;
  478. // If line separator, jump over it.
  479. if (sepCnt > 0 && ++cc == 19) {
  480. sIx += 2;
  481. cc = 0;
  482. }
  483. }
  484. if (d < len) {
  485. // Decode last 1-3 bytes (incl '=') into 1-3 bytes
  486. int i = 0;
  487. for (int j = 0; sIx <= eIx - pad; j++)
  488. i |= IA[s.charAt(sIx++)] << (18 - j * 6);
  489. for (int r = 16; d < len; r -= 8)
  490. dArr[d++] = (byte) (i >> r);
  491. }
  492. return dArr;
  493. }
  494. }