1 22 23 24 package org.ozoneDB.util; 25 26 27 35 public final class MimeBase64Encoder { 36 37 38 private StringBuffer out = new StringBuffer (); 39 40 private int buf = 0; 41 private int buf_bytes = 0; 42 private char[] line = new char[74]; 43 private int line_length = 0; 44 45 private final static byte[] crlf = "\r\n".getBytes(); 46 47 private final static char[] map = 48 49 {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; 50 59 60 private final void encode_token() { 61 int i = line_length; 62 line[i] = map[0x3F & buf >> 18]; 63 line[i + 1] = map[0x3F & buf >> 12]; 64 line[i + 2] = map[0x3F & buf >> 6]; 65 line[i + 3] = map[0x3F & buf]; 66 line_length += 4; 67 buf = 0; 68 buf_bytes = 0; 69 } 70 71 72 private final void encode_partial_token() { 73 int i = line_length; 74 line[i] = map[0x3F & buf >> 18]; 75 line[i + 1] = map[0x3F & buf >> 12]; 76 77 if (buf_bytes == 1) { 78 line[i + 2] = '='; 79 } else { 80 line[i + 2] = map[0x3F & buf >> 6]; 81 } 82 83 if (buf_bytes <= 2) { 84 line[i + 3] = '='; 85 } else { 86 line[i + 3] = map[0x3F & buf]; 87 } 88 line_length += 4; 89 buf = 0; 90 buf_bytes = 0; 91 } 92 93 94 private final void flush_line() { 95 out.append( line, 0, line_length ); 96 line_length = 0; 97 } 98 99 100 106 public final void translate( byte[] in ) { 107 int in_length = in.length; 108 109 for (int i = 0; i < in_length; i++) { 110 if (buf_bytes == 0) { 111 buf = buf & 0x00FFFF | in[i] << 16; 112 } else if (buf_bytes == 1) { 113 buf = buf & 0xFF00FF | in[i] << 8 & 0x00FFFF; 114 } else { 115 buf = buf & 0xFFFF00 | in[i] & 0x0000FF; 116 } 117 118 if (++buf_bytes == 3) { 119 encode_token(); 120 if (line_length >= 72) { 121 flush_line(); 122 } 123 } 124 125 if (i == (in_length - 1)) { 126 if (buf_bytes > 0 && buf_bytes < 3) { 127 encode_partial_token(); 128 } 129 if (line_length > 0) { 130 flush_line(); 131 } 132 } 133 } 134 135 for (int i = 0; i < line.length; i++) { 136 line[i] = 0; 137 } 138 } 139 140 141 public char[] getCharArray() { 142 char[] ch; 143 144 if (buf_bytes != 0) { 145 encode_partial_token(); 146 } 147 flush_line(); 148 for (int i = 0; i < line.length; i++) { 149 line[i] = 0; 150 } 151 ch = new char[out.length()]; 152 out.getChars( 0, out.length(), ch, 0 ); 153 return ch; 154 } 155 } 156 | Popular Tags |