binary.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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(const unsigned char *data_, std::size_t size_)
  18. : m_data{}, m_unownedData(data_), m_unownedSize(size_) {}
  19. Binary() : Binary(nullptr, 0) {}
  20. Binary(const Binary &) = default;
  21. Binary(Binary &&) = default;
  22. Binary &operator=(const Binary &) = default;
  23. Binary &operator=(Binary &&) = default;
  24. bool owned() const { return !m_unownedData; }
  25. std::size_t size() const { return owned() ? m_data.size() : m_unownedSize; }
  26. const unsigned char *data() const {
  27. return owned() ? &m_data[0] : m_unownedData;
  28. }
  29. void swap(std::vector<unsigned char> &rhs) {
  30. if (m_unownedData) {
  31. m_data.swap(rhs);
  32. rhs.clear();
  33. rhs.resize(m_unownedSize);
  34. std::copy(m_unownedData, m_unownedData + m_unownedSize, rhs.begin());
  35. m_unownedData = nullptr;
  36. m_unownedSize = 0;
  37. } else {
  38. m_data.swap(rhs);
  39. }
  40. }
  41. bool operator==(const Binary &rhs) const {
  42. const std::size_t s = size();
  43. if (s != rhs.size())
  44. return false;
  45. const unsigned char *d1 = data();
  46. const unsigned char *d2 = rhs.data();
  47. for (std::size_t i = 0; i < s; i++) {
  48. if (*d1++ != *d2++)
  49. return false;
  50. }
  51. return true;
  52. }
  53. bool operator!=(const Binary &rhs) const { return !(*this == rhs); }
  54. private:
  55. std::vector<unsigned char> m_data;
  56. const unsigned char *m_unownedData;
  57. std::size_t m_unownedSize;
  58. };
  59. } // namespace YAML
  60. #endif // BASE64_H_62B23520_7C8E_11DE_8A39_0800200C9A66