base64.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include<__vic/base64.h>
  2. #include<__vic/readers/string.h>
  3. #include<__vic/writers/string.h>
  4. #include<iostream>
  5. #include<exception>
  6. #include<cassert>
  7. #include<string>
  8. namespace tests {
  9. typedef std::string bytes;
  10. typedef __vic::string_reader bytes_reader;
  11. typedef __vic::string_writer bytes_writer;
  12. std::string encode(const bytes &s)
  13. {
  14. std::string res;
  15. size_t enc_len = __vic::base64::encoded_length(s.length());
  16. res.reserve(enc_len);
  17. __vic::base64::encode(bytes_reader(s), __vic::string_writer(res));
  18. assert(res.length() == enc_len);
  19. return res;
  20. }
  21. bytes decode(const std::string &s)
  22. {
  23. bytes res;
  24. size_t max_dec_len = __vic::base64::max_decoded_length(s.length());
  25. res.reserve(max_dec_len);
  26. __vic::base64::decode(__vic::string_reader(s), bytes_writer(res));
  27. assert(res.length() <= max_dec_len);
  28. return res;
  29. }
  30. void run()
  31. {
  32. assert(encode("Hello") == "SGVsbG8=");
  33. assert(decode("SGVsbG8=") == "Hello");
  34. try
  35. {
  36. decode("!SGVsbG8="); // non-BASE64 digit
  37. assert(false);
  38. }
  39. catch(__vic::base64::bad_format) {} // OK
  40. try
  41. {
  42. decode("SGVsbG8"); // bad length
  43. assert(false);
  44. }
  45. catch(__vic::base64::bad_format) {} // OK
  46. }
  47. } // namespace
  48. int main()
  49. {
  50. try
  51. {
  52. tests::run();
  53. return 0;
  54. }
  55. catch(const std::exception &ex)
  56. {
  57. std::cerr << ex.what() << '\n';
  58. }
  59. return 1;
  60. }