StringEscape.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. #include <stddef.h>
  2. //FIXME out gets silently truncated if outsize is too small
  3. size_t escape(char* in, char* out, size_t outsize) {
  4. size_t l = 0;
  5. while(*in && l + 3 < outsize) {
  6. switch(*in) {
  7. case '\n':
  8. *out++ = '\\';
  9. l++;
  10. *out = 'n';
  11. break;
  12. case '\r':
  13. *out++ = '\\';
  14. l++;
  15. *out = 'r';
  16. break;
  17. case '\t':
  18. *out++ = '\\';
  19. l++;
  20. *out = 't';
  21. break;
  22. case '\\':
  23. *out++ = '\\';
  24. l++;
  25. *out = '\\';
  26. break;
  27. case '"':
  28. *out++ = '\\';
  29. l++;
  30. *out = '"';
  31. break;
  32. case '\v':
  33. *out++ = '\\';
  34. l++;
  35. *out = '\v';
  36. break;
  37. case '\?':
  38. *out++ = '\\';
  39. l++;
  40. *out = '\?';
  41. break;
  42. case '\f':
  43. *out++ = '\\';
  44. l++;
  45. *out = '\f';
  46. break;
  47. default:
  48. *out = *in;
  49. }
  50. in++;
  51. out++;
  52. l++;
  53. }
  54. *out = 0;
  55. return l;
  56. }
  57. #include <assert.h>
  58. #include <stdlib.h>
  59. size_t unescape(char* in, char *out, size_t outsize) {
  60. size_t l = 0;
  61. while(*in && l + 2 < outsize) {
  62. switch (*in) {
  63. case '\\':
  64. ++in;
  65. assert(*in);
  66. switch(*in) {
  67. case 'n':
  68. *out='\n';
  69. break;
  70. case 'r':
  71. *out='\r';
  72. break;
  73. case 't':
  74. *out='\t';
  75. break;
  76. case '\\':
  77. *out='\\';
  78. break;
  79. case '"':
  80. *out='"';
  81. break;
  82. case 'v':
  83. *out='\v';
  84. break;
  85. case '\?':
  86. *out = '\?';
  87. break;
  88. case 'f':
  89. *out = '\f';
  90. break;
  91. case '\'':
  92. *out = '\'';
  93. break;
  94. case 'b':
  95. *out = '\b';
  96. break;
  97. // FIXME add handling of hex and octal
  98. default:
  99. abort();
  100. }
  101. break;
  102. default:
  103. *out=*in;
  104. }
  105. in++;
  106. out++;
  107. l++;
  108. }
  109. *out = 0;
  110. return l;
  111. }