percent_encode.c 920 B

1234567891011121314151617181920212223242526272829303132333435
  1. /*
  2. * %-encoding in URL style.
  3. *
  4. * Defaults to escaping % itself (necessary for decoding to even
  5. * work), and any C0 escape character. Further bad characters can be
  6. * provided in 'badchars'.
  7. */
  8. #include "misc.h"
  9. void percent_encode_bs(BinarySink *bs, ptrlen data, const char *badchars)
  10. {
  11. for (const char *p = data.ptr, *e = ptrlen_end(data); p < e; p++) {
  12. char c = *p;
  13. if (c == '%' || c < ' ' || (badchars && strchr(badchars, c)))
  14. put_fmt(bs, "%%%02X", (unsigned char)c);
  15. else
  16. put_byte(bs, c);
  17. }
  18. }
  19. void percent_encode_fp(FILE *fp, ptrlen data, const char *badchars)
  20. {
  21. stdio_sink ss;
  22. stdio_sink_init(&ss, fp);
  23. percent_encode_bs(BinarySink_UPCAST(&ss), data, badchars);
  24. }
  25. strbuf *percent_encode_sb(ptrlen data, const char *badchars)
  26. {
  27. strbuf *sb = strbuf_new();
  28. percent_encode_bs(BinarySink_UPCAST(sb), data, badchars);
  29. return sb;
  30. }