base64.cc 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // compile with:
  2. // g++ -Wall -Os base64.cc -I ../src/utils/ ../src/utils/Base64.cc -lz -o encode-gz-base64
  3. // g++ -Wall -Os base64.cc -I ../src/utils/ ../src/utils/Base64.cc -lz -o decode-gz-base64
  4. #include "Base64.hh"
  5. #include <vector>
  6. #include <iostream>
  7. #include <cstdlib>
  8. #include <cstdio>
  9. #include <cstring>
  10. #include <sys/stat.h>
  11. #include <zlib.h>
  12. using namespace std;
  13. string encode(const void* data, unsigned len)
  14. {
  15. uLongf dstLen = len + len / 1000 + 12 + 1; // worst-case
  16. vector<unsigned char> buf(dstLen);
  17. if (compress2(buf.data(), &dstLen,
  18. reinterpret_cast<const Bytef*>(data), len, 9)
  19. != Z_OK) {
  20. cerr << "Error while compressing blob." << endl;
  21. exit(1);
  22. }
  23. return Base64::encode(buf.data(), dstLen);
  24. }
  25. string decode(const char* data, unsigned len)
  26. {
  27. static const unsigned MAX_SIZE = 1024 * 1024; // 1MB
  28. string tmp = Base64::decode(string(data, len));
  29. vector<char> buf(MAX_SIZE);
  30. uLongf dstLen = MAX_SIZE;
  31. if (uncompress(reinterpret_cast<Bytef*>(buf.data()), &dstLen,
  32. reinterpret_cast<const Bytef*>(tmp.data()), uLong(tmp.size()))
  33. != Z_OK) {
  34. cerr << "Error while decompressing blob." << endl;
  35. exit(1);
  36. }
  37. return string(buf.data(), dstLen);
  38. }
  39. int main(int argc, char** argv)
  40. {
  41. if (argc != 3) {
  42. cerr << "Usage: " << argv[0] << " <input> <output>\n";
  43. exit(1);
  44. }
  45. FILE* inf = fopen(argv[1], "rb");
  46. if (!inf) {
  47. cerr << "Error while opening " << argv[1] << endl;
  48. exit(1);
  49. }
  50. struct stat st;
  51. fstat(fileno(inf), &st);
  52. size_t size = st.st_size;
  53. vector<char> inBuf(size);
  54. if (fread(inBuf.data(), size, 1, inf) != 1) {
  55. cerr << "Error whle reading " << argv[1] << endl;
  56. exit(1);
  57. }
  58. string result;
  59. if (strstr(argv[0], "encode-gz-base64")) {
  60. result = encode(inBuf.data(), inBuf.size());
  61. } else if (strstr(argv[0], "decode-gz-base64")) {
  62. result = decode(inBuf.data(), inBuf.size());
  63. } else {
  64. cerr << "This executable should be named 'encode-gz-base64' or "
  65. "'decode-gz-base64'." << endl;
  66. exit(1);
  67. }
  68. FILE* outf = fopen(argv[2], "wb+");
  69. if (!outf) {
  70. cerr << "Error while opening " << argv[2] << endl;
  71. exit(1);
  72. }
  73. if (fwrite(result.data(), result.size(), 1, outf) != 1) {
  74. cerr << "Error whle writing " << argv[2] << endl;
  75. exit(1);
  76. }
  77. }