Skip to content

Commit e284a95

Browse files
committed
ubinascii: b2a_base64: Optimize away a modulo operation.
1 parent 616986a commit e284a95

1 file changed

Lines changed: 8 additions & 3 deletions

File tree

extmod/modubinascii.c

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -147,17 +147,20 @@ mp_obj_t mod_binascii_b2a_base64(mp_obj_t data) {
147147

148148
vstr_t vstr;
149149
vstr_init_len(&vstr, ((bufinfo.len != 0) ? (((bufinfo.len - 1) / 3) + 1) * 4 : 0) + 1);
150+
151+
// First pass, we convert input buffer to numeric base 64 values
150152
byte *in = bufinfo.buf, *out = (byte*)vstr.buf;
151-
for (mp_uint_t i = bufinfo.len; i >= 3; i -= 3) {
153+
mp_uint_t i;
154+
for (i = bufinfo.len; i >= 3; i -= 3) {
152155
*out++ = (in[0] & 0xFC) >> 2;
153156
*out++ = (in[0] & 0x03) << 4 | (in[1] & 0xF0) >> 4;
154157
*out++ = (in[1] & 0x0F) << 2 | (in[2] & 0xC0) >> 6;
155158
*out++ = in[2] & 0x3F;
156159
in += 3;
157160
}
158-
if (bufinfo.len % 3 != 0) {
161+
if (i != 0) {
159162
*out++ = (in[0] & 0xFC) >> 2;
160-
if (bufinfo.len % 3 == 2) {
163+
if (i == 2) {
161164
*out++ = (in[0] & 0x03) << 4 | (in[1] & 0xF0) >> 4;
162165
*out++ = (in[1] & 0x0F) << 2;
163166
}
@@ -167,6 +170,8 @@ mp_obj_t mod_binascii_b2a_base64(mp_obj_t data) {
167170
}
168171
*out++ = 64;
169172
}
173+
174+
// Second pass, we convert number base 64 values to actual base64 ascii encoding
170175
out = (byte*)vstr.buf;
171176
for (mp_uint_t i = vstr.len - 1; i--;) {
172177
if (*out < 26) {

0 commit comments

Comments
 (0)