1
0

Escape.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #ifndef Escape_H
  16. #define Escape_H
  17. #include "memory/Allocator.h"
  18. #include "util/Assert.h"
  19. static inline char* Escape_getEscaped(uint8_t* buff, int length, struct Allocator* alloc)
  20. {
  21. const char* hexSymbols = "0123456789abcdef";
  22. int finalSize = 1;
  23. for (int i = 0; i < length; i++) {
  24. if (buff[i] > 31 && buff[i] < 127) {
  25. finalSize++;
  26. } else {
  27. finalSize += 4;
  28. }
  29. }
  30. char* output = Allocator_malloc(alloc, finalSize);
  31. int j = 0;
  32. for (int i = 0; i < length; i++) {
  33. if (buff[i] > 31 && buff[i] < 127) {
  34. output[j++] = buff[i];
  35. } else {
  36. output[j++] = '\\';
  37. output[j++] = 'x';
  38. output[j++] = hexSymbols[buff[i] >> 4];
  39. output[j++] = hexSymbols[buff[i] & 0x0f];
  40. }
  41. }
  42. output[j++] = '\0';
  43. Assert_true(j == finalSize);
  44. return output;
  45. }
  46. #endif