PageRenderTime 53ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/core/src/main/java/com/twitter/elephantbird/mapreduce/input/Base64Codec.java

http://github.com/kevinweil/elephant-bird
Java | 301 lines | 132 code | 38 blank | 131 comment | 43 complexity | ffdd3c300854eabe1a911be3d67cbbc0 MD5 | raw file
Possible License(s): Apache-2.0
  1. package com.twitter.elephantbird.mapreduce.input;
  2. import java.util.Arrays;
  3. import com.twitter.elephantbird.mapreduce.io.DecodeException;
  4. /** A very fast and memory efficient class to encode and decode to and from BASE64 in full accordance
  5. * with RFC 2045.<br><br>
  6. * On Windows XP sp1 with 1.4.2_04 and later ;), this encoder and decoder is about 10 times faster
  7. * on small arrays (10 - 1000 bytes) and 2-3 times as fast on larger arrays (10000 - 1000000 bytes)
  8. * compared to <code>sun.misc.Encoder()/Decoder()</code>.<br><br>
  9. *
  10. * On byte arrays the encoder is about 20% faster than Jakarta Commons Base64 Codec for encode and
  11. * about 50% faster for decoding large arrays. This implementation is about twice as fast on very small
  12. * arrays (&lt 30 bytes). If source/destination is a <code>String</code> this
  13. * version is about three times as fast due to the fact that the Commons Codec result has to be recoded
  14. * to a <code>String</code> from <code>byte[]</code>, which is very expensive.<br><br>
  15. *
  16. * This encode/decode algorithm doesn't create any temporary arrays as many other codecs do, it only
  17. * allocates the resulting array. This produces less garbage and it is possible to handle arrays twice
  18. * as large as algorithms that create a temporary array. (E.g. Jakarta Commons Codec). It is unknown
  19. * whether Sun's <code>sun.misc.Encoder()/Decoder()</code> produce temporary arrays but since performance
  20. * is quite low it probably does.<br><br>
  21. *
  22. * The encoder produces the same output as the Sun one except that the Sun's encoder appends
  23. * a trailing line separator if the last character isn't a pad. Unclear why but it only adds to the
  24. * length and is probably a side effect. Both are in conformance with RFC 2045 though.<br>
  25. * Commons codec seem to always att a trailing line separator.<br><br>
  26. *
  27. * <b>Note!</b>
  28. * The encode/decode method pairs (types) come in three versions with the <b>exact</b> same algorithm and
  29. * thus a lot of code redundancy. This is to not create any temporary arrays for transcoding to/from different
  30. * format types. The methods not used can simply be commented out.<br><br>
  31. *
  32. * There is also a "fast" version of all decode methods that works the same way as the normal ones, but
  33. * har a few demands on the decoded input. Normally though, these fast verions should be used if the source if
  34. * the input is known and it hasn't bee tampered with.<br><br>
  35. *
  36. * If you find the code useful or you find a bug, please send me a note at base64 @ miginfocom . com.
  37. *
  38. * Licence (BSD):
  39. * ==============
  40. *
  41. * Copyright (c) 2004, Mikael Grev, MiG InfoCom AB. (base64 @ miginfocom . com)
  42. * All rights reserved.
  43. *
  44. * Redistribution and use in source and binary forms, with or without modification,
  45. * are permitted provided that the following conditions are met:
  46. * Redistributions of source code must retain the above copyright notice, this list
  47. * of conditions and the following disclaimer.
  48. * Redistributions in binary form must reproduce the above copyright notice, this
  49. * list of conditions and the following disclaimer in the documentation and/or other
  50. * materials provided with the distribution.
  51. * Neither the name of the MiG InfoCom AB nor the names of its contributors may be
  52. * used to endorse or promote products derived from this software without specific
  53. * prior written permission.
  54. *
  55. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  56. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  57. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  58. * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  59. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  60. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  61. * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  62. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  63. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
  64. * OF SUCH DAMAGE.
  65. *
  66. * @version 2.2
  67. * @author Mikael Grev
  68. * Date: 2004-aug-02
  69. * Time: 11:31:11
  70. */
  71. public class Base64Codec
  72. {
  73. private static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
  74. private static final int[] IA = new int[256];
  75. static {
  76. Arrays.fill(IA, -1);
  77. for (int i = 0, iS = CA.length; i < iS; i++)
  78. IA[CA[i]] = i;
  79. IA['='] = 0;
  80. }
  81. // ****************************************************************************************
  82. // * byte[] version
  83. // ****************************************************************************************
  84. /** Encodes a raw byte array into a BASE64 <code>byte[]</code> representation i accordance with RFC 2045.
  85. * @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
  86. * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
  87. * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
  88. * little faster.
  89. * @return A BASE64 encoded array. Never <code>null</code>.
  90. */
  91. public final static byte[] encodeToByte(byte[] sArr, boolean lineSep)
  92. {
  93. return encodeToByte(sArr, 0, sArr != null ? sArr.length : 0, lineSep);
  94. }
  95. /** Encodes a raw byte array into a BASE64 <code>byte[]</code> representation i accordance with RFC 2045.
  96. * @param sArr The bytes to convert. If <code>null</code> an empty array will be returned.
  97. * @param sOff The starting position in the bytes to convert.
  98. * @param sLen The number of bytes to convert. If 0 an empty array will be returned.
  99. * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
  100. * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
  101. * little faster.
  102. * @return A BASE64 encoded array. Never <code>null</code>.
  103. */
  104. public final static byte[] encodeToByte(byte[] sArr, int sOff, int sLen, boolean lineSep)
  105. {
  106. // Check special case
  107. if (sArr == null || sLen == 0)
  108. return new byte[0];
  109. int eLen = (sLen / 3) * 3; // Length of even 24-bits.
  110. int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count
  111. int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array
  112. byte[] dArr = new byte[dLen];
  113. // Encode even 24-bits
  114. for (int s = sOff, d = 0, cc = 0; s < sOff + eLen;) {
  115. // Copy next three bytes into lower 24 bits of int, paying attension to sign.
  116. int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff);
  117. // Encode the int into four chars
  118. dArr[d++] = (byte) CA[(i >>> 18) & 0x3f];
  119. dArr[d++] = (byte) CA[(i >>> 12) & 0x3f];
  120. dArr[d++] = (byte) CA[(i >>> 6) & 0x3f];
  121. dArr[d++] = (byte) CA[i & 0x3f];
  122. // Add optional line separator
  123. if (lineSep && ++cc == 19 && d < dLen - 2) {
  124. dArr[d++] = '\r';
  125. dArr[d++] = '\n';
  126. cc = 0;
  127. }
  128. }
  129. // Pad and encode last bits if source isn't an even 24 bits.
  130. int left = sLen - eLen; // 0 - 2.
  131. if (left > 0) {
  132. // Prepare the int
  133. int i = ((sArr[sOff + eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sOff + sLen - 1] & 0xff) << 2) : 0);
  134. // Set last four chars
  135. dArr[dLen - 4] = (byte) CA[i >> 12];
  136. dArr[dLen - 3] = (byte) CA[(i >>> 6) & 0x3f];
  137. dArr[dLen - 2] = left == 2 ? (byte) CA[i & 0x3f] : (byte) '=';
  138. dArr[dLen - 1] = '=';
  139. }
  140. return dArr;
  141. }
  142. /** Decodes a BASE64 encoded byte array. All illegal characters will be ignored and can handle both arrays with
  143. * and without line separators.
  144. * @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
  145. * @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
  146. * (including '=') isn't divideable by 4. (I.e. definitely corrupted).
  147. */
  148. public final static byte[] decode(byte[] sArr) throws DecodeException
  149. {
  150. return decode(sArr, 0, sArr.length);
  151. }
  152. /** Decodes a BASE64 encoded byte array. All illegal characters will be ignored and can handle both arrays with
  153. * and without line separators.
  154. * @param sArr The source array. <code>null</code> will throw an exception.
  155. * @param sOff The starting position in the source array.
  156. * @param sLen The number of bytes to decode from the source array. Length 0 will return an empty array.
  157. * @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
  158. * (including '=') isn't divideable by 4. (I.e. definitely corrupted).
  159. */
  160. public final static byte[] decode(byte[] sArr, int sOff, int sLen) throws DecodeException
  161. {
  162. try {
  163. return doDecode(sArr, sOff, sLen);
  164. } catch (RuntimeException e) {
  165. throw new DecodeException(e);
  166. }
  167. }
  168. private final static byte[] doDecode(byte[] sArr, int sOff, int sLen) {
  169. // Count illegal characters (including '\r', '\n') to know what size the returned array will be,
  170. // so we don't have to reallocate & copy it later.
  171. int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
  172. 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.
  173. if (IA[sArr[sOff + i] & 0xff] < 0)
  174. sepCnt++;
  175. // Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
  176. if ((sLen - sepCnt) % 4 != 0)
  177. return null;
  178. int pad = 0;
  179. for (int i = sLen; i > 1 && IA[sArr[sOff + --i] & 0xff] <= 0;)
  180. if (sArr[sOff + i] == '=')
  181. pad++;
  182. int len = ((sLen - sepCnt) * 6 >> 3) - pad;
  183. byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
  184. for (int s = 0, d = 0; d < len;) {
  185. // Assemble three bytes into an int from four "valid" characters.
  186. int i = 0;
  187. for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
  188. int c = IA[sArr[sOff + s++] & 0xff];
  189. if (c >= 0)
  190. i |= c << (18 - j * 6);
  191. else
  192. j--;
  193. }
  194. // Add the bytes
  195. dArr[d++] = (byte) (i >> 16);
  196. if (d < len) {
  197. dArr[d++]= (byte) (i >> 8);
  198. if (d < len)
  199. dArr[d++] = (byte) i;
  200. }
  201. }
  202. return dArr;
  203. }
  204. /** Decodes a BASE64 encoded byte array that is known to be resonably well formatted. The method is about twice as
  205. * fast as {@link #decode(byte[])}. The preconditions are:<br>
  206. * + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
  207. * + Line separator must be "\r\n", as specified in RFC 2045
  208. * + The array must not contain illegal characters within the encoded string<br>
  209. * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
  210. * @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
  211. * @return The decoded array of bytes. May be of length 0.
  212. */
  213. public final static byte[] decodeFast(byte[] sArr, int sLen) throws DecodeException
  214. {
  215. try {
  216. return doDecodeFast(sArr, sLen);
  217. } catch (RuntimeException e) {
  218. throw new DecodeException(e);
  219. }
  220. }
  221. private final static byte[] doDecodeFast(byte[] sArr, int sLen) {
  222. // Check special case
  223. if (sLen == 0)
  224. return new byte[0];
  225. int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
  226. // Trim illegal chars from start
  227. while (sIx < eIx && IA[sArr[sIx] & 0xff] < 0)
  228. sIx++;
  229. // Trim illegal chars from end
  230. while (eIx > 0 && IA[sArr[eIx] & 0xff] < 0)
  231. eIx--;
  232. // get the padding count (=) (0, 1 or 2)
  233. int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end.
  234. int cCnt = eIx - sIx + 1; // Content count including possible separators
  235. int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0;
  236. int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
  237. byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
  238. // Decode all but the last 0 - 2 bytes.
  239. int d = 0;
  240. for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
  241. // Assemble three bytes into an int from four "valid" characters.
  242. int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]];
  243. // Add the bytes
  244. dArr[d++] = (byte) (i >> 16);
  245. dArr[d++] = (byte) (i >> 8);
  246. dArr[d++] = (byte) i;
  247. // If line separator, jump over it.
  248. if (sepCnt > 0 && ++cc == 19) {
  249. sIx += 2;
  250. cc = 0;
  251. }
  252. }
  253. if (d < len) {
  254. // Decode last 1-3 bytes (incl '=') into 1-3 bytes
  255. int i = 0;
  256. for (int j = 0; sIx <= eIx - pad; j++)
  257. i |= IA[sArr[sIx++]] << (18 - j * 6);
  258. for (int r = 16; d < len; r -= 8)
  259. dArr[d++] = (byte) (i >> r);
  260. }
  261. return dArr;
  262. }
  263. }