Tag.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #ifndef TAG_H__
  2. #define TAG_H__
  3. /*
  4. * Copyright (c) 2013-2017, The PurpleI2P Project
  5. *
  6. * This file is part of Purple i2pd project and licensed under BSD3
  7. *
  8. * See full license text in LICENSE file at top of project tree
  9. */
  10. #include <boost/static_assert.hpp>
  11. #include <string.h>
  12. #include <openssl/rand.h>
  13. #include "Base.h"
  14. namespace i2p {
  15. namespace data {
  16. template<size_t sz>
  17. class Tag
  18. {
  19. BOOST_STATIC_ASSERT_MSG(sz % 8 == 0, "Tag size must be multiple of 8 bytes");
  20. public:
  21. Tag () = default;
  22. Tag (const uint8_t * buf) { memcpy (m_Buf, buf, sz); }
  23. bool operator== (const Tag& other) const { return !memcmp (m_Buf, other.m_Buf, sz); }
  24. bool operator!= (const Tag& other) const { return !(*this == other); }
  25. bool operator< (const Tag& other) const { return memcmp (m_Buf, other.m_Buf, sz) < 0; }
  26. uint8_t * operator()() { return m_Buf; }
  27. const uint8_t * operator()() const { return m_Buf; }
  28. operator uint8_t * () { return m_Buf; }
  29. operator const uint8_t * () const { return m_Buf; }
  30. const uint8_t * data() const { return m_Buf; }
  31. const uint64_t * GetLL () const { return ll; }
  32. bool IsZero () const
  33. {
  34. for (size_t i = 0; i < sz/8; ++i)
  35. if (ll[i]) return false;
  36. return true;
  37. }
  38. void Fill(uint8_t c)
  39. {
  40. memset(m_Buf, c, sz);
  41. }
  42. void Randomize()
  43. {
  44. RAND_bytes(m_Buf, sz);
  45. }
  46. std::string ToBase64 () const
  47. {
  48. char str[sz*2];
  49. size_t l = i2p::data::ByteStreamToBase64 (m_Buf, sz, str, sz*2);
  50. return std::string (str, str + l);
  51. }
  52. std::string ToBase32 () const
  53. {
  54. char str[sz*2];
  55. size_t l = i2p::data::ByteStreamToBase32 (m_Buf, sz, str, sz*2);
  56. return std::string (str, str + l);
  57. }
  58. size_t FromBase32 (const std::string& s)
  59. {
  60. return i2p::data::Base32ToByteStream (s.c_str (), s.length (), m_Buf, sz);
  61. }
  62. size_t FromBase64 (const std::string& s)
  63. {
  64. return i2p::data::Base64ToByteStream (s.c_str (), s.length (), m_Buf, sz);
  65. }
  66. private:
  67. union // 8 bytes aligned
  68. {
  69. uint8_t m_Buf[sz];
  70. uint64_t ll[sz/8];
  71. };
  72. };
  73. } // data
  74. } // i2p
  75. #endif /* TAG_H__ */