PageRenderTime 33ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/com/alibaba/fastjson/util/Base64.java

https://bitbucket.org/xiejuntao/xdesktop
Java | 198 lines | 80 code | 28 blank | 90 comment | 33 complexity | f71ddd74af66b035398ae5dc14a963eb MD5 | raw file
  1. package com.alibaba.fastjson.util;
  2. import java.util.Arrays;
  3. /**
  4. * A very fast and memory efficient class to encode and decode to and from BASE64 in full accordance with RFC 2045.<br>
  5. * <br>
  6. * On Windows XP sp1 with 1.4.2_04 and later ;), this encoder and decoder is about 10 times faster on small arrays (10 -
  7. * 1000 bytes) and 2-3 times as fast on larger arrays (10000 - 1000000 bytes) compared to
  8. * <code>sun.misc.Encoder()/Decoder()</code>.<br>
  9. * <br>
  10. * On byte arrays the encoder is about 20% faster than Jakarta Commons Base64 Codec for encode and about 50% faster for
  11. * decoding large arrays. This implementation is about twice as fast on very small arrays (&lt 30 bytes). If
  12. * source/destination is a <code>String</code> this version is about three times as fast due to the fact that the
  13. * Commons Codec result has to be recoded to a <code>String</code> from <code>byte[]</code>, which is very expensive.<br>
  14. * <br>
  15. * This encode/decode algorithm doesn't create any temporary arrays as many other codecs do, it only allocates the
  16. * resulting array. This produces less garbage and it is possible to handle arrays twice as large as algorithms that
  17. * create a temporary array. (E.g. Jakarta Commons Codec). It is unknown whether Sun's
  18. * <code>sun.misc.Encoder()/Decoder()</code> produce temporary arrays but since performance is quite low it probably
  19. * does.<br>
  20. * <br>
  21. * The encoder produces the same output as the Sun one except that the Sun's encoder appends a trailing line separator
  22. * if the last character isn't a pad. Unclear why but it only adds to the length and is probably a side effect. Both are
  23. * in conformance with RFC 2045 though.<br>
  24. * Commons codec seem to always att a trailing line separator.<br>
  25. * <br>
  26. * <b>Note!</b> The encode/decode method pairs (types) come in three versions with the <b>exact</b> same algorithm and
  27. * thus a lot of code redundancy. This is to not create any temporary arrays for transcoding to/from different format
  28. * types. The methods not used can simply be commented out.<br>
  29. * <br>
  30. * There is also a "fast" version of all decode methods that works the same way as the normal ones, but har a few
  31. * demands on the decoded input. Normally though, these fast verions should be used if the source if the input is known
  32. * and it hasn't bee tampered with.<br>
  33. * <br>
  34. * If you find the code useful or you find a bug, please send me a note at base64 @ miginfocom . com. Licence (BSD):
  35. * ============== Copyright (c) 2004, Mikael Grev, MiG InfoCom AB. (base64 @ miginfocom . com) All rights reserved.
  36. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
  37. * following conditions are met: Redistributions of source code must retain the above copyright notice, this list of
  38. * conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice,
  39. * this list of conditions and the following disclaimer in the documentation and/or other materials provided with the
  40. * distribution. Neither the name of the MiG InfoCom AB nor the names of its contributors may be used to endorse or
  41. * promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY
  42. * THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  43. * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  44. * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  45. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  46. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  47. * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  48. * POSSIBILITY OF SUCH DAMAGE.
  49. *
  50. * @version 2.2
  51. * @author Mikael Grev Date: 2004-aug-02 Time: 11:31:11
  52. */
  53. public class Base64 {
  54. public static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
  55. public static final int[] IA = new int[256];
  56. static {
  57. Arrays.fill(IA, -1);
  58. for (int i = 0, iS = CA.length; i < iS; i++)
  59. IA[CA[i]] = i;
  60. IA['='] = 0;
  61. }
  62. /**
  63. * Decodes a BASE64 encoded char array that is known to be resonably well formatted. The method is about twice as
  64. * fast as {@link #decode(char[])}. The preconditions are:<br>
  65. * + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
  66. * + Line separator must be "\r\n", as specified in RFC 2045 + The array must not contain illegal characters within
  67. * the encoded string<br>
  68. * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
  69. *
  70. * @param chars The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
  71. * @return The decoded array of bytes. May be of length 0.
  72. */
  73. public final static byte[] decodeFast(char[] chars, int offset, int charsLen) {
  74. // Check special case
  75. if (charsLen == 0) {
  76. return new byte[0];
  77. }
  78. int sIx = offset, eIx = offset + charsLen - 1; // Start and end index after trimming.
  79. // Trim illegal chars from start
  80. while (sIx < eIx && IA[chars[sIx]] < 0)
  81. sIx++;
  82. // Trim illegal chars from end
  83. while (eIx > 0 && IA[chars[eIx]] < 0)
  84. eIx--;
  85. // get the padding count (=) (0, 1 or 2)
  86. int pad = chars[eIx] == '=' ? (chars[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end.
  87. int cCnt = eIx - sIx + 1; // Content count including possible separators
  88. int sepCnt = charsLen > 76 ? (chars[76] == '\r' ? cCnt / 78 : 0) << 1 : 0;
  89. int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
  90. byte[] bytes = new byte[len]; // Preallocate byte[] of exact length
  91. // Decode all but the last 0 - 2 bytes.
  92. int d = 0;
  93. for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
  94. // Assemble three bytes into an int from four "valid" characters.
  95. int i = IA[chars[sIx++]] << 18 | IA[chars[sIx++]] << 12 | IA[chars[sIx++]] << 6 | IA[chars[sIx++]];
  96. // Add the bytes
  97. bytes[d++] = (byte) (i >> 16);
  98. bytes[d++] = (byte) (i >> 8);
  99. bytes[d++] = (byte) i;
  100. // If line separator, jump over it.
  101. if (sepCnt > 0 && ++cc == 19) {
  102. sIx += 2;
  103. cc = 0;
  104. }
  105. }
  106. if (d < len) {
  107. // Decode last 1-3 bytes (incl '=') into 1-3 bytes
  108. int i = 0;
  109. for (int j = 0; sIx <= eIx - pad; j++)
  110. i |= IA[chars[sIx++]] << (18 - j * 6);
  111. for (int r = 16; d < len; r -= 8)
  112. bytes[d++] = (byte) (i >> r);
  113. }
  114. return bytes;
  115. }
  116. /**
  117. * Decodes a BASE64 encoded string that is known to be resonably well formatted. The method is about twice as fast
  118. * as {@link #decode(String)}. The preconditions are:<br>
  119. * + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
  120. * + Line separator must be "\r\n", as specified in RFC 2045 + The array must not contain illegal characters within
  121. * the encoded string<br>
  122. * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
  123. *
  124. * @param s The source string. Length 0 will return an empty array. <code>null</code> will throw an exception.
  125. * @return The decoded array of bytes. May be of length 0.
  126. */
  127. public final static byte[] decodeFast(String s) {
  128. // Check special case
  129. int sLen = s.length();
  130. if (sLen == 0) return new byte[0];
  131. int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
  132. // Trim illegal chars from start
  133. while (sIx < eIx && IA[s.charAt(sIx) & 0xff] < 0)
  134. sIx++;
  135. // Trim illegal chars from end
  136. while (eIx > 0 && IA[s.charAt(eIx) & 0xff] < 0)
  137. eIx--;
  138. // get the padding count (=) (0, 1 or 2)
  139. int pad = s.charAt(eIx) == '=' ? (s.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count '=' at end.
  140. int cCnt = eIx - sIx + 1; // Content count including possible separators
  141. int sepCnt = sLen > 76 ? (s.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0;
  142. int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
  143. byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
  144. // Decode all but the last 0 - 2 bytes.
  145. int d = 0;
  146. for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
  147. // Assemble three bytes into an int from four "valid" characters.
  148. int i = IA[s.charAt(sIx++)] << 18 | IA[s.charAt(sIx++)] << 12 | IA[s.charAt(sIx++)] << 6
  149. | IA[s.charAt(sIx++)];
  150. // Add the bytes
  151. dArr[d++] = (byte) (i >> 16);
  152. dArr[d++] = (byte) (i >> 8);
  153. dArr[d++] = (byte) i;
  154. // If line separator, jump over it.
  155. if (sepCnt > 0 && ++cc == 19) {
  156. sIx += 2;
  157. cc = 0;
  158. }
  159. }
  160. if (d < len) {
  161. // Decode last 1-3 bytes (incl '=') into 1-3 bytes
  162. int i = 0;
  163. for (int j = 0; sIx <= eIx - pad; j++)
  164. i |= IA[s.charAt(sIx++)] << (18 - j * 6);
  165. for (int r = 16; d < len; r -= 8)
  166. dArr[d++] = (byte) (i >> r);
  167. }
  168. return dArr;
  169. }
  170. }