@@ -700,40 +700,42 @@ namespace http
700700 return table;
701701 }();
702702
703+ constexpr uint8_t top6 (const uint8_t a) {return a >> 2 ;}
704+ constexpr uint8_t bot6 (const uint8_t a) {return a & 0x3f ;}
705+ constexpr uint8_t top4 (const uint8_t a) {return a >> 4 ;}
706+ constexpr uint8_t bot4 (const uint8_t a) {return a & 0x0f ;}
707+ constexpr uint8_t top2 (const uint8_t a) {return a >> 6 ;}
708+ constexpr uint8_t bot2 (const uint8_t a) {return a & 0x03 ;}
709+
703710 std::string base64_encode (const size_t ndata, const uint8_t * data)
704711 {
705712 std::string ret;
706713 ret.resize ((ndata+2 ) / 3 * 4 );
707- size_t i{0 };
708- char * out{&ret[0 ]};
714+ char * out{&ret[0 ]};
709715
710- while (i < ndata)
716+ for ( size_t i = 0 ; i < ndata ; i += 3 )
711717 {
712- *out++ = base64_encode_table[(data[i+0 ] & 0xfc ) >> 2 ];
713-
714- if (i+1 < ndata)
718+ if (i+2 < ndata)
715719 {
716- *out++ = base64_encode_table[((data[i+0 ] & 0x03 ) << 4 ) + ((data[i + 1 ] & 0xf0 ) >> 4 )];
717-
718- if (i+2 < ndata)
719- {
720- *out++ = base64_encode_table[((data[i+1 ] & 0x0f ) << 2 ) + ((data[i + 2 ] & 0xc0 ) >> 6 )];
721- *out++ = base64_encode_table[ data[i+2 ] & 0x3f ];
722- }
723- else
724- {
725- *out++ = base64_encode_table[(data[i+1 ] & 0x0f ) << 2 ];
726- *out++ = ' =' ;
727- }
720+ *out++ = base64_encode_table[top6 (data[i+0 ])];
721+ *out++ = base64_encode_table[(bot2 (data[i+0 ]) << 4 ) | top4 (data[i+1 ])];
722+ *out++ = base64_encode_table[(bot4 (data[i+1 ]) << 2 ) | top2 (data[i+2 ])];
723+ *out++ = base64_encode_table[bot6 (data[i+2 ])];
728724 }
729- else
725+ else if (i+1 < ndata)
726+ {
727+ *out++ = base64_encode_table[top6 (data[i+0 ])];
728+ *out++ = base64_encode_table[(bot2 (data[i+0 ]) << 4 ) | top4 (data[i+1 ])];
729+ *out++ = base64_encode_table[bot4 (data[i+1 ]) << 2 ];
730+ *out++ = ' =' ;
731+ }
732+ else
730733 {
731- *out++ = base64_encode_table[(data[i+0 ] & 0x03 ) << 4 ];
734+ *out++ = base64_encode_table[top6 (data[i+0 ])];
735+ *out++ = base64_encode_table[bot2 (data[i+0 ]) << 4 ];
732736 *out++ = ' =' ;
733737 *out++ = ' =' ;
734738 }
735-
736- i += 3 ;
737739 }
738740
739741 return ret;
0 commit comments