From 0dfa601b9fec5191269702cdd037adf25814ab19 Mon Sep 17 00:00:00 2001 From: Rob Landley Date: Wed, 2 Mar 2016 22:05:21 -0600 Subject: Fix base64 so == wraps properly. --- toys/other/base64.c | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) (limited to 'toys') diff --git a/toys/other/base64.c b/toys/other/base64.c index 7dc61147..234ca1c3 100644 --- a/toys/other/base64.c +++ b/toys/other/base64.c @@ -24,26 +24,39 @@ config BASE64 GLOBALS( long columns; + + unsigned total; ) +static void wraputchar(int c, int *x) +{ + putchar(c); + TT.total++; + if (++*x == TT.columns) { + *x = 0; + xputc('\n'); + }; +} + static void do_base64(int fd, char *name) { int out = 0, bits = 0, x = 0, i, len; char *buf = toybuf+128; + TT.total = 0; + for (;;) { + // If no more data, flush buffer if (!(len = xread(fd, buf, sizeof(toybuf)-128))) { if (!(toys.optflags & FLAG_d)) { - if (bits) { - putchar(toybuf[out<<(6-bits)]); - x++; - } - while (x++&3) putchar('='); - if (x != 1) xputc('\n'); + if (bits) wraputchar(toybuf[out<<(6-bits)], &x); + while (TT.total&3) wraputchar('=', &x); + if (x) xputc('\n'); } return; } + for (i=0; i