ReneNyffenegger / cpp-base64

base64 encoding and decoding with c++
Other
891 stars 311 forks source link

Removed code that does not contribute to the result #3

Closed Ingmar-Paetzold closed 7 years ago

Ingmar-Paetzold commented 7 years ago

While working on a derived implementation of the base64 code, I got an exception in the decode function and started wondering what the find() function (line 117) would return when it gets one of the 0-bytes that have been put to char_array_4 in line 114. It is actually std::string::npos, thus -1. All bits set?? Does not sound like base64.

So I noticed that the block after "if (i)" is only entered for i = 2 or 3. That narrows j in the for loop in line 116 to 0, 1 or 2. -> char_array_4[3] is no longer accessed. Also, since this block handles the cases where 1 or 2 bytes of the original buffer are encoded into 4 bytes, where only char_array_3[0] and char_array_3[1] are used which renders line 121 useless.

As a consequence, the whole filling with zeros in lines 113 and 114 is not necessary at all and can be omitted. Just adapt the following for loop to not use these bytes.

A similar situation applies in line 74 of the encode function: the block after "if (i)" handles cases where one or two original bytes are encoded (i = 1 or 2), but not 3, so char_array_3[2] is not needed, therefore char_array_4[3] likewise. The for loop in line 76 can generate j = 0, 1 or 2 (thus, again, char_array_4[3] is never accessed).

I added some more tests where all three cases are tested: number of bytes divisible by 3 (thus, i=0, no '='), and those with rest 1 and 2 (i.e. two trailing ==, or one =, resp.).

ReneNyffenegger commented 7 years ago

Thanks for the contribution. I've merged it into master.