pairconverter.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include "pairconverter_p.h"
  2. #include "exception.h"
  3. #include "cborserializer.h"
  4. #include <QtCore/QCborArray>
  5. using namespace QtJsonSerializer;
  6. using namespace QtJsonSerializer::TypeConverters;
  7. bool PairConverter::canConvert(int metaTypeId) const
  8. {
  9. const auto extractor = helper()->extractor(metaTypeId);
  10. return extractor && extractor->baseType() == "pair";
  11. }
  12. QList<QCborTag> PairConverter::allowedCborTags(int metaTypeId) const
  13. {
  14. Q_UNUSED(metaTypeId)
  15. return {NoTag, static_cast<QCborTag>(CborSerializer::Pair)};
  16. }
  17. QList<QCborValue::Type> PairConverter::allowedCborTypes(int metaTypeId, QCborTag tag) const
  18. {
  19. Q_UNUSED(metaTypeId)
  20. Q_UNUSED(tag)
  21. return {QCborValue::Array};
  22. }
  23. QCborValue PairConverter::serialize(int propertyType, const QVariant &value) const
  24. {
  25. const auto extractor = helper()->extractor(propertyType);
  26. if (!extractor) {
  27. throw SerializationException(QByteArray("Failed to get extractor for type ") +
  28. QMetaTypeName(propertyType) +
  29. QByteArray(". Make shure to register pair types via QJsonSerializer::registerPairConverters"));
  30. }
  31. const auto subTypes = extractor->subtypes();
  32. return {
  33. static_cast<QCborTag>(CborSerializer::Pair),
  34. QCborArray {
  35. helper()->serializeSubtype(subTypes[0], extractor->extract(value, 0), "first"),
  36. helper()->serializeSubtype(subTypes[1], extractor->extract(value, 1), "second")
  37. }
  38. };
  39. }
  40. QVariant PairConverter::deserializeCbor(int propertyType, const QCborValue &value, QObject *parent) const
  41. {
  42. const auto extractor = helper()->extractor(propertyType);
  43. if (!extractor) {
  44. throw DeserializationException(QByteArray("Failed to get extractor for type ") +
  45. QMetaTypeName(propertyType) +
  46. QByteArray(". Make shure to register pair types via QJsonSerializer::registerPairConverters"));
  47. }
  48. const auto array = (value.isTag() ? value.taggedValue() : value).toArray();
  49. if (array.size() != 2)
  50. throw DeserializationException("CBOR/JSON array must have exactly 2 elements to be read as a pair");
  51. const auto subTypes = extractor->subtypes();
  52. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  53. QVariant resPair{propertyType, nullptr};
  54. #else
  55. QVariant resPair{QMetaType(propertyType), nullptr};
  56. #endif
  57. extractor->emplace(resPair, helper()->deserializeSubtype(subTypes[0], array[0], parent, "first"), 0);
  58. extractor->emplace(resPair, helper()->deserializeSubtype(subTypes[1], array[1], parent, "second"), 1);
  59. return resPair;
  60. }