Serializer.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. //
  2. // Copyright @ 2014 Hangzhou Topzen Ltd.
  3. // Author: Tang (tang@hztopzen.com) @ 2014-12
  4. //
  5. #ifndef __SERIALIZER_H
  6. #define __SERIALIZER_H
  7. #include <cassert>
  8. #include "BaseTypes.h"
  9. #include "BaseHeaders.h"
  10. #include "BaseCalls.h"
  11. namespace tzc {
  12. class Serializer {
  13. public:
  14. Serializer()
  15. {
  16. }
  17. virtual ~Serializer()
  18. {
  19. }
  20. virtual TZ_BOOL ToByteArray(TZ_BYTE *, TZ_Uint32 &) = 0;
  21. virtual TZ_BOOL FromByteArray(const TZ_BYTE *, TZ_Uint32 ) = 0;
  22. virtual TZ_Uint32 GetPackedSize(void) const = 0;
  23. protected:
  24. // from memory to property
  25. template<class T>
  26. TZ_Uint32 MemToProperty(const TZ_BYTE *, T &);
  27. TZ_Uint32 MemToProperty(const TZ_BYTE *, TZ_BYTE *, TZ_Uint32);
  28. TZ_Uint32 MemToProperty(const TZ_BYTE *, TZ_CHAR *, TZ_Uint32);
  29. // from property to memory
  30. template<class T>
  31. TZ_Uint32 PropertyToMem(TZ_BYTE *, const T &);
  32. TZ_Uint32 PropertyToMem(TZ_BYTE *, const TZ_BYTE *, TZ_Uint32);
  33. TZ_Uint32 PropertyToMem(TZ_BYTE *, const TZ_CHAR *, TZ_Uint32);
  34. };
  35. //
  36. // inlines
  37. //
  38. inline TZ_Uint32 Serializer::MemToProperty(const TZ_BYTE * pMem,
  39. TZ_BYTE * property, TZ_Uint32 len)
  40. {
  41. assert(pMem != NULL && property != NULL && len != 0);
  42. memcpy(property, pMem, len);
  43. return len;
  44. }
  45. inline TZ_Uint32 Serializer::MemToProperty(const TZ_BYTE * pMem,
  46. TZ_CHAR * property, TZ_Uint32 len)
  47. {
  48. assert(pMem != NULL && property != NULL && len != 0);
  49. STRNCPY(property, reinterpret_cast<const TZ_CHAR *>(pMem), len);
  50. return len;
  51. }
  52. inline TZ_Uint32 Serializer::PropertyToMem(TZ_BYTE * pMem,
  53. const TZ_BYTE * property, const TZ_Uint32 len)
  54. {
  55. assert(pMem != NULL && property != NULL && len != 0);
  56. memcpy(pMem, property, len);
  57. return len;
  58. }
  59. inline TZ_Uint32 Serializer::PropertyToMem(TZ_BYTE * pMem,
  60. const TZ_CHAR * property, const TZ_Uint32 len)
  61. {
  62. assert(pMem != NULL && property != NULL && len != 0);
  63. STRNCPY(reinterpret_cast<TZ_CHAR *>(pMem), property, len);
  64. return len;
  65. }
  66. template<class T>
  67. TZ_Uint32 Serializer::MemToProperty(const TZ_BYTE * pMem, T & property)
  68. {
  69. assert(pMem != NULL);
  70. property = *(reinterpret_cast<const T *>(pMem));
  71. return sizeof(property);
  72. }
  73. template<class T>
  74. TZ_Uint32 Serializer::PropertyToMem(TZ_BYTE * pMem, const T & property)
  75. {
  76. assert(pMem != NULL);
  77. *(reinterpret_cast<T *>(pMem)) = property;
  78. return sizeof(property);
  79. }
  80. }; // namespace tzc
  81. #endif