Use bytes.length in Base64Encoder loop

Update Base64Encoder to use `bytes.length` instead of `encoded.length`
when lopping over the bytes.

Fixes gh-3314
This commit is contained in:
izeye 2015-06-24 08:49:51 +09:00 committed by Phillip Webb
parent 855e5a8e5f
commit 286c98d716
2 changed files with 14 additions and 18 deletions

View File

@ -40,7 +40,7 @@ class Base64Encoder {
public static String encode(byte[] bytes) {
byte[] encoded = new byte[bytes.length / 3 * 4 + (bytes.length % 3 == 0 ? 0 : 4)];
for (int i = 0; i < encoded.length; i += 3) {
for (int i = 0; i < bytes.length; i += 3) {
encodeBlock(bytes, i, Math.min((bytes.length - i), 3), encoded, i / 3 * 4);
}
return new String(encoded, UTF_8);
@ -48,14 +48,12 @@ class Base64Encoder {
private static void encodeBlock(byte[] src, int srcPos, int blockLen, byte[] dest,
int destPos) {
if (blockLen > 0) {
int inBuff = (blockLen > 0 ? ((src[srcPos] << 24) >>> 8) : 0)
| (blockLen > 1 ? ((src[srcPos + 1] << 24) >>> 16) : 0)
| (blockLen > 2 ? ((src[srcPos + 2] << 24) >>> 24) : 0);
for (int i = 0; i < 4; i++) {
dest[destPos + i] = (i > blockLen ? EQUALS_SIGN
: ALPHABET[(inBuff >>> (6 * (3 - i))) & 0x3f]);
}
int inBuff = (blockLen > 0 ? ((src[srcPos] << 24) >>> 8) : 0)
| (blockLen > 1 ? ((src[srcPos + 1] << 24) >>> 16) : 0)
| (blockLen > 2 ? ((src[srcPos + 2] << 24) >>> 24) : 0);
for (int i = 0; i < 4; i++) {
dest[destPos + i] = (i > blockLen ? EQUALS_SIGN
: ALPHABET[(inBuff >>> (6 * (3 - i))) & 0x3f]);
}
}

View File

@ -40,7 +40,7 @@ class Base64Encoder {
public static String encode(byte[] bytes) {
byte[] encoded = new byte[bytes.length / 3 * 4 + (bytes.length % 3 == 0 ? 0 : 4)];
for (int i = 0; i < encoded.length; i += 3) {
for (int i = 0; i < bytes.length; i += 3) {
encodeBlock(bytes, i, Math.min((bytes.length - i), 3), encoded, i / 3 * 4);
}
return new String(encoded, UTF_8);
@ -48,14 +48,12 @@ class Base64Encoder {
private static void encodeBlock(byte[] src, int srcPos, int blockLen, byte[] dest,
int destPos) {
if (blockLen > 0) {
int inBuff = (blockLen > 0 ? ((src[srcPos] << 24) >>> 8) : 0)
| (blockLen > 1 ? ((src[srcPos + 1] << 24) >>> 16) : 0)
| (blockLen > 2 ? ((src[srcPos + 2] << 24) >>> 24) : 0);
for (int i = 0; i < 4; i++) {
dest[destPos + i] = (i > blockLen ? EQUALS_SIGN
: ALPHABET[(inBuff >>> (6 * (3 - i))) & 0x3f]);
}
int inBuff = (blockLen > 0 ? ((src[srcPos] << 24) >>> 8) : 0)
| (blockLen > 1 ? ((src[srcPos + 1] << 24) >>> 16) : 0)
| (blockLen > 2 ? ((src[srcPos + 2] << 24) >>> 24) : 0);
for (int i = 0; i < 4; i++) {
dest[destPos + i] = (i > blockLen ? EQUALS_SIGN
: ALPHABET[(inBuff >>> (6 * (3 - i))) & 0x3f]);
}
}