protobufobject.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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 <QDebug>
  28. #include <QMetaObject>
  29. #include <QMetaProperty>
  30. #include <QBitArray>
  31. #include <unordered_map>
  32. #include <memory>
  33. #include <type_traits>
  34. #include <qtprotobuftypes.h>
  35. #define ASSERT_FIELD_NUMBER(X) Q_ASSERT_X(X < 128 && X > 0 && X != NotUsedFieldIndex, T::staticMetaObject.className(), "fieldIndex is out of range")
  36. namespace qtprotobuf {
  37. enum WireTypes {
  38. UnknownWireType = -1,
  39. Varint = 0,
  40. Fixed64 = 1,
  41. LengthDelimited = 2,
  42. Fixed32 = 5
  43. };
  44. constexpr int NotUsedFieldIndex = -1;
  45. class ProtobufObjectPrivate : public QObject {
  46. protected:
  47. explicit ProtobufObjectPrivate(QObject *parent = nullptr) : QObject(parent) {}
  48. /* Header byte
  49. * bits | 7 6 5 4 3 | 2 1 0
  50. * -----------------------------------
  51. * meaning | Field index | Type
  52. */
  53. inline static unsigned char encodeHeaderByte(int fieldIndex, WireTypes wireType) {
  54. unsigned char header = (fieldIndex << 3) | wireType;
  55. return *(char *)&header;
  56. }
  57. inline static bool decodeHeaderByte(unsigned char typeByte, int &fieldIndex, WireTypes &wireType) {
  58. wireType = static_cast<WireTypes>(typeByte & 0x07);
  59. fieldIndex = typeByte >> 3;
  60. return fieldIndex < 128 && fieldIndex > 0 && (wireType == Varint
  61. || wireType == Fixed64
  62. || wireType == Fixed32
  63. || wireType == LengthDelimited);
  64. }
  65. QByteArray serializeValue(const QVariant& propertyValue, int fieldIndex, bool isFixed = false) {
  66. QByteArray result;
  67. WireTypes type = UnknownWireType;
  68. switch (propertyValue.type()) {
  69. case QMetaType::Int:
  70. type = Varint;
  71. result.append(serializeVarint(propertyValue.toInt()));
  72. break;
  73. case QMetaType::Float:
  74. type = Fixed32;
  75. result.append(serializeFixed(propertyValue.toFloat()));
  76. break;
  77. case QMetaType::Double:
  78. type = Fixed64;
  79. result.append(serializeFixed(propertyValue.toDouble()));
  80. break;
  81. case QMetaType::QString:
  82. type = LengthDelimited;
  83. result.append(serializeLengthDelimited(propertyValue.toString().toUtf8()));
  84. break;
  85. case QMetaType::QByteArray:
  86. type = LengthDelimited;
  87. result.append(serializeLengthDelimited(propertyValue.toByteArray()));
  88. break;
  89. //TODO: explicit QList<TypeName> is more user friendly and performance efficient
  90. case QMetaType::QVariantList:
  91. type = LengthDelimited;
  92. result.append(serializeListType(propertyValue.toList(), fieldIndex));
  93. break;
  94. case QMetaType::QStringList:
  95. type = LengthDelimited;
  96. result.append(serializeListType(propertyValue.toStringList(), fieldIndex));
  97. break;
  98. case QMetaType::QByteArrayList:
  99. type = LengthDelimited;
  100. result.append(serializeListType(propertyValue.value<QByteArrayList>(), fieldIndex));
  101. break;
  102. case QMetaType::User:
  103. type = LengthDelimited;
  104. result.append(serializeUserType(propertyValue, fieldIndex));
  105. break;
  106. case QMetaType::UInt:
  107. type = Fixed32;
  108. if (isFixed) {
  109. result.append(serializeFixed(propertyValue.toUInt()));
  110. } else {
  111. result.append(serializeVarint(propertyValue.toUInt()));
  112. }
  113. break;
  114. case QMetaType::ULongLong:
  115. type = Fixed64;
  116. if (isFixed) {
  117. result.append(serializeFixed(propertyValue.toULongLong()));
  118. } else {
  119. result.append(serializeVarint(propertyValue.toULongLong()));
  120. }
  121. break;
  122. default:
  123. Q_ASSERT_X(false, staticMetaObject.className(), "Serialization of unknown type is impossible");
  124. }
  125. if (fieldIndex != NotUsedFieldIndex
  126. && type != UnknownWireType) {
  127. result.prepend(encodeHeaderByte(fieldIndex, type));
  128. }
  129. return result;
  130. }
  131. QByteArray serializeLengthDelimited(const QByteArray &data) {
  132. //Varint serialize field size and apply result as starting point
  133. QByteArray result = serializeVarint(static_cast<unsigned int>(data.size()));
  134. result.append(data);
  135. return result;
  136. }
  137. QByteArray serializeUserType(const QVariant &propertyValue, int &fieldIndex) {
  138. int userType = propertyValue.userType();
  139. if (userType == qMetaTypeId<IntList>()) {
  140. return serializeListType(propertyValue.value<IntList>(), fieldIndex);
  141. } else if(userType == qMetaTypeId<FloatList>()) {
  142. return serializeListType(propertyValue.value<FloatList>(), fieldIndex);
  143. } else if(userType == qMetaTypeId<DoubleList>()) {
  144. return serializeListType(propertyValue.value<DoubleList>(), fieldIndex);
  145. } else {
  146. const void *src = propertyValue.constData();
  147. //TODO: each time huge objects will make own copies
  148. //Probably generate fields reflection is better solution
  149. auto value = std::unique_ptr<ProtobufObjectPrivate>(reinterpret_cast<ProtobufObjectPrivate *>(QMetaType::create(userType, src)));
  150. return serializeLengthDelimited(value->serializePrivate());
  151. }
  152. Q_ASSERT_X(QMetaType::UnknownType == userType, staticMetaObject.className(), "Serialization of unknown user type");
  153. return QByteArray();
  154. }
  155. template<typename V,
  156. typename std::enable_if_t<std::is_integral<V>::value
  157. || std::is_floating_point<V>::value, int> = 0>
  158. QByteArray serializeListType(const QList<V> &listValue, int &outFieldIndex) {
  159. if (listValue.count() <= 0) {
  160. outFieldIndex = NotUsedFieldIndex;
  161. return QByteArray();
  162. }
  163. QByteArray serializedList;
  164. for(auto& value : listValue) {
  165. serializedList.append(serializeValue(value, NotUsedFieldIndex));
  166. }
  167. //If internal field type is not LengthDelimited, exact amount of fields to be specified
  168. serializedList.prepend(serializeVarint(static_cast<unsigned int>(serializedList.size())));
  169. return serializedList;
  170. }
  171. template<typename V,
  172. typename std::enable_if_t<std::is_same<V, QString>::value
  173. || std::is_same<V, QByteArray>::value, int> = 0>
  174. QByteArray serializeListType(const QList<V> &listValue, int &outFieldIndex) {
  175. if (listValue.count() <= 0) {
  176. outFieldIndex = NotUsedFieldIndex;
  177. return QByteArray();
  178. }
  179. QByteArray serializedList;
  180. for(auto& value : listValue) {
  181. serializedList.append(serializeValue(value, outFieldIndex));
  182. }
  183. outFieldIndex = NotUsedFieldIndex;
  184. return serializedList;
  185. }
  186. //TODO: This specialization is deprecated and won't be used in future
  187. QByteArray serializeListType(const QVariantList &listValue, int &outFieldIndex)
  188. {
  189. if (listValue.count() <= 0) {
  190. outFieldIndex = NotUsedFieldIndex;
  191. return QByteArray();
  192. }
  193. int itemType = listValue.first().type();
  194. //If internal serialized type is LengthDelimited, need to specify type for each field
  195. int inFieldIndex = (itemType == QMetaType::QString ||
  196. itemType == QMetaType::QByteArray ||
  197. itemType == QMetaType::User) ? outFieldIndex : NotUsedFieldIndex;
  198. QByteArray serializedList;
  199. for(auto& value : listValue) {
  200. serializedList.append(serializeValue(value, inFieldIndex));
  201. }
  202. //If internal field type is not LengthDelimited, exact amount of fields to be specified
  203. if(inFieldIndex == NotUsedFieldIndex) {
  204. serializedList.prepend(serializeVarint(static_cast<unsigned int>(serializedList.size())));
  205. } else {
  206. outFieldIndex = NotUsedFieldIndex;
  207. }
  208. return serializedList;
  209. }
  210. template <typename V,
  211. typename std::enable_if_t<std::is_floating_point<V>::value
  212. || std::is_same<V, unsigned int>::value
  213. || std::is_same<V, qulonglong>::value, int> = 0>
  214. QByteArray serializeFixed(V value) {
  215. //Reserve required amount of bytes
  216. QByteArray result(sizeof(V), '\0');
  217. *(V*)(result.data()) = value;
  218. return result;
  219. }
  220. template <typename V,
  221. typename std::enable_if_t<std::is_signed<V>::value, int> = 0>
  222. QByteArray serializeVarint(V value) {
  223. using UV = typename std::make_unsigned<V>::type;
  224. //Use ZigZag convertion first and apply unsigned variant next
  225. value = (value << 1) ^ (value >> (sizeof(UV) * 8 - 1));
  226. UV uValue = *(UV *)&value;
  227. return serializeVarint(uValue);
  228. }
  229. template <typename V,
  230. typename std::enable_if_t<std::is_unsigned<V>::value, int> = 0>
  231. QByteArray serializeVarint(V value) {
  232. QByteArray result;
  233. //Reserve maximum required amount of bytes
  234. result.reserve(sizeof(V));
  235. while (value > 0) {
  236. //Put first 7 bits to result buffer and mark as not last
  237. result.append(value & 0x7F | 0x80);
  238. //Devide values to chunks of 7 bits, move to next chunk
  239. value >>= 7;
  240. }
  241. //Zero case
  242. if (result.isEmpty()) {
  243. result.append('\0');
  244. }
  245. //Mark last chunk as last
  246. result.data()[result.size() - 1] &= ~0x80;
  247. return result;
  248. }
  249. //####################################################
  250. // Deserialization
  251. //####################################################
  252. void deserializeProperty(WireTypes wireType, const QMetaProperty &metaProperty, QByteArray::const_iterator &it)
  253. {
  254. QVariant newPropertyValue;
  255. int type = metaProperty.type();
  256. switch(type) {
  257. case QMetaType::UInt:
  258. if (wireType == Fixed32) {
  259. newPropertyValue = deserializeFixed<FixedInt32>(it);
  260. } else {
  261. newPropertyValue = deserializeVarint<unsigned int>(it);
  262. }
  263. break;
  264. case QMetaType::ULongLong:
  265. if (wireType == Fixed64) {
  266. newPropertyValue = deserializeFixed<FixedInt64>(it);
  267. } else {
  268. //TODO: deserialize varint
  269. }
  270. break;
  271. case QMetaType::Float:
  272. newPropertyValue = deserializeFixed<float>(it);
  273. break;
  274. case QMetaType::Double:
  275. newPropertyValue = deserializeFixed<double>(it);
  276. break;
  277. case QMetaType::Int:
  278. newPropertyValue = deserializeVarint<int>(it);
  279. break;
  280. case QMetaType::QString:
  281. newPropertyValue = QString::fromUtf8(deserializeLengthDelimited(it));
  282. break;
  283. case QMetaType::QByteArray:
  284. newPropertyValue = deserializeLengthDelimited(it);
  285. break;
  286. case QMetaType::User:
  287. deserializeUserType(metaProperty.userType(), it, newPropertyValue);
  288. break;
  289. case QMetaType::QByteArrayList: {
  290. QByteArrayList currentValue = metaProperty.read(this).value<QByteArrayList>();
  291. currentValue.append(deserializeListType<QByteArray>(it));
  292. metaProperty.write(this, QVariant::fromValue<QByteArrayList>(currentValue));
  293. }
  294. return;
  295. case QMetaType::QStringList: {
  296. QStringList currentValue = metaProperty.read(this).value<QStringList>();
  297. currentValue.append(QString::fromUtf8(deserializeListType<QString>(it)));
  298. metaProperty.write(this, currentValue);
  299. }
  300. return;
  301. default:
  302. break;
  303. }
  304. metaProperty.write(this, newPropertyValue);
  305. }
  306. template <typename V,
  307. typename std::enable_if_t<std::is_floating_point<V>::value
  308. || std::is_same<V, unsigned int>::value
  309. || std::is_same<V, qulonglong>::value, int> = 0>
  310. QVariant deserializeFixed(QByteArray::const_iterator &it) {
  311. QVariant newPropertyValue(QVariant::fromValue(*(V*)it));
  312. it += sizeof(V);
  313. return newPropertyValue;
  314. }
  315. template <typename V,
  316. typename std::enable_if_t<std::is_unsigned<V>::value, int> = 0>
  317. QVariant deserializeVarint(QByteArray::const_iterator &it) {
  318. return QVariant::fromValue(deserializeVarintCommon<V>(it));
  319. }
  320. template <typename V,
  321. typename std::enable_if_t<std::is_signed<V>::value, int> = 0>
  322. QVariant deserializeVarint(QByteArray::const_iterator &it) {
  323. using UV = typename std::make_unsigned<V>::type;
  324. UV unsignedValue = deserializeVarintCommon<UV>(it);
  325. V value = (unsignedValue >> 1) ^ (-(unsignedValue & 1));
  326. return QVariant::fromValue(value);
  327. }
  328. template <typename V>
  329. V deserializeVarintCommon(QByteArray::const_iterator &it) {
  330. V value = 0;
  331. int k = 0;
  332. while((*it) & 0x80) {
  333. value += ((*it) & 0x7f) << (7 * k);
  334. ++k;
  335. ++it;
  336. }
  337. value += ((*it) & 0x7f) << (7 * k);
  338. ++it;
  339. return value;
  340. }
  341. QByteArray deserializeLengthDelimited(QByteArray::const_iterator &it) {
  342. unsigned int length = deserializeVarint<unsigned int>(it).toUInt();
  343. QByteArray result(it, length);
  344. it += length;
  345. return result;
  346. }
  347. void deserializeUserType(int userType, QByteArray::const_iterator& it, QVariant &newValue)
  348. {
  349. if (userType == qMetaTypeId<IntList>()) {
  350. //TODO: implement
  351. } else if(userType == qMetaTypeId<FloatList>()) {
  352. //TODO: implement
  353. } else if(userType == qMetaTypeId<DoubleList>()) {
  354. //TODO: implement
  355. } else {
  356. auto value = reinterpret_cast<ProtobufObjectPrivate *>(QMetaType::create(userType));
  357. value->deserializePrivate(deserializeLengthDelimited(it));
  358. newValue = QVariant(userType, value);
  359. }
  360. }
  361. template <typename V,
  362. typename std::enable_if_t<std::is_same<V, QString>::value
  363. || std::is_same<V, QByteArray>::value, int> = 0>
  364. QByteArray deserializeListType(QByteArray::const_iterator& it) {
  365. return deserializeLengthDelimited(it);
  366. }
  367. public:
  368. virtual QByteArray serializePrivate() = 0;
  369. virtual void deserializePrivate(const QByteArray &data) = 0;
  370. };
  371. template <typename T>
  372. class ProtobufObject : public ProtobufObjectPrivate
  373. {
  374. protected:
  375. QByteArray serializePrivate() override {
  376. return serialize();
  377. }
  378. void deserializePrivate(const QByteArray &data) override {
  379. deserialize(data);
  380. }
  381. public:
  382. explicit ProtobufObject(QObject *parent = nullptr) : ProtobufObjectPrivate(parent) {}
  383. QByteArray serialize() {
  384. QByteArray result;
  385. T *instance = dynamic_cast<T *>(this);
  386. for (auto field : T::propertyOrdering) {
  387. int propertyIndex = field.second;
  388. int fieldIndex = field.first;
  389. ASSERT_FIELD_NUMBER(fieldIndex);
  390. QMetaProperty metaProperty = T::staticMetaObject.property(propertyIndex);
  391. const char *propertyName = metaProperty.name();
  392. const QVariant &propertyValue = instance->property(propertyName);
  393. //TODO: flag isFixed looks ugly. Need to define more effective strategy
  394. //for type detection.
  395. result.append(serializeValue(propertyValue, fieldIndex, QString(metaProperty.typeName()).contains("Fixed")));
  396. }
  397. return result;
  398. }
  399. void deserialize(const QByteArray &array) {
  400. T *instance = dynamic_cast<T *>(this);
  401. for(QByteArray::const_iterator it = array.begin(); it != array.end();) {
  402. //Each iteration we expect iterator is setup to beginning of next chunk
  403. int fieldNumber = NotUsedFieldIndex;
  404. WireTypes wireType = UnknownWireType;
  405. if (!decodeHeaderByte(*it, fieldNumber, wireType)) {
  406. ++it;
  407. qCritical() << "Message received doesn't contains valid header byte. "
  408. "Trying next, but seems stream is broken";
  409. continue;
  410. }
  411. auto propertyNumberIt = T::propertyOrdering.find(fieldNumber);
  412. if (propertyNumberIt == std::end(T::propertyOrdering)) {
  413. ++it;
  414. qCritical() << "Message received contains invalid field number. "
  415. "Trying next, but seems stream is broken";
  416. continue;
  417. }
  418. int propertyIndex = propertyNumberIt->second;
  419. QMetaProperty metaProperty = T::staticMetaObject.property(propertyIndex);
  420. ++it;
  421. deserializeProperty(wireType, metaProperty, it);
  422. }
  423. }
  424. };
  425. }