protobufobject_p.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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 QLatin1Literal &typeName) 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_signed<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(serializeVarint(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_signed<V>::value, int> = 0>
  96. QByteArray serializeListTypeZigZag(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(serializeVarintZigZag(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_unsigned<V>::value, int> = 0>
  112. QByteArray serializeListType(const QList<V> &listValue, int &outFieldIndex) const {
  113. qProtoDebug() << __func__ << "listValue.count" << listValue.count() << "outFiledIndex" << outFieldIndex;
  114. if (listValue.count() <= 0) {
  115. outFieldIndex = NotUsedFieldIndex;
  116. return QByteArray();
  117. }
  118. QByteArray serializedList;
  119. for (auto &value : listValue) {
  120. serializedList.append(serializeVarint(value));
  121. }
  122. //If internal field type is not LengthDelimited, exact amount of fields to be specified
  123. serializedList.prepend(serializeVarintZero(static_cast<unsigned int>(serializedList.size())));
  124. return serializedList;
  125. }
  126. template<typename V,
  127. typename std::enable_if_t<std::is_floating_point<V>::value
  128. || std::is_same<V, unsigned int>::value
  129. || std::is_same<V, qulonglong>::value
  130. || std::is_same<V, int>::value
  131. || std::is_same<V, qlonglong>::value, int> = 0>
  132. QByteArray serializeFixedListType(const QList<V> &listValue, int &outFieldIndex) const {
  133. qProtoDebug() << __func__ << "listValue.count" << listValue.count() << "outFiledIndex" << outFieldIndex;
  134. if (listValue.count() <= 0) {
  135. outFieldIndex = NotUsedFieldIndex;
  136. return QByteArray();
  137. }
  138. QByteArray serializedList;
  139. for (auto &value : listValue) {
  140. serializedList.append(serializeFixed(value));
  141. }
  142. //If internal field type is not LengthDelimited, exact amount of fields to be specified
  143. serializedList.prepend(serializeVarintZero(static_cast<unsigned int>(serializedList.size())));
  144. return serializedList;
  145. }
  146. template<typename V,
  147. typename std::enable_if_t<std::is_same<V, QString>::value
  148. || std::is_same<V, QByteArray>::value, int> = 0>
  149. QByteArray serializeListType(const QList<V> &listValue, int &outFieldIndex) const {
  150. qProtoDebug() << __func__ << "listValue.count" << listValue.count() << "outFiledIndex" << outFieldIndex;
  151. if (listValue.count() <= 0) {
  152. outFieldIndex = NotUsedFieldIndex;
  153. return QByteArray();
  154. }
  155. QByteArray serializedList;
  156. for (auto &value : listValue) {
  157. serializedList.append(serializeValue(value, outFieldIndex, QLatin1Literal()));
  158. }
  159. outFieldIndex = NotUsedFieldIndex;
  160. return serializedList;
  161. }
  162. template<typename V,
  163. typename std::enable_if_t<std::is_base_of<ProtobufObjectPrivate, V>::value, int> = 0>
  164. QByteArray serializeListType(const QList<V> &listValue, int &outFieldIndex) const {
  165. qProtoDebug() << __func__ << "listValue.count" << listValue.count() << "outFiledIndex" << outFieldIndex;
  166. if (listValue.count() <= 0) {
  167. outFieldIndex = NotUsedFieldIndex;
  168. return QByteArray();
  169. }
  170. QByteArray serializedList;
  171. for (auto &value : listValue) {
  172. QByteArray serializedValue = serializeLengthDelimited(value.serialize());
  173. serializedValue.prepend(encodeHeaderByte(outFieldIndex, LengthDelimited));
  174. serializedList.append(serializedValue);
  175. }
  176. outFieldIndex = NotUsedFieldIndex;
  177. return serializedList;
  178. }
  179. template <typename V,
  180. typename std::enable_if_t<std::is_floating_point<V>::value
  181. || std::is_same<V, unsigned int>::value
  182. || std::is_same<V, qulonglong>::value
  183. || std::is_same<V, int>::value
  184. || std::is_same<V, qlonglong>::value, int> = 0>
  185. QByteArray serializeFixed(V value) const {
  186. qProtoDebug() << __func__ << "value" << value;
  187. //Reserve required amount of bytes
  188. QByteArray result(sizeof(V), '\0');
  189. *(V*)(result.data()) = value;
  190. return result;
  191. }
  192. template <typename V, typename UV = typename std::make_unsigned<V>::type,
  193. typename std::enable_if_t<std::is_signed<V>::value, int> = 0>
  194. QByteArray serializeVarint(V value) const {
  195. qProtoDebug() << __func__ << "value" << value;
  196. return serializeVarint(static_cast<UV>(value));
  197. }
  198. template <typename V, typename UV = typename std::make_unsigned<V>::type,
  199. typename std::enable_if_t<std::is_signed<V>::value, int> = 0>
  200. QByteArray serializeVarintZigZag(V value) const {
  201. qProtoDebug() << __func__ << "value" << value;
  202. UV uValue = 0;
  203. //Use ZigZag convertion first and apply unsigned variant next
  204. value = (value << 1) ^ (value >> (sizeof(UV) * 8 - 1));
  205. uValue = static_cast<UV>(value);
  206. return serializeVarint(uValue);
  207. }
  208. template <typename V,
  209. typename std::enable_if_t<std::is_unsigned<V>::value, int> = 0>
  210. QByteArray serializeVarint(V value) const {
  211. qProtoDebug() << __func__ << "value" << value;
  212. QByteArray result;
  213. //Reserve maximum required amount of bytes
  214. result.reserve(sizeof(V));
  215. while (value > 0) {
  216. //Put first 7 bits to result buffer and mark as not last
  217. result.append((value & 0x7F) | 0x80);
  218. //Devide values to chunks of 7 bits, move to next chunk
  219. value >>= 7;
  220. }
  221. //TODO: Zero case.
  222. //Aligned to reference cpp implementation. Where 0 ignored.
  223. //if (result.isEmpty()) {
  224. // result.append('\0');
  225. //}
  226. //Mark last chunk as last
  227. result.data()[result.size() - 1] &= ~0x80;
  228. return result;
  229. }
  230. template <typename V,
  231. typename std::enable_if_t<std::is_unsigned<V>::value, int> = 0>
  232. QByteArray serializeVarintZero(V value) const {
  233. qProtoDebug() << __func__ << "value" << value;
  234. QByteArray result = serializeVarint(value);
  235. //Zero case.
  236. if (result.isEmpty()) {
  237. result.append('\0');
  238. }
  239. return result;
  240. }
  241. //###########################################################################
  242. // Deserialization helpers
  243. //###########################################################################
  244. template <typename V,
  245. typename std::enable_if_t<std::is_floating_point<V>::value
  246. || std::is_same<V, int>::value
  247. || std::is_same<V, qlonglong>::value
  248. || std::is_same<V, unsigned int>::value
  249. || std::is_same<V, qulonglong>::value, int> = 0>
  250. QVariant deserializeFixed(QByteArray::const_iterator &it) {
  251. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  252. QVariant newPropertyValue(QVariant::fromValue(*(V*)it));
  253. it += sizeof(V);
  254. return newPropertyValue;
  255. }
  256. template <typename V,
  257. typename std::enable_if_t<std::is_unsigned<V>::value, int> = 0>
  258. QVariant deserializeVarint(QByteArray::const_iterator &it) {
  259. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  260. return QVariant::fromValue(deserializeVarintCommon<V>(it));
  261. }
  262. template <typename V, typename UV = typename std::make_unsigned<V>::type,
  263. typename std::enable_if_t<std::is_signed<V>::value, int> = 0>
  264. QVariant deserializeVarintZigZag(QByteArray::const_iterator &it) {
  265. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  266. UV unsignedValue = deserializeVarintCommon<UV>(it);
  267. V value = (unsignedValue >> 1) ^ (-(unsignedValue & 1));
  268. return QVariant::fromValue(value);
  269. }
  270. template <typename V, typename UV = typename std::make_unsigned<V>::type,
  271. typename std::enable_if_t<std::is_signed<V>::value, int> = 0>
  272. QVariant deserializeVarint(QByteArray::const_iterator &it) {
  273. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  274. UV unsignedValue = deserializeVarintCommon<UV>(it);
  275. V value = static_cast<V>(unsignedValue);
  276. return QVariant::fromValue(value);
  277. }
  278. template <typename V>
  279. V deserializeVarintCommon(QByteArray::const_iterator &it) {
  280. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  281. V value = 0;
  282. int k = 0;
  283. while (true) {
  284. uint64_t byte = static_cast<uint64_t>(*it);
  285. value += (byte & 0x7f) << k;
  286. k += 7;
  287. if (((*it) & 0x80) == 0) {
  288. break;
  289. }
  290. ++it;
  291. }
  292. ++it;
  293. return value;
  294. }
  295. QByteArray deserializeLengthDelimited(QByteArray::const_iterator &it) {
  296. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  297. unsigned int length = deserializeVarint<unsigned int>(it).toUInt();
  298. QByteArray result(it, length);
  299. it += length;
  300. return result;
  301. }
  302. QVariant deserializeProtobufObjectType(int userType, QByteArray::const_iterator &it) {
  303. auto value = reinterpret_cast<ProtobufObjectPrivate *>(QMetaType::create(userType));
  304. value->deserializePrivate(deserializeLengthDelimited(it));
  305. return QVariant(userType, value);
  306. }
  307. template <typename V,
  308. typename std::enable_if_t<std::is_same<V, QString>::value
  309. || std::is_same<V, QByteArray>::value, int> = 0>
  310. QByteArray deserializeListType(QByteArray::const_iterator &it) {
  311. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  312. return deserializeLengthDelimited(it);
  313. }
  314. template <typename V,
  315. typename std::enable_if_t<std::is_base_of<ProtobufObjectPrivate, V>::value, int> = 0>
  316. QVariant deserializeListType(QByteArray::const_iterator &it) {
  317. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  318. return deserializeProtobufObjectType(qMetaTypeId<V>(), it);
  319. }
  320. template <typename V,
  321. typename std::enable_if_t<std::is_floating_point<V>::value
  322. || std::is_same<V, unsigned int>::value
  323. || std::is_same<V, qulonglong>::value
  324. || std::is_same<V, int>::value
  325. || std::is_same<V, qlonglong>::value, int> = 0>
  326. QVariant deserializeListType(QByteArray::const_iterator &it) {
  327. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  328. QList<V> out;
  329. unsigned int count = deserializeVarint<unsigned int>(it).toUInt() / sizeof(V);
  330. for (unsigned int i = 0; i < count; i++) {
  331. QVariant variant = deserializeFixed<V>(it);
  332. out.append(variant.value<V>());
  333. }
  334. return QVariant::fromValue(out);
  335. }
  336. template <typename V>
  337. QVariant deserializeVarintListType(QByteArray::const_iterator &it) {
  338. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  339. QList<V> out;
  340. unsigned int count = deserializeVarint<unsigned int>(it).toUInt();
  341. QByteArray::const_iterator lastVarint = it + count;
  342. while (it != lastVarint) {
  343. QVariant variant = deserializeVarint<V>(it);
  344. out.append(variant.value<V>());
  345. }
  346. return QVariant::fromValue(out);
  347. }
  348. template <typename V>
  349. QVariant deserializeVarintListTypeZigZag(QByteArray::const_iterator &it) {
  350. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  351. QList<V> out;
  352. unsigned int count = deserializeVarint<unsigned int>(it).toUInt();
  353. QByteArray::const_iterator lastVarint = it + count;
  354. while (it != lastVarint) {
  355. QVariant variant = deserializeVarintZigZag<V>(it);
  356. out.append(variant.value<V>());
  357. }
  358. return QVariant::fromValue(out);
  359. }
  360. };
  361. /* Header byte
  362. * bits | 7 6 5 4 3 | 2 1 0
  363. * -----------------------------------
  364. * meaning | Field index | Type
  365. */
  366. unsigned char ProtobufObjectPrivate::encodeHeaderByte(int fieldIndex, WireTypes wireType)
  367. {
  368. unsigned char header = (fieldIndex << 3) | wireType;
  369. return static_cast<char>(header);
  370. }
  371. bool ProtobufObjectPrivate::decodeHeaderByte(unsigned char typeByte, int &fieldIndex, WireTypes &wireType)
  372. {
  373. wireType = static_cast<WireTypes>(typeByte & 0x07);
  374. fieldIndex = typeByte >> 3;
  375. return fieldIndex < 128 && fieldIndex > 0 && (wireType == Varint
  376. || wireType == Fixed64
  377. || wireType == Fixed32
  378. || wireType == LengthDelimited);
  379. }
  380. }