base16.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include<__vic/base16.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_lower(const bytes &s)
  13. {
  14. std::string res;
  15. res.reserve(s.length() * 2);
  16. __vic::base16::encode_lower(bytes_reader(s), __vic::string_writer(res));
  17. return res;
  18. }
  19. std::string encode_upper(const bytes &s)
  20. {
  21. std::string res;
  22. res.reserve(s.length() * 2);
  23. __vic::base16::encode_upper(bytes_reader(s), __vic::string_writer(res));
  24. return res;
  25. }
  26. bytes decode(const std::string &s)
  27. {
  28. bytes res;
  29. res.reserve(s.length() / 2);
  30. __vic::base16::decode(__vic::string_reader(s), bytes_writer(res));
  31. return res;
  32. }
  33. void run()
  34. {
  35. assert(encode_lower("\x12\x34\xAB") == "1234ab");
  36. assert(encode_upper("\x12\x34\xAB") == "1234AB");
  37. assert(decode("1234ab") == "\x12\x34\xAB");
  38. assert(decode("1234AB") == decode("1234ab"));
  39. try
  40. {
  41. decode("12ZX"); // non-HEX digit
  42. assert(false);
  43. }
  44. catch(__vic::base16::bad_format) {} // OK
  45. try
  46. {
  47. decode("12A"); // odd length
  48. assert(false);
  49. }
  50. catch(__vic::base16::bad_format) {} // OK
  51. }
  52. } // namespace
  53. int main()
  54. {
  55. try
  56. {
  57. tests::run();
  58. return 0;
  59. }
  60. catch(const std::exception &ex)
  61. {
  62. std::cerr << ex.what() << '\n';
  63. }
  64. return 1;
  65. }