protobufobject_p.h 16 KB

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