toybox/toys/other/ascii.c
<<
>>
Prefs
   1/* ascii.c - display ascii table
   2 *
   3 * Copyright 2017 Rob Landley <rob@landley.net>
   4 *
   5 * Technically 7-bit ASCII is ANSI X3.4-1986, a standard available as
   6 * INCITS 4-1986[R2012] on ansi.org, but they charge for it.
   7 *
   8 * unicode.c - convert between Unicode and UTF-8
   9 *
  10 * Copyright 2020 The Android Open Source Project.
  11 *
  12 * Loosely based on the Plan9/Inferno unicode(1).
  13
  14USE_ASCII(NEWTOY(ascii, 0, TOYFLAG_USR|TOYFLAG_BIN|TOYFLAG_LINEBUF))
  15USE_UNICODE(NEWTOY(unicode, "<1", TOYFLAG_USR|TOYFLAG_BIN))
  16
  17config ASCII
  18  bool "ascii"
  19  default y
  20  help
  21    usage: ascii
  22
  23    Display ascii character set.
  24
  25config UNICODE
  26  bool "unicode"
  27  default y
  28  help
  29    usage: unicode CODE[-END]...
  30
  31    Convert between Unicode code points and UTF-8, in both directions.
  32    CODE can be one or more characters (show U+XXXX), hex numbers
  33    (show character), or dash separated range.
  34*/
  35
  36#define FOR_unicode
  37#include "toys.h"
  38
  39static char *low="NULSOHSTXETXEOTENQACKBELBS HT LF VT FF CR SO SI DLEDC1DC2"
  40                 "DC3DC4NAKSYNETBCANEM SUBESCFS GS RS US ";
  41
  42static void codepoint(unsigned wc)
  43{
  44  char *s = toybuf + sprintf(toybuf, "U+%04X : ", wc), *ss;
  45  unsigned n, i;
  46
  47  if (wc>31 && wc!=127) {
  48    s += n = wctoutf8(ss = s, wc);
  49    if (n>1) for (i = 0; i<n; i++) s += sprintf(s, " : %#02x"+2*!!i, *ss++);
  50  } else s = memcpy(s, (wc==127) ? "DEL" : low+wc*3, 3)+3;
  51  *s++ = '\n';
  52  writeall(1, toybuf, s-toybuf);
  53}
  54
  55void unicode_main(void)
  56{
  57  int from, to, n;
  58  char next, **args, *s;
  59  unsigned wc;
  60
  61  // Loop through args, handling range, hex code, or character(s)
  62  for (args = toys.optargs; *args; args++) {
  63    if (sscanf(*args, "%x-%x%c", &from, &to, &next) == 2)
  64      while (from <= to) codepoint(from++);
  65    else if (sscanf(*args, "%x%c", &from, &next) == 1) codepoint(from);
  66    else for (s = *args; (n = utf8towc(&wc, s, 4)) > 0; s += n) codepoint(wc);
  67  }
  68}
  69
  70void ascii_main(void)
  71{
  72  char *s = toybuf;
  73  int i, x, y;
  74
  75  for (y = -1; y<16; y++) for (x = 0; x<8; x++) {
  76    if (y>=0) {
  77      i = (x<<4)+y;
  78      s += sprintf(s, "% *d %02X ", 3+(x>5), i, i);
  79      if (i<32 || i==127) s += sprintf(s, "%.3s", (i<32) ? low+3*i : "DEL");
  80      else *s++ = i;
  81    } else s += sprintf(s, "Dec Hex%*c", 1+2*(x<2)+(x>4), ' ');
  82    *s++ = (x>6) ? '\n' : ' ';
  83  }
  84  writeall(1, toybuf, s-toybuf);
  85}
  86