PageRenderTime 55ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/net.sf.py4j/src/py4j/Base64.java

http://github.com/bartdag/py4j
Java | 598 lines | 293 code | 82 blank | 223 comment | 118 complexity | 1922e982a2e0d0ce23073d37ce3505fc MD5 | raw file
Possible License(s): BSD-3-Clause
  1. package py4j;
  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. return encodeToByte(sArr, 0, sArr != null ? sArr.length : 0, lineSep);
  242. }
  243. /** Encodes a raw byte array into a BASE64 <code>byte[]</code> representation i accordance with RFC 2045.
  244. * @param sArr The bytes to convert. If <code>null</code> an empty array will be returned.
  245. * @param sOff The starting position in the bytes to convert.
  246. * @param sLen The number of bytes to convert. If 0 an empty array will be returned.
  247. * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
  248. * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
  249. * little faster.
  250. * @return A BASE64 encoded array. Never <code>null</code>.
  251. */
  252. public final static byte[] encodeToByte(byte[] sArr, int sOff, int sLen, boolean lineSep)
  253. {
  254. // Check special case
  255. if (sArr == null || sLen == 0)
  256. return new byte[0];
  257. int eLen = (sLen / 3) * 3; // Length of even 24-bits.
  258. int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count
  259. int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array
  260. byte[] dArr = new byte[dLen];
  261. // Encode even 24-bits
  262. for (int s = sOff, d = 0, cc = 0; s < sOff + eLen;) {
  263. // Copy next three bytes into lower 24 bits of int, paying attension to sign.
  264. int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff);
  265. // Encode the int into four chars
  266. dArr[d++] = (byte) CA[(i >>> 18) & 0x3f];
  267. dArr[d++] = (byte) CA[(i >>> 12) & 0x3f];
  268. dArr[d++] = (byte) CA[(i >>> 6) & 0x3f];
  269. dArr[d++] = (byte) CA[i & 0x3f];
  270. // Add optional line separator
  271. if (lineSep && ++cc == 19 && d < dLen - 2) {
  272. dArr[d++] = '\r';
  273. dArr[d++] = '\n';
  274. cc = 0;
  275. }
  276. }
  277. // Pad and encode last bits if source isn't an even 24 bits.
  278. int left = sLen - eLen; // 0 - 2.
  279. if (left > 0) {
  280. // Prepare the int
  281. int i = ((sArr[sOff + eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sOff + sLen - 1] & 0xff) << 2) : 0);
  282. // Set last four chars
  283. dArr[dLen - 4] = (byte) CA[i >> 12];
  284. dArr[dLen - 3] = (byte) CA[(i >>> 6) & 0x3f];
  285. dArr[dLen - 2] = left == 2 ? (byte) CA[i & 0x3f] : (byte) '=';
  286. dArr[dLen - 1] = '=';
  287. }
  288. return dArr;
  289. }
  290. /** Decodes a BASE64 encoded byte array. All illegal characters will be ignored and can handle both arrays with
  291. * and without line separators.
  292. * @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
  293. * @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
  294. * (including '=') isn't divideable by 4. (I.e. definitely corrupted).
  295. */
  296. public final static byte[] decode(byte[] sArr)
  297. {
  298. return decode(sArr, 0, sArr.length);
  299. }
  300. /** Decodes a BASE64 encoded byte array. All illegal characters will be ignored and can handle both arrays with
  301. * and without line separators.
  302. * @param sArr The source array. <code>null</code> will throw an exception.
  303. * @param sOff The starting position in the source array.
  304. * @param sLen The number of bytes to decode from the source array. Length 0 will return an empty array.
  305. * @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
  306. * (including '=') isn't divideable by 4. (I.e. definitely corrupted).
  307. */
  308. public final static byte[] decode(byte[] sArr, int sOff, int sLen)
  309. {
  310. // Count illegal characters (including '\r', '\n') to know what size the returned array will be,
  311. // so we don't have to reallocate & copy it later.
  312. int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
  313. 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.
  314. if (IA[sArr[sOff + i] & 0xff] < 0)
  315. sepCnt++;
  316. // Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
  317. if ((sLen - sepCnt) % 4 != 0)
  318. return null;
  319. int pad = 0;
  320. for (int i = sLen; i > 1 && IA[sArr[sOff + --i] & 0xff] <= 0;)
  321. if (sArr[sOff + i] == '=')
  322. pad++;
  323. int len = ((sLen - sepCnt) * 6 >> 3) - pad;
  324. byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
  325. for (int s = 0, d = 0; d < len;) {
  326. // Assemble three bytes into an int from four "valid" characters.
  327. int i = 0;
  328. for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
  329. int c = IA[sArr[sOff + s++] & 0xff];
  330. if (c >= 0)
  331. i |= c << (18 - j * 6);
  332. else
  333. j--;
  334. }
  335. // Add the bytes
  336. dArr[d++] = (byte) (i >> 16);
  337. if (d < len) {
  338. dArr[d++]= (byte) (i >> 8);
  339. if (d < len)
  340. dArr[d++] = (byte) i;
  341. }
  342. }
  343. return dArr;
  344. }
  345. /** Decodes a BASE64 encoded byte array that is known to be resonably well formatted. The method is about twice as
  346. * fast as {@link #decode(byte[])}. The preconditions are:<br>
  347. * + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
  348. * + Line separator must be "\r\n", as specified in RFC 2045
  349. * + The array must not contain illegal characters within the encoded string<br>
  350. * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
  351. * @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
  352. * @return The decoded array of bytes. May be of length 0.
  353. */
  354. public final static byte[] decodeFast(byte[] sArr)
  355. {
  356. // Check special case
  357. int sLen = sArr.length;
  358. if (sLen == 0)
  359. return new byte[0];
  360. int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
  361. // Trim illegal chars from start
  362. while (sIx < eIx && IA[sArr[sIx] & 0xff] < 0)
  363. sIx++;
  364. // Trim illegal chars from end
  365. while (eIx > 0 && IA[sArr[eIx] & 0xff] < 0)
  366. eIx--;
  367. // get the padding count (=) (0, 1 or 2)
  368. int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end.
  369. int cCnt = eIx - sIx + 1; // Content count including possible separators
  370. int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0;
  371. int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
  372. byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
  373. // Decode all but the last 0 - 2 bytes.
  374. int d = 0;
  375. for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
  376. // Assemble three bytes into an int from four "valid" characters.
  377. int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]];
  378. // Add the bytes
  379. dArr[d++] = (byte) (i >> 16);
  380. dArr[d++] = (byte) (i >> 8);
  381. dArr[d++] = (byte) i;
  382. // If line separator, jump over it.
  383. if (sepCnt > 0 && ++cc == 19) {
  384. sIx += 2;
  385. cc = 0;
  386. }
  387. }
  388. if (d < len) {
  389. // Decode last 1-3 bytes (incl '=') into 1-3 bytes
  390. int i = 0;
  391. for (int j = 0; sIx <= eIx - pad; j++)
  392. i |= IA[sArr[sIx++]] << (18 - j * 6);
  393. for (int r = 16; d < len; r -= 8)
  394. dArr[d++] = (byte) (i >> r);
  395. }
  396. return dArr;
  397. }
  398. // ****************************************************************************************
  399. // * String version
  400. // ****************************************************************************************
  401. /** Encodes a raw byte array into a BASE64 <code>String</code> representation i accordance with RFC 2045.
  402. * @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
  403. * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
  404. * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
  405. * little faster.
  406. * @return A BASE64 encoded array. Never <code>null</code>.
  407. */
  408. public final static String encodeToString(byte[] sArr, boolean lineSep)
  409. {
  410. // Reuse char[] since we can't create a String incrementally anyway and StringBuffer/Builder would be slower.
  411. return new String(encodeToChar(sArr, lineSep));
  412. }
  413. /** Decodes a BASE64 encoded <code>String</code>. All illegal characters will be ignored and can handle both strings with
  414. * and without line separators.<br>
  415. * <b>Note!</b> It can be up to about 2x the speed to call <code>decode(str.toCharArray())</code> instead. That
  416. * will create a temporary array though. This version will use <code>str.charAt(i)</code> to iterate the string.
  417. * @param str The source string. <code>null</code> or length 0 will return an empty array.
  418. * @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
  419. * (including '=') isn't divideable by 4. (I.e. definitely corrupted).
  420. */
  421. public final static byte[] decode(String str)
  422. {
  423. // Check special case
  424. int sLen = str != null ? str.length() : 0;
  425. if (sLen == 0)
  426. return new byte[0];
  427. // Count illegal characters (including '\r', '\n') to know what size the returned array will be,
  428. // so we don't have to reallocate & copy it later.
  429. int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
  430. 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.
  431. if (IA[str.charAt(i)] < 0)
  432. sepCnt++;
  433. // Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
  434. if ((sLen - sepCnt) % 4 != 0)
  435. return null;
  436. // Count '=' at end
  437. int pad = 0;
  438. for (int i = sLen; i > 1 && IA[str.charAt(--i)] <= 0;)
  439. if (str.charAt(i) == '=')
  440. pad++;
  441. int len = ((sLen - sepCnt) * 6 >> 3) - pad;
  442. byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
  443. for (int s = 0, d = 0; d < len;) {
  444. // Assemble three bytes into an int from four "valid" characters.
  445. int i = 0;
  446. for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
  447. int c = IA[str.charAt(s++)];
  448. if (c >= 0)
  449. i |= c << (18 - j * 6);
  450. else
  451. j--;
  452. }
  453. // Add the bytes
  454. dArr[d++] = (byte) (i >> 16);
  455. if (d < len) {
  456. dArr[d++]= (byte) (i >> 8);
  457. if (d < len)
  458. dArr[d++] = (byte) i;
  459. }
  460. }
  461. return dArr;
  462. }
  463. /** Decodes a BASE64 encoded string that is known to be resonably well formatted. The method is about twice as
  464. * fast as {@link #decode(String)}. The preconditions are:<br>
  465. * + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
  466. * + Line separator must be "\r\n", as specified in RFC 2045
  467. * + The array must not contain illegal characters within the encoded string<br>
  468. * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
  469. * @param s The source string. Length 0 will return an empty array. <code>null</code> will throw an exception.
  470. * @return The decoded array of bytes. May be of length 0.
  471. */
  472. public final static byte[] decodeFast(String s)
  473. {
  474. // Check special case
  475. int sLen = s.length();
  476. if (sLen == 0)
  477. return new byte[0];
  478. int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
  479. // Trim illegal chars from start
  480. while (sIx < eIx && IA[s.charAt(sIx) & 0xff] < 0)
  481. sIx++;
  482. // Trim illegal chars from end
  483. while (eIx > 0 && IA[s.charAt(eIx) & 0xff] < 0)
  484. eIx--;
  485. // get the padding count (=) (0, 1 or 2)
  486. int pad = s.charAt(eIx) == '=' ? (s.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count '=' at end.
  487. int cCnt = eIx - sIx + 1; // Content count including possible separators
  488. int sepCnt = sLen > 76 ? (s.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0;
  489. int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
  490. byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
  491. // Decode all but the last 0 - 2 bytes.
  492. int d = 0;
  493. for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
  494. // Assemble three bytes into an int from four "valid" characters.
  495. int i = IA[s.charAt(sIx++)] << 18 | IA[s.charAt(sIx++)] << 12 | IA[s.charAt(sIx++)] << 6 | IA[s.charAt(sIx++)];
  496. // Add the bytes
  497. dArr[d++] = (byte) (i >> 16);
  498. dArr[d++] = (byte) (i >> 8);
  499. dArr[d++] = (byte) i;
  500. // If line separator, jump over it.
  501. if (sepCnt > 0 && ++cc == 19) {
  502. sIx += 2;
  503. cc = 0;
  504. }
  505. }
  506. if (d < len) {
  507. // Decode last 1-3 bytes (incl '=') into 1-3 bytes
  508. int i = 0;
  509. for (int j = 0; sIx <= eIx - pad; j++)
  510. i |= IA[s.charAt(sIx++)] << (18 - j * 6);
  511. for (int r = 16; d < len; r -= 8)
  512. dArr[d++] = (byte) (i >> r);
  513. }
  514. return dArr;
  515. }
  516. }