printable_string.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Unicode support routines.
  4. *
  5. * Copyright (C) 2010 Denys Vlasenko
  6. *
  7. * Licensed under GPLv2, see file LICENSE in this source tree.
  8. */
  9. #include "libbb.h"
  10. #include "unicode.h"
  11. const char* FAST_FUNC printable_string2(uni_stat_t *stats, const char *str)
  12. {
  13. char *dst;
  14. const char *s;
  15. s = str;
  16. while (1) {
  17. unsigned char c = *s;
  18. if (c == '\0') {
  19. /* 99+% of inputs do not need conversion */
  20. if (stats) {
  21. stats->byte_count = (s - str);
  22. stats->unicode_count = (s - str);
  23. stats->unicode_width = (s - str);
  24. }
  25. return str;
  26. }
  27. if (c < ' ')
  28. break;
  29. if (c >= 0x7f)
  30. break;
  31. s++;
  32. }
  33. #if ENABLE_UNICODE_SUPPORT
  34. dst = unicode_conv_to_printable(stats, str);
  35. #else
  36. {
  37. char *d = dst = xstrdup(str);
  38. while (1) {
  39. unsigned char c = *d;
  40. if (c == '\0')
  41. break;
  42. if (c < ' ' || c >= 0x7f)
  43. *d = '?';
  44. d++;
  45. }
  46. if (stats) {
  47. stats->byte_count = (d - dst);
  48. stats->unicode_count = (d - dst);
  49. stats->unicode_width = (d - dst);
  50. }
  51. }
  52. #endif
  53. return auto_string(dst);
  54. }
  55. const char* FAST_FUNC printable_string(const char *str)
  56. {
  57. return printable_string2(NULL, str);
  58. }