qprotobufserializer_p.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. /*
  2. * MIT License
  3. *
  4. * Copyright (c) 2019 Alexey Edelev <semlanik@gmail.com>, Viktor Kopp <vifactor@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. #include <QString>
  26. #include <QByteArray>
  27. #include <QtProtobuf/qprotobufselfcheckiterator.h>
  28. #include <QtProtobuf/qtprotobuftypes.h>
  29. #include <QtProtobuf/private/qtprotobuflogging_p.h>
  30. #include <QtProtobuf/qabstractprotobufserializer.h>
  31. QT_BEGIN_NAMESPACE
  32. /*!
  33. * \ingroup QtProtobuf
  34. * \private
  35. * \brief The QProtobufSerializerPrivate class
  36. */
  37. class QProtobufSerializer;
  38. //! \private
  39. class QProtobufSerializerPrivate final
  40. {
  41. Q_DISABLE_COPY_MOVE(QProtobufSerializerPrivate)
  42. public:
  43. /*!
  44. * \brief Serializer is interface function for serialize method
  45. */
  46. using Serializer = QByteArray(*)(const QVariant &, int &);
  47. /*!
  48. * \brief Deserializer is interface function for deserialize method
  49. */
  50. using Deserializer = void(*)(QProtobufSelfcheckIterator &, QVariant &);
  51. /*!
  52. * \private
  53. * \brief SerializationHandlers contains set of objects that required for class serializaion/deserialization
  54. */
  55. struct SerializationHandlers {
  56. Serializer serializer; /*!< serializer assigned to class */
  57. Deserializer deserializer;/*!< deserializer assigned to class */
  58. WireTypes type;/*!< Serialization WireType */
  59. };
  60. using SerializerRegistry = std::unordered_map<int/*metatypeid*/, SerializationHandlers>;
  61. QProtobufSerializerPrivate(QProtobufSerializer *q);
  62. ~QProtobufSerializerPrivate() = default;
  63. //###########################################################################
  64. // Serializers
  65. //###########################################################################
  66. template <typename V,
  67. typename std::enable_if_t<std::is_integral<V>::value
  68. && std::is_unsigned<V>::value, int> = 0>
  69. static QByteArray serializeVarintCommon(const V &value) {
  70. qProtoDebug() << __func__ << "value" << value;
  71. V varint = value;
  72. QByteArray result;
  73. while (varint != 0) {
  74. //Put 7 bits to result buffer and mark as "not last" (0b10000000)
  75. result.append((varint & 0b01111111) | 0b10000000);
  76. //Divide values to chunks of 7 bits and move to next chunk
  77. varint >>= 7;
  78. }
  79. if (result.isEmpty()) {
  80. result.append('\0');
  81. }
  82. result.data()[result.size() - 1] &= ~0b10000000;
  83. return result;
  84. }
  85. //---------------Integral and floating point types serializers---------------
  86. /*!
  87. * \brief Serialization of fixed-length primitive types
  88. *
  89. * Natural layout of bits is used: value is encoded in a byte array same way as it is located in memory
  90. *
  91. * \param[in] value Value to serialize
  92. * \param[out] outFieldIndex Index of the value in parent structure (ignored)
  93. * \return Byte array with value encoded
  94. */
  95. template <typename V,
  96. typename std::enable_if_t<std::is_floating_point<V>::value, int> = 0>
  97. static QByteArray serializeBasic(const V &value, int &/*outFieldIndex*/) {
  98. qProtoDebug() << __func__ << "value" << value;
  99. //Reserve required number of bytes
  100. QByteArray result(sizeof(V), '\0');
  101. *reinterpret_cast<V *>(result.data()) = value;
  102. return result;
  103. }
  104. /*!
  105. * \brief Serialization of fixed length integral types
  106. *
  107. * \details Natural layout of bits is employed
  108. *
  109. * \param[in] value Value to serialize
  110. * \param[out] outFieldIndex Index of the value in parent structure (ignored)
  111. * \return Byte array with value encoded
  112. */
  113. template <typename V,
  114. typename std::enable_if_t<std::is_same<V, QtProtobuf::fixed32>::value
  115. || std::is_same<V, QtProtobuf::fixed64>::value
  116. || std::is_same<V, QtProtobuf::sfixed32>::value
  117. || std::is_same<V, QtProtobuf::sfixed64>::value, int> = 0>
  118. static QByteArray serializeBasic(const V &value, int &/*outFieldIndex*/) {
  119. qProtoDebug() << __func__ << "value" << value;
  120. //Reserve required number of bytes
  121. QByteArray result(sizeof(V), '\0');
  122. *reinterpret_cast<V *>(result.data()) = value;
  123. return result;
  124. }
  125. /*!
  126. *\brief Serialization of signed integral types
  127. *
  128. * Use <a href="https://developers.google.com/protocol-buffers/docs/encoding">ZigZag encoding</a> first,
  129. * then apply serialization as for unsigned integral types
  130. * \see serializeBasic\<typename V, typename std::enable_if_t\<std::is_integral\<V\>::value && std::is_unsigned\<V\>::value, int\> = 0\>(V, int)
  131. *
  132. * \param[in] value Value to serialize
  133. * \param[out] outFieldIndex Index of the value in parent structure
  134. * \return Byte array with value encoded
  135. */
  136. template <typename V,
  137. typename std::enable_if_t<std::is_integral<V>::value
  138. && std::is_signed<V>::value, int> = 0>
  139. static QByteArray serializeBasic(const V &value, int &outFieldIndex) {
  140. qProtoDebug() << __func__ << "value" << value;
  141. using UV = typename std::make_unsigned<V>::type;
  142. UV uValue = 0;
  143. //Use ZigZag convertion first and apply unsigned variant next
  144. V zigZagValue = (value << 1) ^ (value >> (sizeof(UV) * 8 - 1));
  145. uValue = static_cast<UV>(zigZagValue);
  146. return serializeBasic(uValue, outFieldIndex);
  147. }
  148. template <typename V,
  149. typename std::enable_if_t<std::is_same<V, QtProtobuf::int32>::value
  150. || std::is_same<V, QtProtobuf::int64>::value, int> = 0>
  151. static QByteArray serializeBasic(const V &value, int &outFieldIndex) {
  152. qProtoDebug() << __func__ << "value" << value;
  153. using UV = typename std::make_unsigned<V>::type;
  154. return serializeBasic(static_cast<UV>(value), outFieldIndex);
  155. }
  156. /*!
  157. *\brief Serialization of unsigned integral types
  158. *
  159. * Use <a href="https://developers.google.com/protocol-buffers/docs/encoding">Varint encoding</a>:
  160. * "Varints are a method of serializing integers using one or more bytes. Smaller numbers
  161. * [regardless its type] take a smaller number of bytes."
  162. *
  163. * \param[in] value Value to serialize
  164. * \param[out] outFieldIndex Index of the value in parent structure
  165. * \return Byte array with value encoded
  166. */
  167. template <typename V,
  168. typename std::enable_if_t<std::is_integral<V>::value
  169. && std::is_unsigned<V>::value, int> = 0>
  170. static QByteArray serializeBasic(const V &value, int &outFieldIndex) {
  171. qProtoDebug() << __func__ << "value" << value;
  172. V varint = value;
  173. QByteArray result;
  174. while (varint != 0) {
  175. //Put 7 bits to result buffer and mark as "not last" (0b10000000)
  176. result.append((varint & 0b01111111) | 0b10000000);
  177. //Divide values to chunks of 7 bits and move to next chunk
  178. varint >>= 7;
  179. }
  180. // Invalidate field index in case if serialized result is empty
  181. // NOTE: the field will not be sent if its index is equal to NotUsedFieldIndex
  182. if (result.size() == 0) {
  183. outFieldIndex = QtProtobufPrivate::NotUsedFieldIndex;
  184. } else {
  185. //Mark last chunk as last by clearing last bit
  186. result.data()[result.size() - 1] &= ~0b10000000;
  187. }
  188. return result;
  189. }
  190. //------------------QString and QByteArray types serializers-----------------
  191. template <typename V,
  192. typename std::enable_if_t<std::is_same<V, QString>::value, int> = 0>
  193. static QByteArray serializeBasic(const V &value, int &/*outFieldIndex*/) {
  194. return serializeLengthDelimited(value.toUtf8());
  195. }
  196. template <typename V,
  197. typename std::enable_if_t<std::is_same<V, QByteArray>::value, int> = 0>
  198. static QByteArray serializeBasic(const V &value, int &/*outFieldIndex*/) {
  199. return serializeLengthDelimited(value);
  200. }
  201. //--------------------------List types serializers---------------------------
  202. template<typename V,
  203. typename std::enable_if_t<!(std::is_same<V, QString>::value
  204. || std::is_base_of<QObject, V>::value), int> = 0>
  205. static QByteArray serializeListType(const QList<V> &listValue, int &outFieldIndex) {
  206. qProtoDebug() << __func__ << "listValue.count" << listValue.count() << "outFiledIndex" << outFieldIndex;
  207. if (listValue.count() <= 0) {
  208. outFieldIndex = QtProtobufPrivate::NotUsedFieldIndex;
  209. return QByteArray();
  210. }
  211. int empty = QtProtobufPrivate::NotUsedFieldIndex;
  212. QByteArray serializedList;
  213. for (auto &value : listValue) {
  214. QByteArray element = serializeBasic<V>(value, empty);
  215. if (element.isEmpty()) {
  216. element.append('\0');
  217. }
  218. serializedList.append(element);
  219. }
  220. //If internal field type is not LengthDelimited, exact amount of fields to be specified
  221. serializedList = prependLengthDelimitedSize(serializedList);
  222. return serializedList;
  223. }
  224. template<typename V,
  225. typename std::enable_if_t<std::is_same<V, QString>::value, int> = 0>
  226. static QByteArray serializeListType(const QStringList &listValue, int &outFieldIndex) {
  227. qProtoDebug() << __func__ << "listValue.count" << listValue.count() << "outFiledIndex" << outFieldIndex;
  228. if (listValue.count() <= 0) {
  229. outFieldIndex = QtProtobufPrivate::NotUsedFieldIndex;
  230. return QByteArray();
  231. }
  232. QByteArray serializedList;
  233. for (auto &value : listValue) {
  234. serializedList.append(QProtobufSerializerPrivate::encodeHeader(outFieldIndex, LengthDelimited));
  235. serializedList.append(serializeLengthDelimited(value.toUtf8()));
  236. }
  237. outFieldIndex = QtProtobufPrivate::NotUsedFieldIndex;
  238. return serializedList;
  239. }
  240. //###########################################################################
  241. // Deserializers
  242. //###########################################################################
  243. template <typename V,
  244. typename std::enable_if_t<std::is_integral<V>::value
  245. && std::is_unsigned<V>::value, int> = 0>
  246. static V deserializeVarintCommon(QProtobufSelfcheckIterator &it) {
  247. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  248. V value = 0;
  249. int k = 0;
  250. while (true) {
  251. uint64_t byte = static_cast<uint64_t>(*it);
  252. value += (byte & 0b01111111) << k;
  253. k += 7;
  254. if (((*it) & 0b10000000) == 0) {
  255. break;
  256. }
  257. ++it;
  258. }
  259. ++it;
  260. return value;
  261. }
  262. //-------------Integral and floating point types deserializers---------------
  263. template <typename V,
  264. typename std::enable_if_t<std::is_floating_point<V>::value
  265. || std::is_same<V, QtProtobuf::fixed32>::value
  266. || std::is_same<V, QtProtobuf::fixed64>::value
  267. || std::is_same<V, QtProtobuf::sfixed32>::value
  268. || std::is_same<V, QtProtobuf::sfixed64>::value, int> = 0>
  269. static void deserializeBasic(QProtobufSelfcheckIterator &it, QVariant &variantValue) {
  270. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  271. variantValue = QVariant::fromValue(*(V *)((QByteArray::const_iterator&)it));
  272. it += sizeof(V);
  273. }
  274. template <typename V,
  275. typename std::enable_if_t<std::is_integral<V>::value
  276. && std::is_unsigned<V>::value, int> = 0>
  277. static void deserializeBasic(QProtobufSelfcheckIterator &it, QVariant &variantValue) {
  278. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  279. variantValue = QVariant::fromValue(deserializeVarintCommon<V>(it));
  280. }
  281. template <typename V,
  282. typename std::enable_if_t<std::is_integral<V>::value
  283. && std::is_signed<V>::value,int> = 0>
  284. static void deserializeBasic(QProtobufSelfcheckIterator &it, QVariant &variantValue) {
  285. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  286. using UV = typename std::make_unsigned<V>::type;
  287. UV unsignedValue = deserializeVarintCommon<UV>(it);
  288. V value = (unsignedValue >> 1) ^ (-1 * (unsignedValue & 1));
  289. variantValue = QVariant::fromValue<V>(value);
  290. }
  291. template <typename V,
  292. typename std::enable_if_t<std::is_same<QtProtobuf::int32, V>::value
  293. || std::is_same<QtProtobuf::int64, V>::value, int> = 0>
  294. static void deserializeBasic(QProtobufSelfcheckIterator &it, QVariant &variantValue) {
  295. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  296. using UV = typename std::make_unsigned<V>::type;
  297. UV unsignedValue = deserializeVarintCommon<UV>(it);
  298. V value = static_cast<V>(unsignedValue);
  299. variantValue = QVariant::fromValue(value);
  300. }
  301. //-----------------QString and QByteArray types deserializers----------------
  302. template <typename V,
  303. typename std::enable_if_t<std::is_same<QByteArray, V>::value, int> = 0>
  304. static void deserializeBasic(QProtobufSelfcheckIterator &it, QVariant &variantValue) {
  305. variantValue = QVariant::fromValue(deserializeLengthDelimited(it));
  306. }
  307. template <typename V,
  308. typename std::enable_if_t<std::is_same<QString, V>::value, int> = 0>
  309. static void deserializeBasic(QProtobufSelfcheckIterator &it, QVariant &variantValue) {
  310. variantValue = QVariant::fromValue(QString::fromUtf8(deserializeLengthDelimited(it)));
  311. }
  312. //-------------------------List types deserializers--------------------------
  313. template <typename V,
  314. typename std::enable_if_t<!std::is_base_of<QObject, V>::value, int> = 0>
  315. static void deserializeList(QProtobufSelfcheckIterator &it, QVariant &previousValue) {
  316. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  317. QList<V> out;
  318. unsigned int count = deserializeVarintCommon<QtProtobuf::uint32>(it);
  319. QProtobufSelfcheckIterator lastVarint = it + count;
  320. while (it != lastVarint) {
  321. QVariant variantValue;
  322. deserializeBasic<V>(it, variantValue);
  323. out.append(variantValue.value<V>());
  324. }
  325. previousValue.setValue(out);
  326. }
  327. //###########################################################################
  328. // Common functions
  329. //###########################################################################
  330. static QByteArray deserializeLengthDelimited(QProtobufSelfcheckIterator &it) {
  331. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  332. unsigned int length = deserializeVarintCommon<QtProtobuf::uint32>(it);
  333. QByteArray result((QByteArray::const_iterator&)it, length); //TODO: it's possible to avoid buffer copying by setuping new "end of QByteArray";
  334. it += length;
  335. return result;
  336. }
  337. static QByteArray serializeLengthDelimited(const QByteArray &data) {
  338. qProtoDebug() << __func__ << "data.size" << data.size() << "data" << data.toHex();
  339. QByteArray result(data);
  340. //Varint serialize field size and apply result as starting point
  341. result = prependLengthDelimitedSize(result);
  342. return result;
  343. }
  344. static bool decodeHeader(QProtobufSelfcheckIterator &it, int &fieldIndex, WireTypes &wireType);
  345. static QByteArray encodeHeader(int fieldIndex, WireTypes wireType);
  346. /*!
  347. * \brief Gets length of a byte-array and prepends to it its serialized length value
  348. * using the appropriate serialization algorithm
  349. *
  350. *
  351. * \param[in, out] serializedList Byte-array to be prepended
  352. */
  353. static QByteArray prependLengthDelimitedSize(const QByteArray &data)
  354. {
  355. return serializeVarintCommon<uint32_t>(data.size()) + data;
  356. }
  357. template <typename T,
  358. QByteArray(*s)(const T &, int &)>
  359. static QByteArray serializeWrapper(const QVariant &variantValue, int &fieldIndex) {
  360. if (variantValue.isNull()) {
  361. fieldIndex = QtProtobufPrivate::NotUsedFieldIndex;
  362. return QByteArray();
  363. }
  364. const T& value = *(static_cast<const T *>(variantValue.data()));
  365. return s(value, fieldIndex);
  366. }
  367. template <typename T, QByteArray(*s)(const T &, int &), Deserializer d, WireTypes type,
  368. typename std::enable_if_t<!std::is_base_of<QObject, T>::value, int> = 0>
  369. static void wrapSerializer() {
  370. handlers[qMetaTypeId<T>()] = {
  371. serializeWrapper<T, s>,
  372. d,
  373. type
  374. };
  375. }
  376. template <typename T, typename S, QByteArray(*s)(const S &, int &), Deserializer d, WireTypes type,
  377. typename std::enable_if_t<!std::is_base_of<QObject, T>::value, int> = 0>
  378. static void wrapSerializer() {
  379. handlers[qMetaTypeId<T>()] = {
  380. serializeWrapper<S, s>,
  381. d,
  382. type
  383. };
  384. }
  385. // this set of 3 methods is used to skip bytes corresponding to an unexpected property
  386. // in a serialized message met while the message being deserialized
  387. static int skipSerializedFieldBytes(QProtobufSelfcheckIterator &it, WireTypes type);
  388. static void skipVarint(QProtobufSelfcheckIterator &it);
  389. static void skipLengthDelimited(QProtobufSelfcheckIterator &it);
  390. QByteArray serializeProperty(const QVariant &propertyValue, const QProtobufMetaProperty &metaProperty);
  391. void deserializeProperty(QObject *object, const QProtobufMetaObject &metaObject, QProtobufSelfcheckIterator &it);
  392. void deserializeMapPair(QVariant &key, QVariant &value, QProtobufSelfcheckIterator &it);
  393. private:
  394. static SerializerRegistry handlers;
  395. QProtobufSerializer *q_ptr;
  396. };
  397. //###########################################################################
  398. // Common functions
  399. //###########################################################################
  400. /*! \brief Encode a property field index and its type into output bytes
  401. *
  402. * \details
  403. * Header byte
  404. * Meaning | Field index | Type
  405. * ---------- | ------------- | --------
  406. * bit number | 7 6 5 4 3 | 2 1 0
  407. * \param fieldIndex The index of a property in parent object
  408. * \param wireType Serialization type used for the property with index @p fieldIndex
  409. *
  410. * \return Varint encoded fieldIndex and wireType
  411. */
  412. inline QByteArray QProtobufSerializerPrivate::encodeHeader(int fieldIndex, WireTypes wireType)
  413. {
  414. uint32_t header = (fieldIndex << 3) | wireType;
  415. return serializeVarintCommon<uint32_t>(header);
  416. }
  417. /*! \brief Decode a property field index and its serialization type from input bytes
  418. *
  419. * \param[in] Iterator that points to header with encoded field index and serialization type
  420. * \param[out] fieldIndex Decoded index of a property in parent object
  421. * \param[out] wireType Decoded serialization type used for the property with index @p fieldIndex
  422. *
  423. * \return true if both decoded wireType and fieldIndex have "allowed" values and false, otherwise
  424. */
  425. inline bool QProtobufSerializerPrivate::decodeHeader(QProtobufSelfcheckIterator &it, int &fieldIndex, WireTypes &wireType)
  426. {
  427. uint32_t header = deserializeVarintCommon<uint32_t>(it);
  428. wireType = static_cast<WireTypes>(header & 0b00000111);
  429. fieldIndex = header >> 3;
  430. constexpr int maxFieldIndex = (1 << 29) - 1;
  431. return fieldIndex <= maxFieldIndex && fieldIndex > 0 && (wireType == Varint
  432. || wireType == Fixed64
  433. || wireType == Fixed32
  434. || wireType == LengthDelimited);
  435. }
  436. QT_END_NAMESPACE