authorgravatar for sadikov.igor@uqam.caIgor Sadikov <sadikov.igor@uqam.ca> 2023-08-28 20:30:49-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-08-29 16:00:31-04:00
log4635179857999a64ce8350c9b3cbe90cede9ea8c
tree933e0470c05ffa496718509316b681fe61ce321f
parent3b2b9fcbc5e162063febf989883f29e55cc64c65

Optimize std.base64.standard.Encoder.encode


1 files changed, 16 insertions(+), 13 deletions(-)

lib/std/base64.zig+16-13
...@@ -100,21 +100,24 @@ pub const Base64Encoder = struct {...@@ -100,21 +100,24 @@ pub const Base64Encoder = struct {
100 const out_len = encoder.calcSize(source.len);100 const out_len = encoder.calcSize(source.len);
101 assert(dest.len >= out_len);101 assert(dest.len >= out_len);
102102
103 var acc: u12 = 0;103 var idx: usize = 0;
104 var acc_len: u4 = 0;
105 var out_idx: usize = 0;104 var out_idx: usize = 0;
106 for (source) |v| {105 while (idx + 2 < source.len) : (idx += 3) {
107 acc = (acc << 8) + v;106 dest[out_idx] = encoder.alphabet_chars[source[idx] >> 2];
108 acc_len += 8;107 dest[out_idx + 1] = encoder.alphabet_chars[((source[idx] & 0x3) << 4) | (source[idx + 1] >> 4)];
109 while (acc_len >= 6) {108 dest[out_idx + 2] = encoder.alphabet_chars[(source[idx + 1] & 0xf) << 2 | (source[idx + 2] >> 6)];
110 acc_len -= 6;109 dest[out_idx + 3] = encoder.alphabet_chars[source[idx + 2] & 0x3f];
111 dest[out_idx] = encoder.alphabet_chars[@as(u6, @truncate((acc >> acc_len)))];110 out_idx += 4;
112 out_idx += 1;
113 }
114 }111 }
115 if (acc_len > 0) {112 if (idx + 1 < source.len) {
116 dest[out_idx] = encoder.alphabet_chars[@as(u6, @truncate((acc << 6 - acc_len)))];113 dest[out_idx] = encoder.alphabet_chars[source[idx] >> 2];
117 out_idx += 1;114 dest[out_idx + 1] = encoder.alphabet_chars[((source[idx] & 0x3) << 4) | (source[idx + 1] >> 4)];
115 dest[out_idx + 2] = encoder.alphabet_chars[(source[idx + 1] & 0xf) << 2];
116 out_idx += 3;
117 } else if (idx < source.len) {
118 dest[out_idx] = encoder.alphabet_chars[source[idx] >> 2];
119 dest[out_idx + 1] = encoder.alphabet_chars[(source[idx] & 0x3) << 4];
120 out_idx += 2;
118 }121 }
119 if (encoder.pad_char) |pad_char| {122 if (encoder.pad_char) |pad_char| {
120 for (dest[out_idx..out_len]) |*pad| {123 for (dest[out_idx..out_len]) |*pad| {