percent_decode.c 891 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /*
  2. * Decode %-encoding in URL style.
  3. */
  4. #include <ctype.h>
  5. #include "misc.h"
  6. void percent_decode_bs(BinarySink *bs, ptrlen data)
  7. {
  8. for (const char *p = data.ptr, *e = ptrlen_end(data); p < e; p++) {
  9. char c = *p;
  10. if (c == '%' && e-p >= 3 &&
  11. isxdigit((unsigned char)p[1]) &&
  12. isxdigit((unsigned char)p[2])) {
  13. char hex[3];
  14. hex[0] = p[1];
  15. hex[1] = p[2];
  16. hex[2] = '\0';
  17. put_byte(bs, strtoul(hex, NULL, 16));
  18. p += 2;
  19. } else {
  20. put_byte(bs, c);
  21. }
  22. }
  23. }
  24. void percent_decode_fp(FILE *fp, ptrlen data)
  25. {
  26. stdio_sink ss;
  27. stdio_sink_init(&ss, fp);
  28. percent_decode_bs(BinarySink_UPCAST(&ss), data);
  29. }
  30. strbuf *percent_decode_sb(ptrlen data)
  31. {
  32. strbuf *sb = strbuf_new();
  33. percent_decode_bs(BinarySink_UPCAST(sb), data);
  34. return sb;
  35. }