binary.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #ifndef BASE64_H_62B23520_7C8E_11DE_8A39_0800200C9A66
  2. #define BASE64_H_62B23520_7C8E_11DE_8A39_0800200C9A66
  3. #if defined(_MSC_VER) || \
  4. (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
  5. (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
  6. #pragma once
  7. #endif
  8. #include <string>
  9. #include <vector>
  10. #include "yaml-cpp/dll.h"
  11. namespace YAML {
  12. YAML_CPP_API std::string EncodeBase64(const unsigned char *data,
  13. std::size_t size);
  14. YAML_CPP_API std::vector<unsigned char> DecodeBase64(const std::string &input);
  15. class YAML_CPP_API Binary {
  16. public:
  17. Binary() : m_unownedData(0), m_unownedSize(0) {}
  18. Binary(const unsigned char *data_, std::size_t size_)
  19. : m_unownedData(data_), m_unownedSize(size_) {}
  20. bool owned() const { return !m_unownedData; }
  21. std::size_t size() const { return owned() ? m_data.size() : m_unownedSize; }
  22. const unsigned char *data() const {
  23. return owned() ? &m_data[0] : m_unownedData;
  24. }
  25. void swap(std::vector<unsigned char> &rhs) {
  26. if (m_unownedData) {
  27. m_data.swap(rhs);
  28. rhs.clear();
  29. rhs.resize(m_unownedSize);
  30. std::copy(m_unownedData, m_unownedData + m_unownedSize, rhs.begin());
  31. m_unownedData = 0;
  32. m_unownedSize = 0;
  33. } else {
  34. m_data.swap(rhs);
  35. }
  36. }
  37. bool operator==(const Binary &rhs) const {
  38. const std::size_t s = size();
  39. if (s != rhs.size())
  40. return false;
  41. const unsigned char *d1 = data();
  42. const unsigned char *d2 = rhs.data();
  43. for (std::size_t i = 0; i < s; i++) {
  44. if (*d1++ != *d2++)
  45. return false;
  46. }
  47. return true;
  48. }
  49. bool operator!=(const Binary &rhs) const { return !(*this == rhs); }
  50. private:
  51. std::vector<unsigned char> m_data;
  52. const unsigned char *m_unownedData;
  53. std::size_t m_unownedSize;
  54. };
  55. }
  56. #endif // BASE64_H_62B23520_7C8E_11DE_8A39_0800200C9A66