diff --git a/lib/base64.c b/lib/base64.c index f3f7298aa..786b0f418 100644 --- a/lib/base64.c +++ b/lib/base64.c @@ -64,11 +64,11 @@ static const char b64c[64] = /* Base64 encode IN array of size INLEN into OUT array. OUT needs to be of length >= BASE64_LENGTH(INLEN), and INLEN needs to be - a multiple of 3. */ + a positive multiple of 3. */ static void base64_encode_fast (const char *restrict in, size_t inlen, char *restrict out) { - while (inlen) + do { *out++ = b64c[to_uchar (in[0]) >> 2]; *out++ = b64c[((to_uchar (in[0]) << 4) + (to_uchar (in[1]) >> 4)) & 0x3f]; @@ -78,6 +78,7 @@ base64_encode_fast (const char *restrict in, size_t inlen, char *restrict out) inlen -= 3; in += 3; } + while (inlen); } /* Base64 encode IN array of size INLEN into OUT array of size OUTLEN. @@ -88,6 +89,9 @@ void base64_encode (const char *restrict in, size_t inlen, char *restrict out, size_t outlen) { + if (!outlen) + return; + /* Note this outlen constraint can be enforced at compile time. I.E. that the output buffer is exactly large enough to hold the encoded inlen bytes. The inlen constraints (of corresponding @@ -101,16 +105,17 @@ base64_encode (const char *restrict in, size_t inlen, return; } - while (inlen && outlen) + if (inlen) + while (true) { *out++ = b64c[to_uchar (in[0]) >> 2]; if (!--outlen) - break; + return; *out++ = b64c[((to_uchar (in[0]) << 4) + (--inlen ? to_uchar (in[1]) >> 4 : 0)) & 0x3f]; if (!--outlen) - break; + return; *out++ = (inlen ? b64c[((to_uchar (in[1]) << 2) @@ -118,18 +123,17 @@ base64_encode (const char *restrict in, size_t inlen, & 0x3f] : '='); if (!--outlen) - break; + return; *out++ = inlen ? b64c[to_uchar (in[2]) & 0x3f] : '='; if (!--outlen) + return; + if (inlen <= 1) break; - if (inlen) - inlen--; - if (inlen) - in += 3; + inlen--; + in += 3; } - if (outlen) - *out = '\0'; + *out = '\0'; } /* Allocate a buffer and store zero terminated base64 encoded data