- const unsigned char *usrc = src;
- int origlen = length;
-
- while(length > 0) {
- if(length >= 3) {
- triplet = usrc[0] | usrc[1] << 8 | usrc[2] << 16;
- dst[0] = base64imals[triplet & 63]; triplet >>= 6;
- dst[1] = base64imals[triplet & 63]; triplet >>= 6;
- dst[2] = base64imals[triplet & 63]; triplet >>= 6;
- dst[3] = base64imals[triplet];
- dst += 4; usrc += 3; length -= 3;
- } else if(length >=2) {
- triplet = usrc[0] | usrc[1] << 8;
- dst[0] = base64imals[triplet & 63]; triplet >>= 6;
- dst[1] = base64imals[triplet & 63]; triplet >>= 6;
- dst[2] = base64imals[triplet];
- dst[3] = 0;
- return origlen / 3 * 4 + 3;
- } else {
- triplet = usrc[0];
- dst[0] = base64imals[triplet & 63]; triplet >>= 6;
- dst[1] = base64imals[triplet];
- dst[2] = 0;
- return origlen / 3 * 4 + 2;
- }
+ const unsigned char *usrc = (unsigned char *)src;
+ int si = length / 3 * 3;
+ int di = length / 3 * 4;
+
+ switch(length % 3) {
+ case 2:
+ triplet = usrc[si] | usrc[si + 1] << 8;
+ dst[di] = base64imals[triplet & 63]; triplet >>= 6;
+ dst[di + 1] = base64imals[triplet & 63]; triplet >>= 6;
+ dst[di + 2] = base64imals[triplet];
+ dst[di + 3] = 0;
+ length = di + 2;
+ break;
+ case 1:
+ triplet = usrc[si];
+ dst[di] = base64imals[triplet & 63]; triplet >>= 6;
+ dst[di + 1] = base64imals[triplet];
+ dst[di + 2] = 0;
+ length = di + 1;
+ break;
+ default:
+ dst[di] = 0;
+ length = di;
+ break;