From 0517eb7d604da454213e42d55f477401dc7f7ebf Mon Sep 17 00:00:00 2001 From: Rob Landley Date: Sat, 13 Dec 2014 11:58:08 -0600 Subject: Add base64. The tizen guys wanted this. Yeah, I know there's base64 code in uuencode/uudecode, but that this has -i, input lines aren't of fixed length, encode/decode are in same file, there's no prefix/suffix code, it always writes to stdout... Eliminating the code duplication wouldn't be worth the if/else I'd have to add, so I just did a new one. Factored out the base64 table init into lib.c though: that was worth sharing. --- lib/lib.c | 15 +++++++++ toys/other/base64.c | 87 +++++++++++++++++++++++++++++++++++++++++++++++++++ toys/posix/uuencode.c | 11 +------ 3 files changed, 103 insertions(+), 10 deletions(-) create mode 100644 toys/other/base64.c diff --git a/lib/lib.c b/lib/lib.c index 33be44b6..490235f4 100644 --- a/lib/lib.c +++ b/lib/lib.c @@ -571,6 +571,21 @@ void crc_init(unsigned int *crc_table, int little_endian) } } +// Init base64 table + +void base64_init(char *p) +{ + int i; + + for (i = 'A'; i != ':'; i++) { + if (i == 'Z'+1) i = 'a'; + if (i == 'z'+1) i = '0'; + *(p++) = i; + } + *(p++) = '+'; + *(p++) = '/'; +} + // Quick and dirty query size of terminal, doesn't do ANSI probe fallback. // set x=80 y=25 before calling to provide defaults. Returns 0 if couldn't // determine size. diff --git a/toys/other/base64.c b/toys/other/base64.c new file mode 100644 index 00000000..7dc61147 --- /dev/null +++ b/toys/other/base64.c @@ -0,0 +1,87 @@ +/* base64.c - Encode and decode base64 + * + * Copyright 2014 Rob Landley + * + * No standard + +USE_BASE64(NEWTOY(base64, "diw#<1[!dw]", TOYFLAG_USR|TOYFLAG_BIN)) + +config BASE64 + bool "base64" + default y + help + usage: base64 [-di] [-w COLUMNS] [FILE...] + + Encode or decode in base64. + + -d decode + -i ignore non-alphabetic characters + -w wrap output at COLUMNS (default 76) +*/ + +#define FOR_base64 +#include "toys.h" + +GLOBALS( + long columns; +) + +static void do_base64(int fd, char *name) +{ + int out = 0, bits = 0, x = 0, i, len; + char *buf = toybuf+128; + + for (;;) { + 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'); + } + + return; + } + for (i=0; i= 6) { + putchar(toybuf[out >> (bits -= 6)]); + out &= (1< 1) fd = xopen(toys.optargs[0], O_RDONLY); - // base64 table - - p = toybuf; - for (i = 'A'; i != ':'; i++) { - if (i == 'Z'+1) i = 'a'; - if (i == 'z'+1) i = '0'; - *(p++) = i; - } - *(p++) = '+'; - *(p++) = '/'; + base64_init(toybuf); xprintf("begin%s 744 %s\n", m ? "-base64" : "", name); for (;;) { -- cgit v1.2.3