ascii.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. USE_ASCII(NEWTOY(ascii, 0, TOYFLAG_USR|TOYFLAG_BIN|TOYFLAG_LINEBUF))
  14. USE_UNICODE(NEWTOY(unicode, "<1", TOYFLAG_USR|TOYFLAG_BIN))
  15. config ASCII
  16. bool "ascii"
  17. default y
  18. help
  19. usage: ascii
  20. Display ascii character set.
  21. config UNICODE
  22. bool "unicode"
  23. default y
  24. help
  25. usage: unicode CODE[-END]...
  26. Convert between Unicode code points and UTF-8, in both directions.
  27. CODE can be one or more characters (show U+XXXX), hex numbers
  28. (show character), or dash separated range.
  29. */
  30. #define FOR_unicode
  31. #include "toys.h"
  32. static char *low="NULSOHSTXETXEOTENQACKBELBS HT LF VT FF CR SO SI DLEDC1DC2"
  33. "DC3DC4NAKSYNETBCANEM SUBESCFS GS RS US ";
  34. static void codepoint(unsigned wc)
  35. {
  36. char *s = toybuf + sprintf(toybuf, "U+%04X : ", wc), *ss;
  37. unsigned n, i;
  38. if (wc>31 && wc!=127) {
  39. s += n = wctoutf8(ss = s, wc);
  40. if (n>1) for (i = 0; i<n; i++) s += sprintf(s, " : %#02x"+2*!!i, *ss++);
  41. } else s = memcpy(s, (wc==127) ? "DEL" : low+wc*3, 3)+3;
  42. *s++ = '\n';
  43. writeall(1, toybuf, s-toybuf);
  44. }
  45. void unicode_main(void)
  46. {
  47. int from, to, n;
  48. char next, **args, *s;
  49. unsigned wc;
  50. // Loop through args, handling range, hex code, or character(s)
  51. for (args = toys.optargs; *args; args++) {
  52. if (sscanf(*args, "%x-%x%c", &from, &to, &next) == 2)
  53. while (from <= to) codepoint(from++);
  54. else if (sscanf(*args, "%x%c", &from, &next) == 1) codepoint(from);
  55. else for (s = *args; (n = utf8towc(&wc, s, 4)) > 0; s += n) codepoint(wc);
  56. }
  57. }
  58. void ascii_main(void)
  59. {
  60. char *s = toybuf;
  61. int i, x, y;
  62. for (y = -1; y<16; y++) for (x = 0; x<8; x++) {
  63. if (y>=0) {
  64. i = (x<<4)+y;
  65. s += sprintf(s, "% *d %02X ", 3+(x>5), i, i);
  66. if (i<32 || i==127) s += sprintf(s, "%.3s", (i<32) ? low+3*i : "DEL");
  67. else *s++ = i;
  68. } else s += sprintf(s, "Dec Hex%*c", 1+2*(x<2)+(x>4), ' ');
  69. *s++ = (x>6) ? '\n' : ' ';
  70. }
  71. writeall(1, toybuf, s-toybuf);
  72. }