protobufobject_p.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. /*
  2. * MIT License
  3. *
  4. * Copyright (c) 2019 Alexey Edelev <semlanik@gmail.com>
  5. *
  6. * This file is part of qtprotobuf project https://git.semlanik.org/semlanik/qtprotobuf
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy of this
  9. * software and associated documentation files (the "Software"), to deal in the Software
  10. * without restriction, including without limitation the rights to use, copy, modify,
  11. * merge, publish, distribute, sublicense, and/or sell copies of the Software, and
  12. * to permit persons to whom the Software is furnished to do so, subject to the following
  13. * conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all copies
  16. * or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  19. * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  20. * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  21. * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  23. * DEALINGS IN THE SOFTWARE.
  24. */
  25. #pragma once
  26. #include <QObject>
  27. #include <QMetaObject>
  28. #include <QMetaProperty>
  29. #include <QBitArray>
  30. #include <unordered_map>
  31. #include <memory>
  32. #include <type_traits>
  33. #include <typeinfo>
  34. #include <functional>
  35. #include <qtprotobuftypes.h>
  36. #include <qtprotobuflogging.h>
  37. #define ASSERT_FIELD_NUMBER(X) Q_ASSERT_X(X < 128 && X > 0 && X != NotUsedFieldIndex, T::staticMetaObject.className(), "fieldIndex is out of range")
  38. namespace qtprotobuf {
  39. enum WireTypes {
  40. UnknownWireType = -1,
  41. Varint = 0,
  42. Fixed64 = 1,
  43. LengthDelimited = 2,
  44. Fixed32 = 5
  45. };
  46. constexpr int NotUsedFieldIndex = -1;
  47. class ProtobufObjectPrivate : public QObject
  48. {
  49. protected:
  50. using ListSerializer = std::function<QByteArray(const ProtobufObjectPrivate *, const QVariant &, int &)>;
  51. using ListDeserializer = std::function<void(ProtobufObjectPrivate *, QByteArray::const_iterator &, QVariant &)>;
  52. struct SerializationHandlers {
  53. ListSerializer serializer;
  54. ListDeserializer deserializer;
  55. };
  56. using SerializerRegistry = std::unordered_map<int/*metatypeid*/, SerializationHandlers>;
  57. static SerializerRegistry serializers;
  58. public:
  59. explicit ProtobufObjectPrivate(QObject *parent = nullptr) : QObject(parent) {}
  60. virtual QByteArray serializePrivate() const = 0;
  61. virtual void deserializePrivate(const QByteArray &data) = 0;
  62. inline static unsigned char encodeHeaderByte(int fieldIndex, WireTypes wireType);
  63. inline static bool decodeHeaderByte(unsigned char typeByte, int &fieldIndex, WireTypes &wireType);
  64. QByteArray serializeValue(const QVariant &propertyValue, int fieldIndex, const QLatin1Literal &typeName) const;
  65. QByteArray serializeUserType(const QVariant &propertyValue, int &fieldIndex) const;
  66. void deserializeProperty(WireTypes wireType, const QMetaProperty &metaProperty, QByteArray::const_iterator &it);
  67. void deserializeUserType(const QMetaProperty &metaType, QByteArray::const_iterator &it, QVariant &newValue);
  68. //###########################################################################
  69. // Serialization helpers
  70. //###########################################################################
  71. QByteArray serializeLengthDelimited(const QByteArray &data) const {
  72. qProtoDebug() << __func__ << "data.size" << data.size() << "data" << data.toHex();
  73. //Varint serialize field size and apply result as starting point
  74. QByteArray result = serializeVarintZero(static_cast<unsigned int>(data.size()));
  75. result.append(data);
  76. return result;
  77. }
  78. template<typename V,
  79. typename std::enable_if_t<std::is_integral<V>::value, int> = 0>
  80. QByteArray serializeListType(const QList<V> &listValue, int &outFieldIndex) const {
  81. qProtoDebug() << __func__ << "listValue.count" << listValue.count() << "outFiledIndex" << outFieldIndex;
  82. if (listValue.count() <= 0) {
  83. outFieldIndex = NotUsedFieldIndex;
  84. return QByteArray();
  85. }
  86. QByteArray serializedList;
  87. for (auto &value : listValue) {
  88. serializedList.append(serializeVarintZigZag(value));
  89. }
  90. //If internal field type is not LengthDelimited, exact amount of fields to be specified
  91. serializedList.prepend(serializeVarintZero(static_cast<unsigned int>(serializedList.size())));
  92. return serializedList;
  93. }
  94. template<typename V,
  95. typename std::enable_if_t<std::is_floating_point<V>::value, int> = 0>
  96. QByteArray serializeListType(const QList<V> &listValue, int &outFieldIndex) const {
  97. qProtoDebug() << __func__ << "listValue.count" << listValue.count() << "outFiledIndex" << outFieldIndex;
  98. if (listValue.count() <= 0) {
  99. outFieldIndex = NotUsedFieldIndex;
  100. return QByteArray();
  101. }
  102. QByteArray serializedList;
  103. for (auto &value : listValue) {
  104. serializedList.append(serializeFixed(value));
  105. }
  106. //If internal field type is not LengthDelimited, exact amount of fields to be specified
  107. serializedList.prepend(serializeVarintZero(static_cast<unsigned int>(serializedList.size())));
  108. return serializedList;
  109. }
  110. template<typename V,
  111. typename std::enable_if_t<std::is_same<V, QString>::value
  112. || std::is_same<V, QByteArray>::value, int> = 0>
  113. QByteArray serializeListType(const QList<V> &listValue, int &outFieldIndex) const {
  114. qProtoDebug() << __func__ << "listValue.count" << listValue.count() << "outFiledIndex" << outFieldIndex;
  115. if (listValue.count() <= 0) {
  116. outFieldIndex = NotUsedFieldIndex;
  117. return QByteArray();
  118. }
  119. QByteArray serializedList;
  120. for (auto &value : listValue) {
  121. serializedList.append(serializeValue(value, outFieldIndex, QLatin1Literal()));
  122. }
  123. outFieldIndex = NotUsedFieldIndex;
  124. return serializedList;
  125. }
  126. template<typename V,
  127. typename std::enable_if_t<std::is_base_of<ProtobufObjectPrivate, V>::value, int> = 0>
  128. QByteArray serializeListType(const QList<V> &listValue, int &outFieldIndex) const {
  129. qProtoDebug() << __func__ << "listValue.count" << listValue.count() << "outFiledIndex" << outFieldIndex;
  130. if (listValue.count() <= 0) {
  131. outFieldIndex = NotUsedFieldIndex;
  132. return QByteArray();
  133. }
  134. QByteArray serializedList;
  135. for (auto &value : listValue) {
  136. QByteArray serializedValue = serializeLengthDelimited(value.serialize());
  137. serializedValue.prepend(encodeHeaderByte(outFieldIndex, LengthDelimited));
  138. serializedList.append(serializedValue);
  139. }
  140. outFieldIndex = NotUsedFieldIndex;
  141. return serializedList;
  142. }
  143. template <typename V,
  144. typename std::enable_if_t<std::is_floating_point<V>::value
  145. || std::is_same<V, unsigned int>::value
  146. || std::is_same<V, qulonglong>::value
  147. || std::is_same<V, int>::value
  148. || std::is_same<V, qlonglong>::value, int> = 0>
  149. QByteArray serializeFixed(V value) const {
  150. qProtoDebug() << __func__ << "value" << value;
  151. //Reserve required amount of bytes
  152. QByteArray result(sizeof(V), '\0');
  153. *(V*)(result.data()) = value;
  154. return result;
  155. }
  156. template <typename V, typename UV = typename std::make_unsigned<V>::type,
  157. typename std::enable_if_t<std::is_signed<V>::value, int> = 0>
  158. QByteArray serializeVarint(V value) const {
  159. qProtoDebug() << __func__ << "value" << value;
  160. return serializeVarint(static_cast<UV>(value));
  161. }
  162. template <typename V, typename UV = typename std::make_unsigned<V>::type,
  163. typename std::enable_if_t<std::is_signed<V>::value, int> = 0>
  164. QByteArray serializeVarintZigZag(V value) const {
  165. qProtoDebug() << __func__ << "value" << value;
  166. UV uValue = 0;
  167. //Use ZigZag convertion first and apply unsigned variant next
  168. value = (value << 1) ^ (value >> (sizeof(UV) * 8 - 1));
  169. uValue = static_cast<UV>(value);
  170. return serializeVarint(uValue);
  171. }
  172. template <typename V,
  173. typename std::enable_if_t<std::is_unsigned<V>::value, int> = 0>
  174. QByteArray serializeVarint(V value) const {
  175. qProtoDebug() << __func__ << "value" << value;
  176. QByteArray result;
  177. //Reserve maximum required amount of bytes
  178. result.reserve(sizeof(V));
  179. while (value > 0) {
  180. //Put first 7 bits to result buffer and mark as not last
  181. result.append((value & 0x7F) | 0x80);
  182. //Devide values to chunks of 7 bits, move to next chunk
  183. value >>= 7;
  184. }
  185. //TODO: Zero case.
  186. //Aligned to reference cpp implementation. Where 0 ignored.
  187. //if (result.isEmpty()) {
  188. // result.append('\0');
  189. //}
  190. //Mark last chunk as last
  191. result.data()[result.size() - 1] &= ~0x80;
  192. return result;
  193. }
  194. template <typename V,
  195. typename std::enable_if_t<std::is_unsigned<V>::value, int> = 0>
  196. QByteArray serializeVarintZero(V value) const {
  197. qProtoDebug() << __func__ << "value" << value;
  198. QByteArray result = serializeVarint(value);
  199. //Zero case.
  200. if (result.isEmpty()) {
  201. result.append('\0');
  202. }
  203. return result;
  204. }
  205. //###########################################################################
  206. // Deserialization helpers
  207. //###########################################################################
  208. template <typename V,
  209. typename std::enable_if_t<std::is_floating_point<V>::value
  210. || std::is_same<V, int>::value
  211. || std::is_same<V, qlonglong>::value
  212. || std::is_same<V, unsigned int>::value
  213. || std::is_same<V, qulonglong>::value, int> = 0>
  214. QVariant deserializeFixed(QByteArray::const_iterator &it) {
  215. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  216. QVariant newPropertyValue(QVariant::fromValue(*(V*)it));
  217. it += sizeof(V);
  218. return newPropertyValue;
  219. }
  220. template <typename V,
  221. typename std::enable_if_t<std::is_unsigned<V>::value, int> = 0>
  222. QVariant deserializeVarint(QByteArray::const_iterator &it) {
  223. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  224. return QVariant::fromValue(deserializeVarintCommon<V>(it));
  225. }
  226. template <typename V, typename UV = typename std::make_unsigned<V>::type,
  227. typename std::enable_if_t<std::is_signed<V>::value, int> = 0>
  228. QVariant deserializeVarintZigZag(QByteArray::const_iterator &it) {
  229. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  230. UV unsignedValue = deserializeVarintCommon<UV>(it);
  231. V value = (unsignedValue >> 1) ^ (-(unsignedValue & 1));
  232. return QVariant::fromValue(value);
  233. }
  234. template <typename V, typename UV = typename std::make_unsigned<V>::type,
  235. typename std::enable_if_t<std::is_signed<V>::value, int> = 0>
  236. QVariant deserializeVarint(QByteArray::const_iterator &it) {
  237. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  238. UV unsignedValue = deserializeVarintCommon<UV>(it);
  239. V value = static_cast<V>(unsignedValue);
  240. return QVariant::fromValue(value);
  241. }
  242. template <typename V>
  243. V deserializeVarintCommon(QByteArray::const_iterator &it) {
  244. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  245. V value = 0;
  246. int k = 0;
  247. while (true) {
  248. uint64_t byte = static_cast<uint64_t>(*it);
  249. value += (byte & 0x7f) << k;
  250. k += 7;
  251. if (((*it) & 0x80) == 0) {
  252. break;
  253. }
  254. ++it;
  255. }
  256. ++it;
  257. return value;
  258. }
  259. QByteArray deserializeLengthDelimited(QByteArray::const_iterator &it) {
  260. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  261. unsigned int length = deserializeVarint<unsigned int>(it).toUInt();
  262. QByteArray result(it, length);
  263. it += length;
  264. return result;
  265. }
  266. QVariant deserializeProtobufObjectType(int userType, QByteArray::const_iterator &it) {
  267. auto value = reinterpret_cast<ProtobufObjectPrivate *>(QMetaType::create(userType));
  268. value->deserializePrivate(deserializeLengthDelimited(it));
  269. return QVariant(userType, value);
  270. }
  271. template <typename V,
  272. typename std::enable_if_t<std::is_same<V, QString>::value
  273. || std::is_same<V, QByteArray>::value, int> = 0>
  274. QByteArray deserializeListType(QByteArray::const_iterator &it) {
  275. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  276. return deserializeLengthDelimited(it);
  277. }
  278. template <typename V,
  279. typename std::enable_if_t<std::is_base_of<ProtobufObjectPrivate, V>::value, int> = 0>
  280. QVariant deserializeListType(QByteArray::const_iterator &it) {
  281. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  282. return deserializeProtobufObjectType(qMetaTypeId<V>(), it);
  283. }
  284. template <typename V,
  285. typename std::enable_if_t<std::is_floating_point<V>::value
  286. || std::is_same<V, unsigned int>::value
  287. || std::is_same<V, qulonglong>::value, int> = 0>
  288. QVariant deserializeListType(QByteArray::const_iterator &it) {
  289. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  290. QList<V> out;
  291. unsigned int count = deserializeVarint<unsigned int>(it).toUInt() / sizeof(V);
  292. for (unsigned int i = 0; i < count; i++) {
  293. QVariant variant = deserializeFixed<V>(it);
  294. out.append(variant.value<V>());
  295. }
  296. return QVariant::fromValue(out);
  297. }
  298. template <typename V>
  299. QVariant deserializeVarintListType(QByteArray::const_iterator &it) {
  300. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  301. QList<V> out;
  302. unsigned int count = deserializeVarint<unsigned int>(it).toUInt();
  303. QByteArray::const_iterator lastVarint = it + count;
  304. while (it != lastVarint) {
  305. QVariant variant = deserializeVarint<V>(it);
  306. out.append(variant.value<V>());
  307. }
  308. return QVariant::fromValue(out);
  309. }
  310. template <typename V>
  311. QVariant deserializeVarintListTypeZigZag(QByteArray::const_iterator &it) {
  312. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  313. QList<V> out;
  314. unsigned int count = deserializeVarint<unsigned int>(it).toUInt();
  315. QByteArray::const_iterator lastVarint = it + count;
  316. while (it != lastVarint) {
  317. QVariant variant = deserializeVarintZigZag<V>(it);
  318. out.append(variant.value<V>());
  319. }
  320. return QVariant::fromValue(out);
  321. }
  322. };
  323. /* Header byte
  324. * bits | 7 6 5 4 3 | 2 1 0
  325. * -----------------------------------
  326. * meaning | Field index | Type
  327. */
  328. unsigned char ProtobufObjectPrivate::encodeHeaderByte(int fieldIndex, WireTypes wireType)
  329. {
  330. unsigned char header = (fieldIndex << 3) | wireType;
  331. return static_cast<char>(header);
  332. }
  333. bool ProtobufObjectPrivate::decodeHeaderByte(unsigned char typeByte, int &fieldIndex, WireTypes &wireType)
  334. {
  335. wireType = static_cast<WireTypes>(typeByte & 0x07);
  336. fieldIndex = typeByte >> 3;
  337. return fieldIndex < 128 && fieldIndex > 0 && (wireType == Varint
  338. || wireType == Fixed64
  339. || wireType == Fixed32
  340. || wireType == LengthDelimited);
  341. }
  342. }