qprotobufserializer_p.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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 "qtprotobuftypes.h"
  28. #include "qprotobufobject_p.h"
  29. namespace qtprotobuf {
  30. class QProtobufSerializerPrivate {
  31. QProtobufSerializerPrivate() = delete;
  32. ~QProtobufSerializerPrivate() = delete;
  33. Q_DISABLE_COPY(QProtobufSerializerPrivate)
  34. QProtobufSerializerPrivate(ProtobufObjectPrivate &&) = delete;
  35. QProtobufSerializerPrivate &operator =(QProtobufSerializerPrivate &&) = delete;
  36. public:
  37. template <typename T,
  38. typename std::enable_if_t<!std::is_base_of<QObject, T>::value, int> = 0>
  39. static void wrapSerializer(const std::function<QByteArray(const T &, int &)> &s, const std::function<QVariant(SelfcheckIterator &)> &d, WireTypes type)
  40. {
  41. ProtobufObjectPrivate::serializers[qMetaTypeId<T>()] = {
  42. [s](const QVariant &value, int &fieldIndex) {
  43. return s(value.value<T>(), fieldIndex);
  44. },
  45. [d](SelfcheckIterator &it, QVariant & value){
  46. value = d(it);
  47. },
  48. type
  49. };
  50. }
  51. template <typename T,
  52. typename std::enable_if_t<!std::is_base_of<QObject, T>::value, int> = 0>
  53. static void wrapSerializer(const std::function<QByteArray(const T &, int &)> &s, const std::function<void(SelfcheckIterator &it, QVariant & value)> &d, WireTypes type)
  54. {
  55. ProtobufObjectPrivate::serializers[qMetaTypeId<T>()] = {
  56. [s](const QVariant &value, int &fieldIndex) {
  57. return s(value.value<T>(), fieldIndex);
  58. },
  59. d,
  60. type
  61. };
  62. }
  63. //----------------Serialize basic integral and floating point----------------
  64. /**
  65. * @brief Serialization of fixed-length primitive types
  66. *
  67. * Natural layout of bits is used: value is encoded in a byte array same way as it is located in memory
  68. *
  69. * @param[in] value Value to serialize
  70. * @param[out] outFieldIndex Index of the value in parent structure (ignored)
  71. * @return Byte array with value encoded
  72. */
  73. template <typename V,
  74. typename std::enable_if_t<std::is_floating_point<V>::value, int> = 0>
  75. static QByteArray serializeBasic(const V &value, int &/*outFieldIndex*/) {
  76. qProtoDebug() << __func__ << "value" << value;
  77. //Reserve required number of bytes
  78. QByteArray result(sizeof(V), '\0');
  79. *reinterpret_cast<V *>(result.data()) = value;
  80. return result;
  81. }
  82. /**
  83. * @brief Serialization of fixed length integral types
  84. *
  85. * @details Natural layout of bits is employed
  86. *
  87. * @param[in] value Value to serialize
  88. * @param[out] outFieldIndex Index of the value in parent structure (ignored)
  89. * @return Byte array with value encoded
  90. */
  91. template <typename V,
  92. typename std::enable_if_t<std::is_same<V, fixed32>::value
  93. || std::is_same<V, fixed64>::value
  94. || std::is_same<V, sfixed32>::value
  95. || std::is_same<V, sfixed64>::value, int> = 0>
  96. static QByteArray serializeBasic(const V &value, int &/*outFieldIndex*/) {
  97. qProtoDebug() << __func__ << "value" << value;
  98. //Reserve required number of bytes
  99. QByteArray result(sizeof(V), '\0');
  100. *reinterpret_cast<V *>(result.data()) = value;
  101. return result;
  102. }
  103. /**
  104. *@brief Serialization of signed integral types
  105. *
  106. * Use <a href="https://developers.google.com/protocol-buffers/docs/encoding">ZigZag encoding</a> first,
  107. * then apply serialization as for unsigned integral types
  108. * @see serializeBasic\<typename V, typename std::enable_if_t\<std::is_integral\<V\>::value && std::is_unsigned\<V\>::value, int\> = 0\>(V, int)
  109. *
  110. * @param[in] value Value to serialize
  111. * @param[out] outFieldIndex Index of the value in parent structure
  112. * @return Byte array with value encoded
  113. */
  114. template <typename V,
  115. typename std::enable_if_t<std::is_integral<V>::value
  116. && std::is_signed<V>::value, int> = 0>
  117. static QByteArray serializeBasic(const V &value, int &outFieldIndex) {
  118. qProtoDebug() << __func__ << "value" << value;
  119. using UV = typename std::make_unsigned<V>::type;
  120. UV uValue = 0;
  121. //Use ZigZag convertion first and apply unsigned variant next
  122. V zigZagValue = (value << 1) ^ (value >> (sizeof(UV) * 8 - 1));
  123. uValue = static_cast<UV>(zigZagValue);
  124. return serializeBasic(uValue, outFieldIndex);
  125. }
  126. template <typename V,
  127. typename std::enable_if_t<std::is_same<V, int32>::value
  128. || std::is_same<V, int64>::value, int> = 0>
  129. static QByteArray serializeBasic(const V &value, int &outFieldIndex) {
  130. qProtoDebug() << __func__ << "value" << value;
  131. using UV = typename std::make_unsigned<V>::type;
  132. return serializeBasic(static_cast<UV>(value), outFieldIndex);
  133. }
  134. /**
  135. *@brief Serialization of unsigned integral types
  136. *
  137. * Use <a href="https://developers.google.com/protocol-buffers/docs/encoding">Varint encoding</a>:
  138. * "Varints are a method of serializing integers using one or more bytes. Smaller numbers
  139. * [regardless its type] take a smaller number of bytes."
  140. *
  141. * @param[in] value Value to serialize
  142. * @param[out] outFieldIndex Index of the value in parent structure
  143. * @return Byte array with value encoded
  144. */
  145. template <typename V,
  146. typename std::enable_if_t<std::is_integral<V>::value
  147. && std::is_unsigned<V>::value, int> = 0>
  148. static QByteArray serializeBasic(const V &value, int &outFieldIndex) {
  149. qProtoDebug() << __func__ << "value" << value;
  150. V varint = value;
  151. QByteArray result;
  152. while (varint != 0) {
  153. //Put 7 bits to result buffer and mark as "not last" (0b10000000)
  154. result.append((varint & 0b01111111) | 0b10000000);
  155. //Divide values to chunks of 7 bits and move to next chunk
  156. varint >>= 7;
  157. }
  158. // Invalidate field index in case if serialized result is empty
  159. // NOTE: the field will not be sent if its index is equal to NotUsedFieldIndex
  160. if (result.size() == 0) {
  161. outFieldIndex = NotUsedFieldIndex;
  162. } else {
  163. //Mark last chunk as last by clearing last bit
  164. result.data()[result.size() - 1] &= ~0b10000000;
  165. }
  166. return result;
  167. }
  168. template <typename V,
  169. typename std::enable_if_t<std::is_same<V, QString>::value, int> = 0>
  170. static QByteArray serializeBasic(const V &value, int &/*outFieldIndex*/) {
  171. return serializeLengthDelimited(value.toUtf8());
  172. }
  173. template <typename V,
  174. typename std::enable_if_t<std::is_same<V, QByteArray>::value, int> = 0>
  175. static QByteArray serializeBasic(const V &value, int &/*outFieldIndex*/) {
  176. return serializeLengthDelimited(value);
  177. }
  178. //---------------Deserialize basic integral and floating point---------------
  179. template <typename V,
  180. typename std::enable_if_t<std::is_floating_point<V>::value
  181. || std::is_same<V, fixed32>::value
  182. || std::is_same<V, fixed64>::value
  183. || std::is_same<V, sfixed32>::value
  184. || std::is_same<V, sfixed64>::value, int> = 0>
  185. static QVariant deserializeBasic(SelfcheckIterator &it) {
  186. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  187. QVariant newPropertyValue(QVariant::fromValue(*(V *)((QByteArray::const_iterator&)it)));
  188. it += sizeof(V);
  189. return newPropertyValue;
  190. }
  191. template <typename V,
  192. typename std::enable_if_t<std::is_integral<V>::value
  193. && std::is_unsigned<V>::value, int> = 0>
  194. static QVariant deserializeBasic(SelfcheckIterator &it) {
  195. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  196. return QVariant::fromValue(deserializeVarintCommon<V>(it));
  197. }
  198. template <typename V,
  199. typename std::enable_if_t<std::is_integral<V>::value
  200. && std::is_signed<V>::value,int> = 0>
  201. static QVariant deserializeBasic(SelfcheckIterator &it) {
  202. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  203. using UV = typename std::make_unsigned<V>::type;
  204. UV unsignedValue = deserializeVarintCommon<UV>(it);
  205. V value = (unsignedValue >> 1) ^ (-1 * (unsignedValue & 1));
  206. return QVariant::fromValue<V>(value);
  207. }
  208. template <typename V,
  209. typename std::enable_if_t<std::is_same<int32, V>::value
  210. || std::is_same<int64, V>::value, int> = 0>
  211. static QVariant deserializeBasic(SelfcheckIterator &it) {
  212. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  213. using UV = typename std::make_unsigned<V>::type;
  214. UV unsignedValue = deserializeVarintCommon<UV>(it);
  215. V value = static_cast<V>(unsignedValue);
  216. return QVariant::fromValue(value);
  217. }
  218. template <typename V,
  219. typename std::enable_if_t<std::is_same<QByteArray, V>::value, int> = 0>
  220. static QVariant deserializeBasic(SelfcheckIterator &it) {
  221. return QVariant::fromValue(deserializeLengthDelimited(it));
  222. }
  223. template <typename V,
  224. typename std::enable_if_t<std::is_same<QString, V>::value, int> = 0>
  225. static QVariant deserializeBasic(SelfcheckIterator &it) {
  226. return QVariant::fromValue(QString::fromUtf8(deserializeLengthDelimited(it)));
  227. }
  228. template<typename V,
  229. typename std::enable_if_t<!(std::is_same<V, QString>::value
  230. || std::is_same<V, QByteArray>::value
  231. || std::is_base_of<QObject, V>::value), int> = 0>
  232. static QByteArray serializeListType(const QList<V> &listValue, int &outFieldIndex) {
  233. qProtoDebug() << __func__ << "listValue.count" << listValue.count() << "outFiledIndex" << outFieldIndex;
  234. if (listValue.count() <= 0) {
  235. outFieldIndex = NotUsedFieldIndex;
  236. return QByteArray();
  237. }
  238. int empty = NotUsedFieldIndex;
  239. QByteArray serializedList;
  240. for (auto &value : listValue) {
  241. serializedList.append(serializeBasic<V>(value, empty));
  242. }
  243. //If internal field type is not LengthDelimited, exact amount of fields to be specified
  244. ProtobufObjectPrivate::prependLengthDelimitedSize(serializedList);
  245. return serializedList;
  246. }
  247. template<typename V,
  248. typename std::enable_if_t<std::is_same<V, QString>::value, int> = 0>
  249. static QByteArray serializeListType(const QList<V> &listValue, int &outFieldIndex) {
  250. qProtoDebug() << __func__ << "listValue.count" << listValue.count() << "outFiledIndex" << outFieldIndex;
  251. if (listValue.count() <= 0) {
  252. outFieldIndex = NotUsedFieldIndex;
  253. return QByteArray();
  254. }
  255. QByteArray serializedList;
  256. for (auto &value : listValue) {
  257. serializedList.append(ProtobufObjectPrivate::encodeHeader(outFieldIndex, LengthDelimited));
  258. serializedList.append(serializeLengthDelimited(value.toUtf8()));
  259. }
  260. outFieldIndex = NotUsedFieldIndex;
  261. return serializedList;
  262. }
  263. template<typename V,
  264. typename std::enable_if_t<std::is_same<V, QByteArray>::value, int> = 0>
  265. static QByteArray serializeListType(const QList<V> &listValue, int &outFieldIndex) {
  266. qProtoDebug() << __func__ << "listValue.count" << listValue.count() << "outFiledIndex" << outFieldIndex;
  267. if (listValue.count() <= 0) {
  268. outFieldIndex = NotUsedFieldIndex;
  269. return QByteArray();
  270. }
  271. QByteArray serializedList;
  272. for (auto &value : listValue) {
  273. serializedList.append(ProtobufObjectPrivate::encodeHeader(outFieldIndex, LengthDelimited));
  274. serializedList.append(serializeLengthDelimited(value));
  275. }
  276. outFieldIndex = NotUsedFieldIndex;
  277. return serializedList;
  278. }
  279. template <typename V,
  280. typename std::enable_if_t<std::is_same<V, QByteArray>::value, int> = 0>
  281. static void deserializeList(SelfcheckIterator &it, QVariant &previous) {
  282. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  283. QByteArrayList list = previous.value<QByteArrayList>();
  284. list.append(deserializeLengthDelimited(it));
  285. previous.setValue(list);
  286. }
  287. template <typename V,
  288. typename std::enable_if_t<std::is_same<V, QString>::value, int> = 0>
  289. static void deserializeList(SelfcheckIterator &it, QVariant &previous) {
  290. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  291. QStringList list = previous.value<QStringList>();
  292. QByteArray value = deserializeLengthDelimited(it);
  293. list.append(QString::fromUtf8(value));
  294. previous.setValue(list);
  295. }
  296. template <typename V,
  297. typename std::enable_if_t<!(std::is_same<V, QString>::value
  298. || std::is_same<V, QByteArray>::value
  299. || std::is_base_of<QObject, V>::value), int> = 0>
  300. static void deserializeList(SelfcheckIterator &it, QVariant &previous) {
  301. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  302. QList<V> out;
  303. unsigned int count = deserializeVarintCommon<uint32>(it);
  304. SelfcheckIterator lastVarint = it + count;
  305. while (it != lastVarint) {
  306. QVariant variant = deserializeBasic<V>(it);
  307. out.append(variant.value<V>());
  308. }
  309. previous.setValue(out);
  310. }
  311. static QByteArray deserializeLengthDelimited(SelfcheckIterator &it) {
  312. qProtoDebug() << __func__ << "currentByte:" << QString::number((*it), 16);
  313. unsigned int length = deserializeVarintCommon<uint32>(it);
  314. QByteArray result((QByteArray::const_iterator&)it, length);
  315. it += length;
  316. return result;
  317. }
  318. static QByteArray serializeLengthDelimited(const QByteArray &data) {
  319. qProtoDebug() << __func__ << "data.size" << data.size() << "data" << data.toHex();
  320. QByteArray result(data);
  321. //Varint serialize field size and apply result as starting point
  322. ProtobufObjectPrivate::prependLengthDelimitedSize(result);
  323. return result;
  324. }
  325. };
  326. }