i2pbase64.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include <unistd.h>
  2. #include <fcntl.h>
  3. #include <iostream>
  4. #include <fstream>
  5. #include <functional>
  6. #include <cassert>
  7. #include "Base.h"
  8. const size_t BUFFSZ = 1024;
  9. static int printHelp(const char * exe, int exitcode)
  10. {
  11. std::cout << "usage: " << exe << " [-d] [filename]" << std::endl;
  12. return exitcode;
  13. }
  14. template <typename InCh, typename OutCh, size_t isz, size_t osz>
  15. static int operate(std::function<std::size_t(const InCh *, size_t, OutCh *, size_t)> f, int infile, int outfile)
  16. {
  17. InCh inbuf[isz];
  18. OutCh outbuf[osz];
  19. ssize_t sz;
  20. size_t outsz;
  21. while((sz = read(infile, inbuf, sizeof(inbuf))) > 0)
  22. {
  23. outsz = f(inbuf, sz, outbuf, sizeof(outbuf));
  24. if(outsz && outsz <= sizeof(outbuf))
  25. {
  26. write(outfile, outbuf, outsz);
  27. }
  28. else
  29. {
  30. return -1;
  31. }
  32. }
  33. return errno;
  34. }
  35. int main(int argc, char * argv[])
  36. {
  37. int opt;
  38. bool decode = false;
  39. int infile = 0;
  40. while((opt = getopt(argc, argv, "dh")) != -1)
  41. {
  42. switch(opt)
  43. {
  44. case 'h':
  45. return printHelp(argv[0], 0);
  46. case 'd':
  47. decode = true;
  48. break;
  49. default:
  50. continue;
  51. }
  52. }
  53. if (argc - optind > 1)
  54. {
  55. return printHelp(argv[0], -1);
  56. }
  57. if (optind < argc)
  58. {
  59. infile = open(argv[optind], O_RDONLY);
  60. if(infile == -1) {
  61. perror(argv[optind]);
  62. return -1;
  63. }
  64. }
  65. int retcode = 0;
  66. if(decode)
  67. {
  68. retcode = operate<char, uint8_t, BUFFSZ*4, BUFFSZ*3>(i2p::data::Base64ToByteStream, infile, 1);
  69. }
  70. else
  71. {
  72. retcode = operate<uint8_t, char, BUFFSZ*3, BUFFSZ*4>(&i2p::data::ByteStreamToBase64, infile, 1);
  73. }
  74. close(infile);
  75. return retcode;
  76. }