support_quote_blob.c 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /* Quote a blob so that it can be used in C literals.
  2. Copyright (C) 2018-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include <support/support.h>
  16. #include <support/xmemstream.h>
  17. char *
  18. support_quote_blob (const void *blob, size_t length)
  19. {
  20. struct xmemstream out;
  21. xopen_memstream (&out);
  22. const unsigned char *p = blob;
  23. for (size_t i = 0; i < length; ++i)
  24. {
  25. unsigned char ch = p[i];
  26. /* Use C backslash escapes for those control characters for
  27. which they are defined. */
  28. switch (ch)
  29. {
  30. case '\a':
  31. putc_unlocked ('\\', out.out);
  32. putc_unlocked ('a', out.out);
  33. break;
  34. case '\b':
  35. putc_unlocked ('\\', out.out);
  36. putc_unlocked ('b', out.out);
  37. break;
  38. case '\f':
  39. putc_unlocked ('\\', out.out);
  40. putc_unlocked ('f', out.out);
  41. break;
  42. case '\n':
  43. putc_unlocked ('\\', out.out);
  44. putc_unlocked ('n', out.out);
  45. break;
  46. case '\r':
  47. putc_unlocked ('\\', out.out);
  48. putc_unlocked ('r', out.out);
  49. break;
  50. case '\t':
  51. putc_unlocked ('\\', out.out);
  52. putc_unlocked ('t', out.out);
  53. break;
  54. case '\v':
  55. putc_unlocked ('\\', out.out);
  56. putc_unlocked ('v', out.out);
  57. break;
  58. case '\\':
  59. case '\'':
  60. case '\"':
  61. putc_unlocked ('\\', out.out);
  62. putc_unlocked (ch, out.out);
  63. break;
  64. default:
  65. if (ch < ' ' || ch > '~')
  66. /* Use octal sequences because they are fixed width,
  67. unlike hexadecimal sequences. */
  68. fprintf (out.out, "\\%03o", ch);
  69. else
  70. putc_unlocked (ch, out.out);
  71. }
  72. }
  73. xfclose_memstream (&out);
  74. return out.buffer;
  75. }