base64_encode.c 1008 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #include "misc.h"
  2. void base64_encode_bs(BinarySink *bs, ptrlen input, int cpl)
  3. {
  4. BinarySource src[1];
  5. BinarySource_BARE_INIT_PL(src, input);
  6. int linelen = 0;
  7. while (get_avail(src)) {
  8. size_t n = get_avail(src) < 3 ? get_avail(src) : 3;
  9. ptrlen binatom = get_data(src, n);
  10. char b64atom[4];
  11. base64_encode_atom(binatom.ptr, binatom.len, b64atom);
  12. for (size_t i = 0; i < 4; i++) {
  13. if (cpl > 0 && linelen >= cpl) {
  14. linelen = 0;
  15. put_byte(bs, '\n');
  16. }
  17. put_byte(bs, b64atom[i]);
  18. linelen++;
  19. }
  20. }
  21. if (cpl > 0)
  22. put_byte(bs, '\n');
  23. }
  24. void base64_encode_fp(FILE *fp, ptrlen input, int cpl)
  25. {
  26. stdio_sink ss;
  27. stdio_sink_init(&ss, fp);
  28. base64_encode_bs(BinarySink_UPCAST(&ss), input, cpl);
  29. }
  30. strbuf *base64_encode_sb(ptrlen input, int cpl)
  31. {
  32. strbuf *sb = strbuf_new_nm();
  33. base64_encode_bs(BinarySink_UPCAST(sb), input, cpl);
  34. return sb;
  35. }